diff options
22 files changed, 702 insertions, 292 deletions
@@ -357,6 +357,30 @@ the common tasks and can be called on to run the main aspects of all the sub-scr <echo>Tests will now run against OpenJDK7</echo> <antcall target="-createEclipseLaunchForTestEnvironmentIfEclipseProject" /> </target> + + <target name="setupJavaOracle7TestEnvironment" description="Sets up the test so that 'ant test' will test against OpenJDK7."> + <mkdir dir="lib/oracleJDK7Environment" /> + <propertyfile file="testenvironment.properties"> + <entry key="test.location.javac" value="lib/oracleJDK7Environment/tools-jdk7.jar" /> + <entry key="test.location.bootclasspath" value="lib/oracleJDK7Environment/rt-oraclejdk7.jar" /> + <entry key="test.location.name" value="OracleJDK7" /> + </propertyfile> + <echo>Tests will now run against Oracle JDK7</echo> + <antcall target="-createEclipseLaunchForTestEnvironmentIfEclipseProject" /> + </target> + + <target name="setupJavaOracle8TestEnvironment" description="Sets up the test so that 'ant test' will test against OpenJDK8."> + <mkdir dir="lib/oracleJDK8Environment" /> + <!--get src="http://projectlombok.org/ivyrepo/langtools/javac-1.7.0.jar" dest="lib/openJDK7Environment/javac7.jar" verbose="true" usetimestamp="true" /--> + <!--get src="http://projectlombok.org/ivyrepo/langtools/rt-openjdk7.jar" dest="lib/openJDK7Environment/rt-openjdk7.jar" verbose="true" usetimestamp="true" /--> + <propertyfile file="testenvironment.properties"> + <entry key="test.location.javac" value="lib/oracleJDK8Environment/tools-jdk8.jar" /> + <entry key="test.location.bootclasspath" value="lib/oracleJDK8Environment/rt-oraclejdk8.jar" /> + <entry key="test.location.name" value="OracleJDK8" /> + </propertyfile> + <echo>Tests will now run against Oracle JDK8</echo> + <antcall target="-createEclipseLaunchForTestEnvironmentIfEclipseProject" /> + </target> <target name="-failIfNoTestEnvironmentProperties" unless="test.location.javac"> <fail>ERROR: No test environment set up. diff --git a/src/core/lombok/javac/FindTypeVarScanner.java b/src/core/lombok/javac/FindTypeVarScanner.java index b1b8e525..7c7d9d50 100644 --- a/src/core/lombok/javac/FindTypeVarScanner.java +++ b/src/core/lombok/javac/FindTypeVarScanner.java @@ -88,7 +88,7 @@ public class FindTypeVarScanner extends AbstractTypeVisitor6<Void, Void> { @Override public Void visitTypeVariable(TypeVariable t, Void p) { Name name = null; try { - name = ((Type)t).tsym.name; + name = ((Type) t).tsym.name; } catch (NullPointerException e) {} if (name != null) typeVariables.add(name.toString()); subVisit(t.getLowerBound()); diff --git a/src/core/lombok/javac/Javac6BasedLombokOptions.java b/src/core/lombok/javac/Javac6BasedLombokOptions.java new file mode 100644 index 00000000..871e41c4 --- /dev/null +++ b/src/core/lombok/javac/Javac6BasedLombokOptions.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2013 The Project Lombok Authors. + * + * 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.OptionName; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Options; + +public class Javac6BasedLombokOptions extends LombokOptions { + public static Javac6BasedLombokOptions replaceWithDelombokOptions(Context context) { + Options options = Options.instance(context); + context.put(optionsKey, (Options)null); + Javac6BasedLombokOptions result = new Javac6BasedLombokOptions(context); + result.putAll(options); + return result; + } + + private Javac6BasedLombokOptions(Context context) { + super(context); + } + + @Override public void putJavacOption(String optionName, String value) { + put(OptionName.valueOf(optionName), value); + } +} diff --git a/src/core/lombok/javac/Javac8BasedLombokOptions.java b/src/core/lombok/javac/Javac8BasedLombokOptions.java new file mode 100644 index 00000000..3fdea890 --- /dev/null +++ b/src/core/lombok/javac/Javac8BasedLombokOptions.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2013 The Project Lombok Authors. + * + * 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.Option; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Options; + +public class Javac8BasedLombokOptions extends LombokOptions { + public static Javac8BasedLombokOptions replaceWithDelombokOptions(Context context) { + Options options = Options.instance(context); + context.put(optionsKey, (Options)null); + Javac8BasedLombokOptions result = new Javac8BasedLombokOptions(context); + result.putAll(options); + return result; + } + + private Javac8BasedLombokOptions(Context context) { + super(context); + } + + @Override public void putJavacOption(String optionName, String value) { + String optionText = Option.valueOf(optionName).text; + put(optionText, value); + } +} diff --git a/src/core/lombok/javac/JavacResolution.java b/src/core/lombok/javac/JavacResolution.java index 0a21aa58..82ce0cb8 100644 --- a/src/core/lombok/javac/JavacResolution.java +++ b/src/core/lombok/javac/JavacResolution.java @@ -43,7 +43,6 @@ import com.sun.tools.javac.code.Type.ArrayType; import com.sun.tools.javac.code.Type.CapturedType; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type.WildcardType; -import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.comp.Attr; import com.sun.tools.javac.comp.AttrContext; @@ -419,8 +418,8 @@ public class JavacResolution { TreeMaker maker = ast.getTreeMaker(); - if (type.tag == CTC_BOT) return createJavaLangObject(ast); - if (type.tag == CTC_VOID) return allowVoid ? primitiveToJCTree(type.getKind(), maker) : createJavaLangObject(ast); + if (Javac.compareCTC(type.tag, CTC_BOT)) return createJavaLangObject(ast); + if (Javac.compareCTC(type.tag, CTC_VOID)) return allowVoid ? primitiveToJCTree(type.getKind(), maker) : createJavaLangObject(ast); if (type.isPrimitive()) return primitiveToJCTree(type.getKind(), maker); if (type.isErroneous()) throw new TypeNotConvertibleException("Type cannot be resolved"); @@ -434,8 +433,8 @@ public class JavacResolution { if (symbol.name.length() == 0) { // Anonymous inner class if (type instanceof ClassType) { - List<Type> ifaces = ((ClassType)type).interfaces_field; - Type supertype = ((ClassType)type).supertype_field; + List<Type> ifaces = ((ClassType) type).interfaces_field; + Type supertype = ((ClassType) type).supertype_field; if (ifaces != null && ifaces.length() == 1) { return typeToJCTree(ifaces.get(0), ast, allowCompound, allowVoid); } @@ -454,7 +453,7 @@ public class JavacResolution { upper = type.getUpperBound(); } if (allowCompound) { - if (lower == null || lower.tag == CTC_BOT) { + if (lower == null || Javac.compareCTC(lower.tag, CTC_BOT)) { if (upper == null || upper.toString().equals("java.lang.Object")) { return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null); } @@ -479,7 +478,7 @@ public class JavacResolution { String qName; if (symbol.isLocal()) { qName = symbol.getSimpleName().toString(); - } else if (symbol.type != null && symbol.type.getEnclosingType() != null && symbol.type.getEnclosingType().tag == TypeTags.CLASS) { + } else if (symbol.type != null && symbol.type.getEnclosingType() != null && Javac.compareCTC(symbol.type.getEnclosingType().tag, Javac.getTypeTag("CLASS"))) { replacement = typeToJCTree0(type.getEnclosingType(), ast, false, false); qName = symbol.getSimpleName().toString(); } else { @@ -515,23 +514,23 @@ public class JavacResolution { private static JCExpression primitiveToJCTree(TypeKind kind, TreeMaker maker) throws TypeNotConvertibleException { switch (kind) { case BYTE: - return maker.TypeIdent(CTC_BYTE); + return Javac.makeTypeIdent(maker, CTC_BYTE); case CHAR: - return maker.TypeIdent(CTC_CHAR); + return Javac.makeTypeIdent(maker, CTC_CHAR); case SHORT: - return maker.TypeIdent(CTC_SHORT); + return Javac.makeTypeIdent(maker, CTC_SHORT); case INT: - return maker.TypeIdent(CTC_INT); + return Javac.makeTypeIdent(maker, CTC_INT); case LONG: - return maker.TypeIdent(CTC_LONG); + return Javac.makeTypeIdent(maker, CTC_LONG); case FLOAT: - return maker.TypeIdent(CTC_FLOAT); + return Javac.makeTypeIdent(maker, CTC_FLOAT); case DOUBLE: - return maker.TypeIdent(CTC_DOUBLE); + return Javac.makeTypeIdent(maker, CTC_DOUBLE); case BOOLEAN: - return maker.TypeIdent(CTC_BOOLEAN); + return Javac.makeTypeIdent(maker, CTC_BOOLEAN); case VOID: - return maker.TypeIdent(CTC_VOID); + return Javac.makeTypeIdent(maker, CTC_VOID); case NULL: case NONE: case OTHER: diff --git a/src/core/lombok/javac/LombokOptions.java b/src/core/lombok/javac/LombokOptions.java index 1a73a8cc..f1567e9d 100644 --- a/src/core/lombok/javac/LombokOptions.java +++ b/src/core/lombok/javac/LombokOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 The Project Lombok Authors. + * Copyright (C) 2010-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -28,18 +28,10 @@ import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Options; -public class LombokOptions extends Options { +public abstract class LombokOptions extends Options { private boolean deleteLombokAnnotations = true; private final Set<JCCompilationUnit> changed = new HashSet<JCCompilationUnit>(); - public static LombokOptions replaceWithDelombokOptions(Context context) { - Options options = Options.instance(context); - context.put(optionsKey, (Options)null); - LombokOptions result = new LombokOptions(context); - result.putAll(options); - return result; - } - public boolean isChanged(JCCompilationUnit ast) { return changed.contains(ast); } @@ -54,7 +46,9 @@ public class LombokOptions extends Options { return (options instanceof LombokOptions) && ((LombokOptions) options).deleteLombokAnnotations; } - private LombokOptions(Context context) { + protected LombokOptions(Context context) { super(context); } + + public abstract void putJavacOption(String optionName, String value); } diff --git a/src/core/lombok/javac/handlers/HandleBuilder.java b/src/core/lombok/javac/handlers/HandleBuilder.java index 6422f5ed..e60819da 100644 --- a/src/core/lombok/javac/handlers/HandleBuilder.java +++ b/src/core/lombok/javac/handlers/HandleBuilder.java @@ -239,7 +239,7 @@ public class HandleBuilder extends JavacAnnotationHandler<Builder> { JCExpression fn = maker.Select(maker.Ident(((JCClassDecl) type.up().get()).name), staticName); call = maker.Apply(typeParams.toList(), fn, args.toList()); - if (returnType instanceof JCPrimitiveTypeTree && ((JCPrimitiveTypeTree) returnType).typetag == CTC_VOID) { + if (returnType instanceof JCPrimitiveTypeTree && compareCTC(getTypeTag((JCPrimitiveTypeTree) returnType), CTC_VOID)) { statement = maker.Exec(call); } else { statement = maker.Return(call); diff --git a/src/core/lombok/javac/handlers/HandleCleanup.java b/src/core/lombok/javac/handlers/HandleCleanup.java index 09b4faee..790d8964 100644 --- a/src/core/lombok/javac/handlers/HandleCleanup.java +++ b/src/core/lombok/javac/handlers/HandleCleanup.java @@ -26,12 +26,12 @@ import static lombok.javac.Javac.*; import lombok.Cleanup; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; +import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; -import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCAssign; @@ -120,7 +120,7 @@ public class HandleCleanup extends JavacAnnotationHandler<Cleanup> { maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil()))); JCMethodInvocation preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name)); - JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null)); + JCBinary isNull = Javac.makeBinary(maker, CTC_NOT_EQUAL, preventNullAnalysis, Javac.makeLiteral(maker, CTC_BOT, null)); JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null); @@ -141,7 +141,7 @@ public class HandleCleanup extends JavacAnnotationHandler<Cleanup> { private JCMethodInvocation preventNullAnalysis(TreeMaker maker, JavacNode node, JCExpression expression) { JCMethodInvocation singletonList = maker.Apply(List.<JCExpression>nil(), chainDotsString(node, "java.util.Collections.singletonList"), List.of(expression)); - JCMethodInvocation cleanedExpr = maker.Apply(List.<JCExpression>nil(), maker.Select(singletonList, node.toName("get")) , List.<JCExpression>of(maker.Literal(TypeTags.INT, 0))); + JCMethodInvocation cleanedExpr = maker.Apply(List.<JCExpression>nil(), maker.Select(singletonList, node.toName("get")) , List.<JCExpression>of(Javac.makeLiteral(maker, CTC_INT, 0))); return cleanedExpr; } diff --git a/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java b/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java index 3b1e226f..741e7e21 100644 --- a/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java +++ b/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java @@ -31,6 +31,7 @@ import java.util.Collections; import lombok.EqualsAndHashCode; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; +import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; @@ -40,7 +41,6 @@ import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; @@ -223,7 +223,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); - JCExpression returnType = maker.TypeIdent(CTC_INT); + JCExpression returnType = Javac.makeTypeIdent(maker, CTC_INT); ListBuffer<JCStatement> statements = ListBuffer.lb(); Name primeName = typeNode.toName(PRIME_NAME); @@ -231,12 +231,12 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas /* final int PRIME = 31; */ { if (!fields.isEmpty() || callSuper) { statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), - primeName, maker.TypeIdent(CTC_INT), maker.Literal(31))); + primeName, Javac.makeTypeIdent(maker, CTC_INT), maker.Literal(31))); } } /* int result = 1; */ { - statements.append(maker.VarDef(maker.Modifiers(0), resultName, maker.TypeIdent(CTC_INT), maker.Literal(1))); + statements.append(maker.VarDef(maker.Modifiers(0), resultName, Javac.makeTypeIdent(maker, CTC_INT), maker.Literal(1))); } if (callSuper) { @@ -258,7 +258,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas break; case LONG: { Name dollarFieldName = dollar.append(((JCVariableDecl)fieldNode.get()).name); - statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), dollarFieldName, maker.TypeIdent(TypeTags.LONG), fieldAccessor)); + statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), dollarFieldName, Javac.makeTypeIdent(maker, CTC_LONG), fieldAccessor)); statements.append(createResultCalculation(typeNode, longToIntForHashCode(maker, maker.Ident(dollarFieldName), maker.Ident(dollarFieldName)))); } break; @@ -276,7 +276,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas List.<JCExpression>nil(), chainDots(typeNode, "java", "lang", "Double", "doubleToLongBits"), List.of(fieldAccessor)); - statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), dollarFieldName, maker.TypeIdent(TypeTags.LONG), init)); + statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), dollarFieldName, Javac.makeTypeIdent(maker, CTC_LONG), init)); statements.append(createResultCalculation(typeNode, longToIntForHashCode(maker, maker.Ident(dollarFieldName), maker.Ident(dollarFieldName)))); } break; @@ -306,7 +306,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCExpression hcCall = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(dollarFieldName), typeNode.toName("hashCode")), List.<JCExpression>nil()); - JCExpression thisEqualsNull = maker.Binary(CTC_EQUAL, maker.Ident(dollarFieldName), maker.Literal(CTC_BOT, null)); + JCExpression thisEqualsNull = Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(dollarFieldName), Javac.makeLiteral(maker, CTC_BOT, null)); statements.append(createResultCalculation(typeNode, maker.Conditional(thisEqualsNull, maker.Literal(0), hcCall))); } } @@ -324,17 +324,17 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas /* result = result * PRIME + (expr); */ TreeMaker maker = typeNode.getTreeMaker(); Name resultName = typeNode.toName(RESULT_NAME); - JCExpression mult = maker.Binary(CTC_MUL, maker.Ident(resultName), maker.Ident(typeNode.toName(PRIME_NAME))); - JCExpression add = maker.Binary(CTC_PLUS, mult, expr); + JCExpression mult = Javac.makeBinary(maker, CTC_MUL, maker.Ident(resultName), maker.Ident(typeNode.toName(PRIME_NAME))); + JCExpression add = Javac.makeBinary(maker, CTC_PLUS, mult, expr); return maker.Exec(maker.Assign(maker.Ident(resultName), add)); } /** The 2 references must be clones of each other. */ private JCExpression longToIntForHashCode(TreeMaker maker, JCExpression ref1, JCExpression ref2) { /* (int)(ref >>> 32 ^ ref) */ - JCExpression shift = maker.Binary(CTC_UNSIGNED_SHIFT_RIGHT, ref1, maker.Literal(32)); - JCExpression xorBits = maker.Binary(CTC_BITXOR, shift, ref2); - return maker.TypeCast(maker.TypeIdent(CTC_INT), xorBits); + JCExpression shift = Javac.makeBinary(maker, CTC_UNSIGNED_SHIFT_RIGHT, ref1, maker.Literal(32)); + JCExpression xorBits = Javac.makeBinary(maker, CTC_BITXOR, shift, ref2); + return maker.TypeCast(Javac.makeTypeIdent(maker, CTC_INT), xorBits); } private JCExpression createTypeReference(JavacNode type) { @@ -368,18 +368,19 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); JCExpression objectType = chainDots(typeNode, "java", "lang", "Object"); - JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN); + JCExpression returnType = Javac.makeTypeIdent(maker, CTC_BOOLEAN); ListBuffer<JCStatement> statements = ListBuffer.lb(); final List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(Flags.FINAL), oName, objectType, null)); /* if (o == this) return true; */ { - statements.append(maker.If(maker.Binary(CTC_EQUAL, maker.Ident(oName), + statements.append(maker.If(Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(oName), maker.Ident(thisName)), returnBool(maker, true), null)); } /* if (!(o instanceof Outer.Inner.MyType) return false; */ { - JCUnary notInstanceOf = maker.Unary(CTC_NOT, maker.TypeTest(maker.Ident(oName), createTypeReference(typeNode))); + + JCUnary notInstanceOf = Javac.makeUnary(maker, CTC_NOT, maker.TypeTest(maker.Ident(oName), createTypeReference(typeNode))); statements.append(maker.If(notInstanceOf, returnBool(maker, false), null)); } @@ -414,7 +415,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCExpression equalityCheck = maker.Apply(exprNil, maker.Select(maker.Ident(otherName), typeNode.toName("canEqual")), List.of(castThisRef)); - statements.append(maker.If(maker.Unary(CTC_NOT, equalityCheck), returnBool(maker, false), null)); + statements.append(maker.If(Javac.makeUnary(maker, CTC_NOT, equalityCheck), returnBool(maker, false), null)); } } @@ -423,7 +424,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("equals")), List.<JCExpression>of(maker.Ident(oName))); - JCUnary superNotEqual = maker.Unary(CTC_NOT, callToSuper); + JCUnary superNotEqual = Javac.makeUnary(maker, CTC_NOT, callToSuper); statements.append(maker.If(superNotEqual, returnBool(maker, false), null)); } @@ -446,7 +447,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas default: /* if (this.fieldName != other.fieldName) return false; */ statements.append( - maker.If(maker.Binary(CTC_NOT_EQUAL, thisFieldAccessor, otherFieldAccessor), returnBool(maker, false), null)); + maker.If(Javac.makeBinary(maker, CTC_NOT_EQUAL, thisFieldAccessor, otherFieldAccessor), returnBool(maker, false), null)); break; } } else if (fType instanceof JCArrayTypeTree) { @@ -457,7 +458,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCExpression eqMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepEquals ? "deepEquals" : "equals"); List<JCExpression> args = List.of(thisFieldAccessor, otherFieldAccessor); - statements.append(maker.If(maker.Unary(CTC_NOT, + statements.append(maker.If(Javac.makeUnary(maker, CTC_NOT, maker.Apply(List.<JCExpression>nil(), eqMethod, args)), returnBool(maker, false), null)); } else /* objects */ { /* final java.lang.Object this$fieldName = this.fieldName; */ @@ -470,12 +471,12 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), thisDollarFieldName, chainDots(typeNode, "java", "lang", "Object"), thisFieldAccessor)); statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), otherDollarFieldName, chainDots(typeNode, "java", "lang", "Object"), otherFieldAccessor)); - JCExpression thisEqualsNull = maker.Binary(CTC_EQUAL, maker.Ident(thisDollarFieldName), maker.Literal(CTC_BOT, null)); - JCExpression otherNotEqualsNull = maker.Binary(CTC_NOT_EQUAL, maker.Ident(otherDollarFieldName), maker.Literal(CTC_BOT, null)); + JCExpression thisEqualsNull = Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(thisDollarFieldName), Javac.makeLiteral(maker, CTC_BOT, null)); + JCExpression otherNotEqualsNull = Javac.makeBinary(maker, CTC_NOT_EQUAL, maker.Ident(otherDollarFieldName), Javac.makeLiteral(maker, CTC_BOT, null)); JCExpression thisEqualsThat = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(thisDollarFieldName), typeNode.toName("equals")), List.<JCExpression>of(maker.Ident(otherDollarFieldName))); - JCExpression fieldsAreNotEqual = maker.Conditional(thisEqualsNull, otherNotEqualsNull, maker.Unary(CTC_NOT, thisEqualsThat)); + JCExpression fieldsAreNotEqual = maker.Conditional(thisEqualsNull, otherNotEqualsNull, Javac.makeUnary(maker, CTC_NOT, thisEqualsThat)); statements.append(maker.If(fieldsAreNotEqual, returnBool(maker, false), null)); } } @@ -496,7 +497,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas TreeMaker maker = typeNode.getTreeMaker(); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.<JCAnnotation>nil()); - JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN); + JCExpression returnType = Javac.makeTypeIdent(maker, CTC_BOOLEAN); Name canEqualName = typeNode.toName("canEqual"); JCExpression objectType = chainDots(typeNode, "java", "lang", "Object"); Name otherName = typeNode.toName("other"); @@ -513,12 +514,12 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */ JCExpression clazz = chainDots(node, "java", "lang", isDouble ? "Double" : "Float"); List<JCExpression> args = List.of(thisDotField, otherDotField); - JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply( + JCBinary compareCallEquals0 = Javac.makeBinary(maker, CTC_NOT_EQUAL, maker.Apply( List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0)); return maker.If(compareCallEquals0, returnBool(maker, false), null); } private JCStatement returnBool(TreeMaker maker, boolean bool) { - return maker.Return(maker.Literal(CTC_BOOLEAN, bool ? 1 : 0)); + return maker.Return(Javac.makeLiteral(maker, CTC_BOOLEAN, bool ? 1 : 0)); } } diff --git a/src/core/lombok/javac/handlers/HandleGetter.java b/src/core/lombok/javac/handlers/HandleGetter.java index 51642f86..c5ec6f60 100644 --- a/src/core/lombok/javac/handlers/HandleGetter.java +++ b/src/core/lombok/javac/handlers/HandleGetter.java @@ -35,6 +35,7 @@ import lombok.Getter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; +import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; @@ -288,9 +289,9 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { private static final String JLO = "java.lang.Object"; private static final List<JCExpression> NIL_EXPRESSION = List.nil(); - private static final java.util.Map<Integer, String> TYPE_MAP; + private static final java.util.Map<Object, String> TYPE_MAP; static { - Map<Integer, String> m = new HashMap<Integer, String>(); + Map<Object, String> m = new HashMap<Object, String>(); m.put(CTC_INT, "java.lang.Integer"); m.put(CTC_DOUBLE, "java.lang.Double"); m.put(CTC_FLOAT, "java.lang.Float"); @@ -373,7 +374,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { } /* [ELSE] value = actualValue == null ? this.fieldName : actualValue; */ { if (!isPrimitive) { - JCExpression actualValueIsNull = maker.Binary(CTC_EQUAL, maker.Ident(actualValueName), maker.Literal(CTC_BOT, null)); + JCExpression actualValueIsNull = Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(actualValueName), Javac.makeLiteral(maker, CTC_BOT, null)); JCExpression thisDotFieldName = createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD); JCExpression ternary = maker.Conditional(actualValueIsNull, thisDotFieldName, maker.Ident(actualValueName)); JCStatement statement = maker.Exec(maker.Assign(maker.Ident(valueName), ternary)); @@ -385,7 +386,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { innerIfStatements.append(statement); } - JCBinary isNull = maker.Binary(CTC_EQUAL, maker.Ident(valueName), maker.Literal(CTC_BOT, null)); + JCBinary isNull = Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(valueName), Javac.makeLiteral(maker, CTC_BOT, null)); JCIf ifStatement = maker.If(isNull, maker.Block(0, innerIfStatements.toList()), null); synchronizedStatements.append(ifStatement); } @@ -393,7 +394,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { synchronizedStatement = maker.Synchronized(createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD), maker.Block(0, synchronizedStatements.toList())); } - JCBinary isNull = maker.Binary(CTC_EQUAL, maker.Ident(valueName), maker.Literal(CTC_BOT, null)); + JCBinary isNull = Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(valueName), Javac.makeLiteral(maker, CTC_BOT, null)); JCIf ifStatement = maker.If(isNull, maker.Block(0, List.<JCStatement>of(synchronizedStatement)), null); statements.append(ifStatement); } @@ -404,8 +405,8 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { } /* [ELSE] return (BoxedValueType) (value == this.fieldName ? null : value); */ { if (!isPrimitive) { - JCExpression valueEqualsSelf = maker.Binary(CTC_EQUAL, maker.Ident(valueName), createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD)); - JCExpression ternary = maker.Conditional(valueEqualsSelf, maker.Literal(CTC_BOT, null), maker.Ident(valueName)); + JCExpression valueEqualsSelf = Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(valueName), createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD)); + JCExpression ternary = maker.Conditional(valueEqualsSelf, Javac.makeLiteral(maker, CTC_BOT, null), maker.Ident(valueName)); JCExpression typeCast = maker.TypeCast(copyOfBoxedFieldType, maker.Parens(ternary)); statements.append(maker.Return(typeCast)); } diff --git a/src/core/lombok/javac/handlers/HandleSetter.java b/src/core/lombok/javac/handlers/HandleSetter.java index 282e6c2f..c3ee10a3 100644 --- a/src/core/lombok/javac/handlers/HandleSetter.java +++ b/src/core/lombok/javac/handlers/HandleSetter.java @@ -26,15 +26,12 @@ import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collection; -import javax.lang.model.type.NoType; -import javax.lang.model.type.TypeKind; -import javax.lang.model.type.TypeVisitor; - import lombok.AccessLevel; import lombok.Setter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; +import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; @@ -42,7 +39,6 @@ import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCAssign; @@ -232,7 +228,7 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { if (methodType == null) { //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6. - methodType = treeMaker.Type(new JCNoType(CTC_VOID)); + methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID)); shouldReturnThis = false; } @@ -257,22 +253,4 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { copyJavadoc(field, decl, CopyJavadoc.SETTER); return decl; } - - private static class JCNoType extends Type implements NoType { - public JCNoType(int tag) { - super(tag, null); - } - - @Override - public TypeKind getKind() { - if (tag == CTC_VOID) return TypeKind.VOID; - if (tag == CTC_NONE) return TypeKind.NONE; - throw new AssertionError("Unexpected tag: " + tag); - } - - @Override - public <R, P> R accept(TypeVisitor<R, P> v, P p) { - return v.visitNoType(this, p); - } - } } diff --git a/src/core/lombok/javac/handlers/HandleSynchronized.java b/src/core/lombok/javac/handlers/HandleSynchronized.java index 2bca49e9..2737eeb2 100644 --- a/src/core/lombok/javac/handlers/HandleSynchronized.java +++ b/src/core/lombok/javac/handlers/HandleSynchronized.java @@ -26,6 +26,7 @@ import static lombok.javac.handlers.JavacHandlerUtil.*; import lombok.Synchronized; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; +import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult; @@ -87,7 +88,7 @@ public class HandleSynchronized extends JavacAnnotationHandler<Synchronized> { JCExpression objectType = chainDots(methodNode, ast.pos, "java", "lang", "Object"); //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable! JCNewArray newObjectArray = maker.NewArray(chainDots(methodNode, ast.pos, "java", "lang", "Object"), - List.<JCExpression>of(maker.Literal(CTC_INT, 0)), null); + List.<JCExpression>of(Javac.makeLiteral(maker, CTC_INT, 0)), null); JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef( maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)), methodNode.toName(lockName), objectType, newObjectArray), ast); diff --git a/src/core/lombok/javac/handlers/HandleToString.java b/src/core/lombok/javac/handlers/HandleToString.java index 333393da..8297a4db 100644 --- a/src/core/lombok/javac/handlers/HandleToString.java +++ b/src/core/lombok/javac/handlers/HandleToString.java @@ -29,6 +29,7 @@ import java.util.Collection; import lombok.ToString; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; +import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; @@ -195,7 +196,7 @@ public class HandleToString extends JavacAnnotationHandler<ToString> { JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")), List.<JCExpression>nil()); - current = maker.Binary(CTC_PLUS, current, callToSuper); + current = Javac.makeBinary(maker, CTC_PLUS, current, callToSuper); first = false; } @@ -219,21 +220,21 @@ public class HandleToString extends JavacAnnotationHandler<ToString> { } else expr = fieldAccessor; if (first) { - current = maker.Binary(CTC_PLUS, current, expr); + current = Javac.makeBinary(maker, CTC_PLUS, current, expr); first = false; continue; } if (includeFieldNames) { - current = maker.Binary(CTC_PLUS, current, maker.Literal(infix + fieldNode.getName() + "=")); + current = Javac.makeBinary(maker, CTC_PLUS, current, maker.Literal(infix + fieldNode.getName() + "=")); } else { - current = maker.Binary(CTC_PLUS, current, maker.Literal(infix)); + current = Javac.makeBinary(maker, CTC_PLUS, current, maker.Literal(infix)); } - current = maker.Binary(CTC_PLUS, current, expr); + current = Javac.makeBinary(maker, CTC_PLUS, current, expr); } - if (!first) current = maker.Binary(CTC_PLUS, current, maker.Literal(suffix)); + if (!first) current = Javac.makeBinary(maker, CTC_PLUS, current, maker.Literal(suffix)); JCStatement returnStatement = maker.Return(current); diff --git a/src/core/lombok/javac/handlers/HandleWither.java b/src/core/lombok/javac/handlers/HandleWither.java index b3f218b8..514e27dd 100644 --- a/src/core/lombok/javac/handlers/HandleWither.java +++ b/src/core/lombok/javac/handlers/HandleWither.java @@ -31,6 +31,7 @@ import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; import lombok.experimental.Wither; +import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil.CopyJavadoc; @@ -240,7 +241,7 @@ public class HandleWither extends JavacAnnotationHandler<Wither> { } JCNewClass newClass = maker.NewClass(null, List.<JCExpression>nil(), selfType, args.toList(), null); - JCExpression identityCheck = maker.Binary(CTC_EQUAL, createFieldAccessor(maker, field, FieldAccess.ALWAYS_FIELD), maker.Ident(fieldDecl.name)); + JCExpression identityCheck = Javac.makeBinary(maker, CTC_EQUAL, createFieldAccessor(maker, field, FieldAccess.ALWAYS_FIELD), maker.Ident(fieldDecl.name)); JCConditional conditional = maker.Conditional(identityCheck, maker.Ident(field.toName("this")), newClass); JCReturn returnStatement = maker.Return(conditional); diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index d7d29da2..211f5d36 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -44,6 +44,7 @@ import lombok.core.AnnotationValues.AnnotationValue; import lombok.core.TransformationsUtil; import lombok.core.TypeResolver; import lombok.experimental.Accessors; +import lombok.javac.Javac; import lombok.javac.JavacNode; import com.sun.tools.javac.code.BoundKind; @@ -940,15 +941,15 @@ public class JavacHandlerUtil { * Generates a new statement that checks if the given variable is null, and if so, throws a {@code NullPointerException} with the * variable name as message. */ - public static JCStatement generateNullCheck(TreeMaker treeMaker, JavacNode variable) { + public static JCStatement generateNullCheck(TreeMaker maker, JavacNode variable) { JCVariableDecl varDecl = (JCVariableDecl) variable.get(); if (isPrimitive(varDecl.vartype)) return null; Name fieldName = varDecl.name; JCExpression npe = chainDots(variable, "java", "lang", "NullPointerException"); - JCTree exception = treeMaker.NewClass(null, List.<JCExpression>nil(), npe, List.<JCExpression>of(treeMaker.Literal(fieldName.toString())), null); - JCStatement throwStatement = treeMaker.Throw(exception); - JCBlock throwBlock = treeMaker.Block(0, List.of(throwStatement)); - return treeMaker.If(treeMaker.Binary(CTC_EQUAL, treeMaker.Ident(fieldName), treeMaker.Literal(CTC_BOT, null)), throwBlock, null); + JCTree exception = maker.NewClass(null, List.<JCExpression>nil(), npe, List.<JCExpression>of(maker.Literal(fieldName.toString())), null); + JCStatement throwStatement = maker.Throw(exception); + JCBlock throwBlock = maker.Block(0, List.of(throwStatement)); + return maker.If(Javac.makeBinary(maker, CTC_EQUAL, maker.Ident(fieldName), Javac.makeLiteral(maker, CTC_BOT, null)), throwBlock, null); } /** diff --git a/src/core/lombok/javac/handlers/NonNullHandler.java b/src/core/lombok/javac/handlers/NonNullHandler.java index 415d6032..d74fb55d 100644 --- a/src/core/lombok/javac/handlers/NonNullHandler.java +++ b/src/core/lombok/javac/handlers/NonNullHandler.java @@ -138,10 +138,10 @@ public class NonNullHandler extends JavacAnnotationHandler<NonNull> { while (cond instanceof JCParens) cond = ((JCParens) cond).expr; if (!(cond instanceof JCBinary)) return null; JCBinary bin = (JCBinary) cond; - if (getTag(bin) != CTC_EQUAL) return null; + if (compareCTC(getTag(bin), CTC_EQUAL)) return null; if (!(bin.lhs instanceof JCIdent)) return null; if (!(bin.rhs instanceof JCLiteral)) return null; - if (((JCLiteral) bin.rhs).typetag != CTC_BOT) return null; + if (compareCTC(getTypeTag((JCLiteral) bin.rhs), CTC_BOT)) return null; return ((JCIdent) bin.lhs).name.toString(); } } diff --git a/src/delombok/lombok/delombok/Delombok.java b/src/delombok/lombok/delombok/Delombok.java index f4e02786..7291ac29 100644 --- a/src/delombok/lombok/delombok/Delombok.java +++ b/src/delombok/lombok/delombok/Delombok.java @@ -52,7 +52,6 @@ import lombok.javac.LombokOptions; import com.sun.tools.javac.comp.Todo; import com.sun.tools.javac.main.JavaCompiler; -import com.sun.tools.javac.main.OptionName; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.zwitserloot.cmdreader.CmdReader; @@ -359,11 +358,11 @@ public class Delombok { } public boolean delombok() throws IOException { - LombokOptions options = LombokOptions.replaceWithDelombokOptions(context); - options.put(OptionName.ENCODING, charset.name()); - if (classpath != null) options.put(OptionName.CLASSPATH, classpath); - if (sourcepath != null) options.put(OptionName.SOURCEPATH, sourcepath); - if (bootclasspath != null) options.put(OptionName.BOOTCLASSPATH, bootclasspath); + LombokOptions options = LombokOptionsFactory.getDelombokOptions(context); + options.putJavacOption("ENCODING", charset.name()); + if (classpath != null) options.putJavacOption("CLASSPATH", classpath); + if (sourcepath != null) options.putJavacOption("SOURCEPATH", sourcepath); + if (bootclasspath != null) options.putJavacOption("BOOTCLASSPATH", bootclasspath); options.put("compilePolicy", "attr"); CommentCatcher catcher = CommentCatcher.create(context); diff --git a/src/delombok/lombok/delombok/LombokOptionsFactory.java b/src/delombok/lombok/delombok/LombokOptionsFactory.java new file mode 100644 index 00000000..e581593f --- /dev/null +++ b/src/delombok/lombok/delombok/LombokOptionsFactory.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2013 The Project Lombok Authors. + * + * 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.delombok; + +import lombok.javac.Javac; +import lombok.javac.Javac6BasedLombokOptions; +import lombok.javac.Javac8BasedLombokOptions; +import lombok.javac.LombokOptions; + +import com.sun.tools.javac.util.Context; + +public class LombokOptionsFactory { + enum LombokOptionCompilerVersion { + JDK7_AND_LOWER { + @Override LombokOptions createAndRegisterOptions(Context context) { + return Javac6BasedLombokOptions.replaceWithDelombokOptions(context); + } + }, + + JDK8 { + @Override LombokOptions createAndRegisterOptions(Context context) { + return Javac8BasedLombokOptions.replaceWithDelombokOptions(context); + } + }; + + abstract LombokOptions createAndRegisterOptions(Context context); + } + + public static LombokOptions getDelombokOptions(Context context) { + LombokOptions options; + if (Javac.getJavaCompilerVersion() < 8) { + options = LombokOptionCompilerVersion.JDK7_AND_LOWER.createAndRegisterOptions(context); + } else { + options = LombokOptionCompilerVersion.JDK8.createAndRegisterOptions(context); + } + return options; + } +} diff --git a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java index 1bb2ce23..075cc64f 100644 --- a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java +++ b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java @@ -53,7 +53,8 @@ import com.sun.source.tree.Tree; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; -import com.sun.tools.javac.code.TypeTags; +//import com.sun.tools.javac.code.TypeTags; +import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeScanner; @@ -126,12 +127,12 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { private static final Method GET_TAG_METHOD; private static final Field TAG_FIELD; - private static final int PARENS = Javac.getCtcInt(JCTree.class, "PARENS"); - private static final int IMPORT = Javac.getCtcInt(JCTree.class, "IMPORT"); - private static final int VARDEF = Javac.getCtcInt(JCTree.class, "VARDEF"); - private static final int SELECT = Javac.getCtcInt(JCTree.class, "SELECT"); + private static final Object PARENS = Javac.getTreeTag("PARENS"); + private static final Object IMPORT = Javac.getTreeTag("IMPORT"); + private static final Object VARDEF = Javac.getTreeTag("VARDEF"); + private static final Object SELECT = Javac.getTreeTag("SELECT"); - private static final Map<Integer, String> OPERATORS; + private static final Map<Object, String> OPERATORS; static { Method m = null; @@ -150,44 +151,44 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { GET_TAG_METHOD = m; TAG_FIELD = f; - Map<Integer, String> map = new HashMap<Integer, String>(); + Map<Object, String> map = new HashMap<Object, String>(); - map.put(Javac.getCtcInt(JCTree.class, "POS"), "+"); - map.put(Javac.getCtcInt(JCTree.class, "NEG"), "-"); - map.put(Javac.getCtcInt(JCTree.class, "NOT"), "!"); - map.put(Javac.getCtcInt(JCTree.class, "COMPL"), "~"); - map.put(Javac.getCtcInt(JCTree.class, "PREINC"), "++"); - map.put(Javac.getCtcInt(JCTree.class, "PREDEC"), "--"); - map.put(Javac.getCtcInt(JCTree.class, "POSTINC"), "++"); - map.put(Javac.getCtcInt(JCTree.class, "POSTDEC"), "--"); - map.put(Javac.getCtcInt(JCTree.class, "NULLCHK"), "<*nullchk*>"); - map.put(Javac.getCtcInt(JCTree.class, "OR"), "||"); - map.put(Javac.getCtcInt(JCTree.class, "AND"), "&&"); - map.put(Javac.getCtcInt(JCTree.class, "EQ"), "=="); - map.put(Javac.getCtcInt(JCTree.class, "NE"), "!="); - map.put(Javac.getCtcInt(JCTree.class, "LT"), "<"); - map.put(Javac.getCtcInt(JCTree.class, "GT"), ">"); - map.put(Javac.getCtcInt(JCTree.class, "LE"), "<="); - map.put(Javac.getCtcInt(JCTree.class, "GE"), ">="); - map.put(Javac.getCtcInt(JCTree.class, "BITOR"), "|"); - map.put(Javac.getCtcInt(JCTree.class, "BITXOR"), "^"); - map.put(Javac.getCtcInt(JCTree.class, "BITAND"), "&"); - map.put(Javac.getCtcInt(JCTree.class, "SL"), "<<"); - map.put(Javac.getCtcInt(JCTree.class, "SR"), ">>"); - map.put(Javac.getCtcInt(JCTree.class, "USR"), ">>>"); - map.put(Javac.getCtcInt(JCTree.class, "PLUS"), "+"); - map.put(Javac.getCtcInt(JCTree.class, "MINUS"), "-"); - map.put(Javac.getCtcInt(JCTree.class, "MUL"), "*"); - map.put(Javac.getCtcInt(JCTree.class, "DIV"), "/"); - map.put(Javac.getCtcInt(JCTree.class, "MOD"), "%"); + map.put(Javac.getTreeTag("POS"), "+"); + map.put(Javac.getTreeTag("NEG"), "-"); + map.put(Javac.getTreeTag("NOT"), "!"); + map.put(Javac.getTreeTag("COMPL"), "~"); + map.put(Javac.getTreeTag("PREINC"), "++"); + map.put(Javac.getTreeTag("PREDEC"), "--"); + map.put(Javac.getTreeTag("POSTINC"), "++"); + map.put(Javac.getTreeTag("POSTDEC"), "--"); + map.put(Javac.getTreeTag("NULLCHK"), "<*nullchk*>"); + map.put(Javac.getTreeTag("OR"), "||"); + map.put(Javac.getTreeTag("AND"), "&&"); + map.put(Javac.getTreeTag("EQ"), "=="); + map.put(Javac.getTreeTag("NE"), "!="); + map.put(Javac.getTreeTag("LT"), "<"); + map.put(Javac.getTreeTag("GT"), ">"); + map.put(Javac.getTreeTag("LE"), "<="); + map.put(Javac.getTreeTag("GE"), ">="); + map.put(Javac.getTreeTag("BITOR"), "|"); + map.put(Javac.getTreeTag("BITXOR"), "^"); + map.put(Javac.getTreeTag("BITAND"), "&"); + map.put(Javac.getTreeTag("SL"), "<<"); + map.put(Javac.getTreeTag("SR"), ">>"); + map.put(Javac.getTreeTag("USR"), ">>>"); + map.put(Javac.getTreeTag("PLUS"), "+"); + map.put(Javac.getTreeTag("MINUS"), "-"); + map.put(Javac.getTreeTag("MUL"), "*"); + map.put(Javac.getTreeTag("DIV"), "/"); + map.put(Javac.getTreeTag("MOD"), "%"); OPERATORS = map; } - static int getTag(JCTree tree) { + static Object getTag(JCTree tree) { if (GET_TAG_METHOD != null) { try { - return (Integer)GET_TAG_METHOD.invoke(tree); + return GET_TAG_METHOD.invoke(tree); } catch (IllegalAccessException e) { throw new RuntimeException(e); @@ -197,7 +198,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { } } try { - return TAG_FIELD.getInt(tree); + return TAG_FIELD.get(tree); } catch (IllegalAccessException e) { throw new RuntimeException(e); @@ -633,7 +634,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { /** Is the given tree an enumerator definition? */ boolean isEnumerator(JCTree t) { - return getTag(t) == VARDEF && (((JCVariableDecl) t).mods.flags & ENUM) != 0; + return Javac.compareCTC(getTag(t), VARDEF) && (((JCVariableDecl) t).mods.flags & ENUM) != 0; } /** Print unit consisting of package clause and import statements in toplevel, @@ -657,7 +658,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { for (List<JCTree> l = tree.defs; l.nonEmpty() && (cdef == null || getTag(l.head) == IMPORT); l = l.tail) { - if (getTag(l.head) == IMPORT) { + if (Javac.compareCTC(getTag(l.head), IMPORT)) { JCImport imp = (JCImport)l.head; Name name = TreeInfo.name(imp.qualid); if (name == name.table.fromChars(new char[] {'*'}, 0, 1) || @@ -876,7 +877,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { printStat(tree.body); align(); print(" while "); - if (getTag(tree.cond) == PARENS) { + if (Javac.compareCTC(getTag(tree.cond), PARENS)) { printExpr(tree.cond); } else { print("("); @@ -892,7 +893,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitWhileLoop(JCWhileLoop tree) { try { print("while "); - if (getTag(tree.cond) == PARENS) { + if (Javac.compareCTC(getTag(tree.cond), PARENS)) { printExpr(tree.cond); } else { print("("); @@ -910,7 +911,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { try { print("for ("); if (tree.init.nonEmpty()) { - if (getTag(tree.init.head) == VARDEF) { + if (Javac.compareCTC(getTag(tree.init.head), VARDEF)) { printExpr(tree.init.head); for (List<JCStatement> l = tree.init.tail; l.nonEmpty(); l = l.tail) { JCVariableDecl vdef = (JCVariableDecl)l.head; @@ -957,7 +958,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitSwitch(JCSwitch tree) { try { print("switch "); - if (getTag(tree.selector) == PARENS) { + if (Javac.compareCTC(getTag(tree.selector), PARENS)) { printExpr(tree.selector); } else { print("("); @@ -996,7 +997,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitSynchronized(JCSynchronized tree) { try { print("synchronized "); - if (getTag(tree.lock) == PARENS) { + if (Javac.compareCTC(getTag(tree.lock), PARENS)) { printExpr(tree.lock); } else { print("("); @@ -1077,7 +1078,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitIf(JCIf tree) { try { print("if "); - if (getTag(tree.cond) == PARENS) { + if (Javac.compareCTC(getTag(tree.cond), PARENS)) { printExpr(tree.cond); } else { print("("); @@ -1173,7 +1174,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitApply(JCMethodInvocation tree) { try { if (!tree.typeargs.isEmpty()) { - if (getTag(tree.meth) == SELECT) { + if (Javac.compareCTC(getTag(tree.meth), SELECT)) { JCFieldAccess left = (JCFieldAccess)tree.meth; printExpr(left.selected); print(".<"); @@ -1277,7 +1278,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { } } - public String operatorName(int tag) { + public String operatorName(Object tag) { String result = OPERATORS.get(tag); if (result == null) throw new Error(); return result; @@ -1287,7 +1288,8 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { try { open(prec, TreeInfo.assignopPrec); printExpr(tree.lhs, TreeInfo.assignopPrec + 1); - print(" " + operatorName(getTag(tree) - JCTree.ASGOffset) + "= "); +// print(" " + operatorName(getTag(tree) - JCTree.ASGOffset) + "= "); + print(" = "); printExpr(tree.rhs, TreeInfo.assignopPrec); close(prec, TreeInfo.assignopPrec); } catch (IOException e) { @@ -1297,10 +1299,10 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitUnary(JCUnary tree) { try { - int ownprec = TreeInfo.opPrec(getTag(tree)); + int ownprec = isOwnPrec(tree); String opname = operatorName(getTag(tree)); open(prec, ownprec); - if (getTag(tree) <= Javac.getCtcInt(JCTree.class, "PREDEC")) { + if (isPostUnary(tree)) { print(opname); printExpr(tree.arg, ownprec); } else { @@ -1312,10 +1314,63 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { throw new UncheckedIOException(e); } } + + private String assignOpName(JCExpression tree) { + try { + Object tag = getTag(tree); + if (JavaCompiler.version().startsWith("1.8")) { + return operatorName(tag.getClass().getMethod("noAssignOp").invoke(tree)); + } else { + return operatorName((Integer)((Integer)tag - (Integer)JCTree.class.getField("ASGOffset").get(null))); + } + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (Exception e) { + if (e instanceof RuntimeException) throw (RuntimeException) e; + throw new RuntimeException(e); + } + } + + private int isOwnPrec(JCExpression tree) { + try { + if (JavaCompiler.version().startsWith("1.8")) { + return (Integer)TreeInfo.class.getMethod("opPrec", Class.forName("com.sun.tools.javac.code.TypeTag")).invoke(null, getTag(tree)); + } else { + return (Integer)TreeInfo.class.getMethod("opPrec", Integer.TYPE).invoke(null, getTag(tree)); + } + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (Exception e) { + if (e instanceof RuntimeException) throw (RuntimeException) e; + throw new RuntimeException(e); + } + } + + private boolean isPostUnary(JCUnary tree) { + try { + Object tag = getTag(tree); + if (JavaCompiler.version().startsWith("1.8")) { + return (Boolean) tag.getClass().getMethod("isPostUnaryOp").invoke(tree); + } else { + return ((Integer) tag) <= ((Integer) Javac.getTreeTag("PREDEC")); + } + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (Exception e) { + if (e instanceof RuntimeException) throw (RuntimeException) e; + throw new RuntimeException(e); + } + } public void visitBinary(JCBinary tree) { try { - int ownprec = TreeInfo.opPrec(getTag(tree)); + int ownprec = isOwnPrec(tree); String opname = operatorName(getTag(tree)); open(prec, ownprec); printExpr(tree.lhs, ownprec); @@ -1382,77 +1437,40 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitLiteral(JCLiteral tree) { try { - switch (tree.typetag) { - case TypeTags.INT: - print(tree.value.toString()); - break; - case TypeTags.LONG: - print(tree.value + "L"); - break; - case TypeTags.FLOAT: - print(tree.value + "F"); - break; - case TypeTags.DOUBLE: - print(tree.value.toString()); - break; - case TypeTags.CHAR: - print("\'" + - Convert.quote( - String.valueOf((char)((Number)tree.value).intValue())) + - "\'"); - break; - case TypeTags.BOOLEAN: - print(((Number)tree.value).intValue() == 1 ? "true" : "false"); - break; - case TypeTags.BOT: - print("null"); - break; - default: - print("\"" + Convert.quote(tree.value.toString()) + "\""); - break; + if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_INT)) print(tree.value.toString()); + else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_LONG)) print(tree.value + "L"); + else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_FLOAT)) print(tree.value + "F"); + else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_DOUBLE)) print(tree.value.toString()); + else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_CHAR)) { + print("\'" + + Convert.quote( + String.valueOf((char)((Number)tree.value).intValue()))+ + "\'"); } + else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_BOOLEAN)) print(((Number)tree.value).intValue() == 1 ? "true" : "false"); + else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_BOT)) print("null"); + else print("\"" + Convert.quote(tree.value.toString()) + "\""); } catch (IOException e) { throw new UncheckedIOException(e); } } - public void visitTypeIdent(JCPrimitiveTypeTree tree) { - try { - switch(tree.typetag) { - case TypeTags.BYTE: - print("byte"); - break; - case TypeTags.CHAR: - print("char"); - break; - case TypeTags.SHORT: - print("short"); - break; - case TypeTags.INT: - print("int"); - break; - case TypeTags.LONG: - print("long"); - break; - case TypeTags.FLOAT: - print("float"); - break; - case TypeTags.DOUBLE: - print("double"); - break; - case TypeTags.BOOLEAN: - print("boolean"); - break; - case TypeTags.VOID: - print("void"); - break; - default: - print("error"); - break; - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } + public void visitTypeIdent(JCPrimitiveTypeTree tree) { + Object typetag = Javac.getTreeTypeTag(tree); + try { + if (Javac.compareCTC(typetag, Javac.CTC_BYTE)) print("byte"); + else if (Javac.compareCTC(typetag, Javac.CTC_CHAR)) print("char"); + else if (Javac.compareCTC(typetag, Javac.CTC_SHORT)) print("short"); + else if (Javac.compareCTC(typetag, Javac.CTC_INT)) print("int"); + else if (Javac.compareCTC(typetag, Javac.CTC_LONG)) print("long"); + else if (Javac.compareCTC(typetag, Javac.CTC_FLOAT)) print("float"); + else if (Javac.compareCTC(typetag, Javac.CTC_DOUBLE)) print("double"); + else if (Javac.compareCTC(typetag, Javac.CTC_BOOLEAN)) print("boolean"); + else if (Javac.compareCTC(typetag, Javac.CTC_VOID)) print("void"); + else print("error"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } } public void visitTypeArray(JCArrayTypeTree tree) { diff --git a/src/stubs/com/sun/tools/javac/main/Option.java b/src/stubs/com/sun/tools/javac/main/Option.java new file mode 100644 index 00000000..f3229c78 --- /dev/null +++ b/src/stubs/com/sun/tools/javac/main/Option.java @@ -0,0 +1,10 @@ +/* + * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. + */ +package com.sun.tools.javac.main; + + +public enum Option { + ; + public String text; +} diff --git a/src/utils/lombok/javac/CommentCatcher.java b/src/utils/lombok/javac/CommentCatcher.java index 565a166d..8d1e71c0 100644 --- a/src/utils/lombok/javac/CommentCatcher.java +++ b/src/utils/lombok/javac/CommentCatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 The Project Lombok Authors. + * Copyright (C) 2011-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -21,9 +21,12 @@ */ package lombok.javac; +import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.WeakHashMap; +import lombok.Lombok; + import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; @@ -62,31 +65,33 @@ public class CommentCatcher { private static void registerCommentsCollectingScannerFactory(Context context) { try { + Class<?> scannerFactory; if (Javac.getJavaCompilerVersion() <= 6) { - Class.forName("lombok.javac.java6.CommentCollectingScannerFactory").getMethod("preRegister", Context.class).invoke(null, context); + scannerFactory = Class.forName("lombok.javac.java6.CommentCollectingScannerFactory"); } else { - Class.forName("lombok.javac.java7.CommentCollectingScannerFactory").getMethod("preRegister", Context.class).invoke(null, context); + scannerFactory = Class.forName("lombok.javac.java7.CommentCollectingScannerFactory"); } + scannerFactory.getMethod("preRegister", Context.class).invoke(null, context); + } catch (InvocationTargetException e) { + throw Lombok.sneakyThrow(e.getCause()); } catch (Exception e) { - if (e instanceof RuntimeException) throw (RuntimeException)e; - throw new RuntimeException(e); + throw Lombok.sneakyThrow(e); } } private static void setInCompiler(JavaCompiler compiler, Context context, Map<JCCompilationUnit, List<CommentInfo>> commentsMap) { - try { + Class<?> parserFactory; if (Javac.getJavaCompilerVersion() <= 6) { - Class<?> parserFactory = Class.forName("lombok.javac.java6.CommentCollectingParserFactory"); - parserFactory.getMethod("setInCompiler", JavaCompiler.class, Context.class, Map.class).invoke(null, compiler, context, commentsMap); + parserFactory = Class.forName("lombok.javac.java6.CommentCollectingParserFactory"); } else { - Class<?> parserFactory = Class.forName("lombok.javac.java7.CommentCollectingParserFactory"); - parserFactory.getMethod("setInCompiler", JavaCompiler.class, Context.class, Map.class).invoke(null, compiler, context, commentsMap); + parserFactory = Class.forName("lombok.javac.java7.CommentCollectingParserFactory"); } + parserFactory.getMethod("setInCompiler", JavaCompiler.class, Context.class, Map.class).invoke(null, compiler, context, commentsMap); + } catch (InvocationTargetException e) { + throw Lombok.sneakyThrow(e.getCause()); } catch (Exception e) { - if (e instanceof RuntimeException) throw (RuntimeException)e; - throw new RuntimeException(e); + throw Lombok.sneakyThrow(e); } } - } diff --git a/src/utils/lombok/javac/Javac.java b/src/utils/lombok/javac/Javac.java index 4f316d9f..dfa51e00 100644 --- a/src/utils/lombok/javac/Javac.java +++ b/src/utils/lombok/javac/Javac.java @@ -25,19 +25,31 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.sun.tools.javac.code.TypeTags; +import javax.lang.model.type.NoType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeVisitor; + +import lombok.Lombok; + +import com.sun.tools.javac.code.Type; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCClassDecl; 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.JCModifiers; +import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; @@ -47,31 +59,39 @@ import com.sun.tools.javac.util.Name; */ public class Javac { private Javac() { - //prevent instantiation + // prevent instantiation } /** Matches any of the 8 primitive names, such as {@code boolean}. */ - private static final Pattern PRIMITIVE_TYPE_NAME_PATTERN = Pattern.compile( - "^(boolean|byte|short|int|long|float|double|char)$"); + private static final Pattern PRIMITIVE_TYPE_NAME_PATTERN = Pattern.compile("^(boolean|byte|short|int|long|float|double|char)$"); private static final Pattern VERSION_PARSER = Pattern.compile("^(\\d{1,6})\\.(\\d{1,6}).*$"); + private static final AtomicInteger compilerVersion = new AtomicInteger(-1); + /** * Returns the version of this java compiler, i.e. the JDK that it shipped in. For example, for javac v1.7, this returns {@code 7}. */ public static int getJavaCompilerVersion() { + int cv = compilerVersion.get(); + if (cv != -1) return cv; Matcher m = VERSION_PARSER.matcher(JavaCompiler.version()); if (m.matches()) { int major = Integer.parseInt(m.group(1)); int minor = Integer.parseInt(m.group(2)); - if (major == 1) return minor; + if (major == 1) { + compilerVersion.set(minor); + return minor; + } } + compilerVersion.set(6); return 6; } /** - * Checks if the given expression (that really ought to refer to a type expression) represents a primitive type. + * 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(); @@ -79,15 +99,16 @@ public class Javac { } /** - * Turns an expression into a guessed intended literal. Only works for literals, as you can imagine. + * 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; + JCLiteral lit = (JCLiteral) expr; if (lit.getKind() == com.sun.source.tree.Tree.Kind.BOOLEAN_LITERAL) { - return ((Number)lit.value).intValue() == 0 ? false : true; + return ((Number) lit.value).intValue() == 0 ? false : true; } return lit.value; } else if (expr instanceof JCIdent || expr instanceof JCFieldAccess) { @@ -98,49 +119,231 @@ public class Javac { if (idx > -1) x = x.substring(idx + 1); } return x; - } else return null; - } - - public static final int CTC_BOOLEAN = getCtcInt(TypeTags.class, "BOOLEAN"); - public static final int CTC_INT = getCtcInt(TypeTags.class, "INT"); - public static final int CTC_DOUBLE = getCtcInt(TypeTags.class, "DOUBLE"); - public static final int CTC_FLOAT = getCtcInt(TypeTags.class, "FLOAT"); - public static final int CTC_SHORT = getCtcInt(TypeTags.class, "SHORT"); - public static final int CTC_BYTE = getCtcInt(TypeTags.class, "BYTE"); - public static final int CTC_LONG = getCtcInt(TypeTags.class, "LONG"); - public static final int CTC_CHAR = getCtcInt(TypeTags.class, "CHAR"); - public static final int CTC_VOID = getCtcInt(TypeTags.class, "VOID"); - public static final int CTC_NONE = getCtcInt(TypeTags.class, "NONE"); - - public static final int CTC_NOT_EQUAL = getCtcInt(JCTree.class, "NE"); - public static final int CTC_NOT = getCtcInt(JCTree.class, "NOT"); - public static final int CTC_BITXOR = getCtcInt(JCTree.class, "BITXOR"); - public static final int CTC_UNSIGNED_SHIFT_RIGHT = getCtcInt(JCTree.class, "USR"); - public static final int CTC_MUL = getCtcInt(JCTree.class, "MUL"); - public static final int CTC_PLUS = getCtcInt(JCTree.class, "PLUS"); - public static final int CTC_BOT = getCtcInt(TypeTags.class, "BOT"); - public static final int CTC_EQUAL = getCtcInt(JCTree.class, "EQ"); + } else + return null; + } + + public static final Object CTC_BOOLEAN = getTypeTag("BOOLEAN"); + public static final Object CTC_INT = getTypeTag("INT"); + public static final Object CTC_DOUBLE = getTypeTag("DOUBLE"); + public static final Object CTC_FLOAT = getTypeTag("FLOAT"); + public static final Object CTC_SHORT = getTypeTag("SHORT"); + public static final Object CTC_BYTE = getTypeTag("BYTE"); + public static final Object CTC_LONG = getTypeTag("LONG"); + public static final Object CTC_CHAR = getTypeTag("CHAR"); + public static final Object CTC_VOID = getTypeTag("VOID"); + public static final Object CTC_NONE = getTypeTag("NONE"); + public static final Object CTC_BOT = getTypeTag("BOT"); + public static final Object CTC_CLASS = getTypeTag("CLASS"); + + public static final Object CTC_NOT_EQUAL = getTreeTag("NE"); + public static final Object CTC_NOT = getTreeTag("NOT"); + public static final Object CTC_BITXOR = getTreeTag("BITXOR"); + public static final Object CTC_UNSIGNED_SHIFT_RIGHT = getTreeTag("USR"); + public static final Object CTC_MUL = getTreeTag("MUL"); + public static final Object CTC_PLUS = getTreeTag("PLUS"); + public static final Object CTC_EQUAL = getTreeTag("EQ"); + + public static boolean compareCTC(Object ctc1, Object ctc2) { + return ctc1 == null ? ctc2 == null : ctc1.equals(ctc2); + } + + private static final ConcurrentMap<String, Object> TYPE_TAG_CACHE = new ConcurrentHashMap<String, Object>(); + private static final ConcurrentMap<String, Object> TREE_TAG_CACHE = new ConcurrentHashMap<String, Object>(); + /** - * Retrieves a compile time constant of type int from the specified class location. + * Retrieves the provided TypeTag value, in a compiler version independent manner. * - * 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) + * The actual type object differs depending on the Compiler version: + * <ul> + * <li>For JDK 8 this is an enum value of type <code>com.sun.tools.javac.code.TypeTag</code> + * <li>for JDK 7 and lower, this is the value of the constant within <code>com.sun.tools.javac.code.TypeTags</code> + * </ul> + * 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. + * @param identifier Identifier to turn into a TypeTag. + * @return the value of the typetag constant (either enum instance or an Integer object). */ - public static int getCtcInt(Class<?> ctcLocation, String identifier) { + public static Object getTypeTag(String identifier) { + return getFieldCached(TYPE_TAG_CACHE, getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.code.TypeTag" : "com.sun.tools.javac.code.TypeTags", identifier); + } + + public static Object getTreeTag(String identifier) { + return getFieldCached(TREE_TAG_CACHE, getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.tree.JCTree" : "com.sun.tools.javac.tree.JCTree$Tag", identifier); + } + + private static Object getFieldCached(ConcurrentMap<String, Object> cache, String className, String fieldName) { + Object value = cache.get(fieldName); + if (value != null) return value; try { - return (Integer)ctcLocation.getField(identifier).get(null); + value = Class.forName(className).getField(fieldName).get(null); } catch (NoSuchFieldException e) { - throw new RuntimeException(e); + throw Lombok.sneakyThrow(e); } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw Lombok.sneakyThrow(e); + } catch (ClassNotFoundException e) { + throw Lombok.sneakyThrow(e); } + + cache.putIfAbsent(fieldName, value); + return value; + } + + public static Object getTreeTypeTag(JCPrimitiveTypeTree tree) { + return tree.typetag; + } + + public static Object getTreeTypeTag(JCLiteral tree) { + return tree.typetag; } - private static final Field JCTREE_TAG; + private static final Method createIdent, createLiteral, createUnary, createBinary; + + static { + if (getJavaCompilerVersion() < 8) { + createIdent = getMethod(TreeMaker.class, "TypeIdent", int.class); + } else { + createIdent = getMethod(TreeMaker.class, "TypeIdent", "com.sun.tools.javac.code.TypeTag"); + } + createIdent.setAccessible(true); + + if (getJavaCompilerVersion() < 8) { + createLiteral = getMethod(TreeMaker.class, "Literal", int.class, Object.class); + } else { + createLiteral = getMethod(TreeMaker.class, "Literal", "com.sun.tools.javac.code.TypeTag", "java.lang.Object"); + } + createLiteral.setAccessible(true); + + if (getJavaCompilerVersion() < 8) { + createUnary = getMethod(TreeMaker.class, "Unary", int.class, JCExpression.class); + } else { + createUnary = getMethod(TreeMaker.class, "Unary", "com.sun.tools.javac.code.TypeTag", JCExpression.class.getName()); + } + createUnary.setAccessible(true); + + if (getJavaCompilerVersion() < 8) { + createBinary = getMethod(TreeMaker.class, "Binary", Integer.TYPE, JCExpression.class, JCExpression.class); + } else { + createBinary = getMethod(TreeMaker.class, "Binary", "com.sun.tools.javac.code.TypeTag", JCExpression.class.getName(), JCExpression.class.getName()); + } + createBinary.setAccessible(true); + } + + private static Method getMethod(Class<?> clazz, String name, Class<?>... paramTypes) { + try { + return clazz.getMethod(name, paramTypes); + } catch (NoSuchMethodException e) { + throw Lombok.sneakyThrow(e); + } + } + + private static Method getMethod(Class<?> clazz, String name, String... paramTypes) { + try { + Class<?>[] c = new Class[paramTypes.length]; + for (int i = 0; i < paramTypes.length; i++) c[i] = Class.forName(paramTypes[i]); + return clazz.getMethod(name, c); + } catch (NoSuchMethodException e) { + throw Lombok.sneakyThrow(e); + } catch (ClassNotFoundException e) { + throw Lombok.sneakyThrow(e); + } + } + + public static JCExpression makeTypeIdent(TreeMaker maker, Object ctc) { + try { + return (JCExpression) createIdent.invoke(maker, ctc); + } catch (IllegalAccessException e) { + throw Lombok.sneakyThrow(e); + } catch (InvocationTargetException e) { + throw Lombok.sneakyThrow(e.getCause()); + } + } + + public static JCLiteral makeLiteral(TreeMaker maker, Object ctc, Object argument) { + try { + return (JCLiteral) createLiteral.invoke(maker, ctc, argument); + } catch (IllegalAccessException e) { + throw Lombok.sneakyThrow(e); + } catch (InvocationTargetException e) { + throw Lombok.sneakyThrow(e.getCause()); + } + } + + public static JCUnary makeUnary(TreeMaker maker, Object ctc, JCExpression argument) { + try { + return (JCUnary) createUnary.invoke(maker, ctc, argument); + } catch (IllegalAccessException e) { + throw Lombok.sneakyThrow(e); + } catch (InvocationTargetException e) { + throw Lombok.sneakyThrow(e.getCause()); + } + } + + public static JCBinary makeBinary(TreeMaker maker, Object ctc, JCExpression lhsArgument, JCExpression rhsArgument) { + try { + return (JCBinary) createBinary.invoke(maker, ctc, lhsArgument, rhsArgument); + } catch (IllegalAccessException e) { + throw Lombok.sneakyThrow(e); + } catch (InvocationTargetException e) { + throw Lombok.sneakyThrow(e.getCause()); + } + } + + private static final Class<?> JC_VOID_TYPE, JC_NO_TYPE; + + static { + Class<?> c = null; + try { + c = Class.forName("com.sun.tools.javac.code.Type$JCVoidType"); + } catch (Exception ignore) {} + JC_VOID_TYPE = c; + c = null; + try { + c = Class.forName("com.sun.tools.javac.code.Type$JCNoType"); + } catch (Exception ignore) {} + JC_NO_TYPE = c; + } + + public static Type createVoidType(TreeMaker maker, Object tag) { + if (Javac.getJavaCompilerVersion() < 8) { + return new JCNoType(((Integer) tag).intValue()); + } else { + try { + if (compareCTC(tag, CTC_VOID)) { + return (Type) JC_VOID_TYPE.newInstance(); + } else { + return (Type) JC_NO_TYPE.newInstance(); + } + } catch (IllegalAccessException e) { + throw Lombok.sneakyThrow(e); + } catch (InstantiationException e) { + throw Lombok.sneakyThrow(e); + } + } + } + + private static class JCNoType extends Type implements NoType { + public JCNoType(int tag) { + super(tag, null); + } + + @Override + public TypeKind getKind() { + if (Javac.compareCTC(tag, CTC_VOID)) return TypeKind.VOID; + if (Javac.compareCTC(tag, CTC_NONE)) return TypeKind.NONE; + throw new AssertionError("Unexpected tag: " + tag); + } + + @Override + public <R, P> R accept(TypeVisitor<R, P> v, P p) { + return v.visitNoType(this, p); + } + } + + private static final Field JCTREE_TAG, JCLITERAL_TYPETAG, JCPRIMITIVETYPETREE_TYPETAG; private static final Method JCTREE_GETTAG; static { Field f = null; @@ -149,6 +352,18 @@ public class Javac { } catch (NoSuchFieldException e) {} JCTREE_TAG = f; + f = null; + try { + f = JCLiteral.class.getDeclaredField("typetag"); + } catch (NoSuchFieldException e) {} + JCLITERAL_TYPETAG = f; + + f = null; + try { + f = JCPrimitiveTypeTree.class.getDeclaredField("typetag"); + } catch (NoSuchFieldException e) {} + JCPRIMITIVETYPETREE_TYPETAG = f; + Method m = null; try { m = JCTree.class.getDeclaredMethod("getTag"); @@ -156,36 +371,52 @@ public class Javac { JCTREE_GETTAG = m; } - public static int getTag(JCTree node) { + public static Object getTag(JCTree node) { if (JCTREE_GETTAG != null) { try { - return (Integer) JCTREE_GETTAG.invoke(node); + return JCTREE_GETTAG.invoke(node); } catch (Exception e) {} } try { - return (Integer) JCTREE_TAG.get(node); + return JCTREE_TAG.get(node); } catch (Exception e) { throw new IllegalStateException("Can't get node tag"); } } - private static Method method; + public static Object getTypeTag(JCLiteral node) { + try { + return JCLITERAL_TYPETAG.get(node); + } catch (Exception e) { + throw new IllegalStateException("Can't get JCLiteral typetag"); + } + } + + public static Object getTypeTag(JCPrimitiveTypeTree node) { + try { + return JCPRIMITIVETYPETREE_TYPETAG.get(node); + } catch (Exception e) { + throw new IllegalStateException("Can't get JCPrimitiveTypeTree typetag"); + } + } + + private static Method classDef; public static JCClassDecl ClassDef(TreeMaker maker, JCModifiers mods, Name name, List<JCTypeParameter> typarams, JCExpression extending, List<JCExpression> implementing, List<JCTree> defs) { - if (method == null) try { - method = TreeMaker.class.getDeclaredMethod("ClassDef", JCModifiers.class, Name.class, List.class, JCExpression.class, List.class, List.class); + if (classDef == null) try { + classDef = TreeMaker.class.getDeclaredMethod("ClassDef", JCModifiers.class, Name.class, List.class, JCExpression.class, List.class, List.class); } catch (NoSuchMethodException ignore) {} - if (method == null) try { - method = TreeMaker.class.getDeclaredMethod("ClassDef", JCModifiers.class, Name.class, List.class, JCTree.class, List.class, List.class); + if (classDef == null) try { + classDef = TreeMaker.class.getDeclaredMethod("ClassDef", JCModifiers.class, Name.class, List.class, JCTree.class, List.class, List.class); } catch (NoSuchMethodException ignore) {} - if (method == null) throw new IllegalStateException("Lombok bug #20130617-1310: ClassDef doesn't look like anything we thought it would look like."); - if (!Modifier.isPublic(method.getModifiers()) && !method.isAccessible()) { - method.setAccessible(true); + if (classDef == null) throw new IllegalStateException("Lombok bug #20130617-1310: ClassDef doesn't look like anything we thought it would look like."); + if (!Modifier.isPublic(classDef.getModifiers()) && !classDef.isAccessible()) { + classDef.setAccessible(true); } try { - return (JCClassDecl) method.invoke(maker, mods, name, typarams, extending, implementing, defs); + return (JCClassDecl) classDef.invoke(maker, mods, name, typarams, extending, implementing, defs); } catch (InvocationTargetException e) { throw sneakyThrow(e.getCause()); } catch (IllegalAccessException e) { |