From d906899546edf29e23ed2ae4ac8b5a781337bdb4 Mon Sep 17 00:00:00 2001 From: Reinier Zwitserloot Date: Mon, 27 Jul 2009 09:21:22 +0200 Subject: Added support for @ToString annotation. The code for generating toStrings has now moved from HandleData to the new HandleToString. --- src/lombok/ToString.java | 57 ++++++ src/lombok/eclipse/handlers/HandleData.java | 63 +------ src/lombok/eclipse/handlers/HandleToString.java | 238 ++++++++++++++++++++++++ src/lombok/javac/handlers/HandleData.java | 42 +---- src/lombok/javac/handlers/HandleToString.java | 196 +++++++++++++++++++ 5 files changed, 494 insertions(+), 102 deletions(-) create mode 100644 src/lombok/ToString.java create mode 100644 src/lombok/eclipse/handlers/HandleToString.java create mode 100644 src/lombok/javac/handlers/HandleToString.java (limited to 'src/lombok') diff --git a/src/lombok/ToString.java b/src/lombok/ToString.java new file mode 100644 index 00000000..8067f647 --- /dev/null +++ b/src/lombok/ToString.java @@ -0,0 +1,57 @@ +/* + * 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; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Generates an implementation for the toString method inherited by all objects. + *

+ * If the method already exists, then @ToString will not generate any method, and instead warns + * that it's doing nothing at all. The parameter list and return type are not relevant when deciding to skip generation of + * the method; any method named toString will make @ToString not generate anything. + *

+ * All fields that are non-static are used in the toString generation. You can exclude fields by specifying them + * in the exclude parameter. + *

+ * Array fields are handled by way of {@link java.util.Arrays#deepToString(Object[], Object[])} where necessary. + * The downside is that arrays with circular references (arrays that contain themselves, + * possibly indirectly) results in calls to toString throwing a + * {@link java.lang.StackOverflowError}. However, the implementations for java's own {@link java.util.ArrayList} suffer + * from the same flaw. + *

+ * The toString method that is generated will print the class name as well as each field. You can optionally + * also print the names of each field, by setting the includeFieldNames flag to true. + *

+ * You can also choose to include the result of toString in your class's superclass by setting the + * callSuper to true. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.SOURCE) +public @interface ToString { + boolean includeFieldNames() default false; + boolean callSuper() default false; + String[] exclude() default {}; +} diff --git a/src/lombok/eclipse/handlers/HandleData.java b/src/lombok/eclipse/handlers/HandleData.java index 71089409..749418eb 100644 --- a/src/lombok/eclipse/handlers/HandleData.java +++ b/src/lombok/eclipse/handlers/HandleData.java @@ -75,7 +75,6 @@ import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; -import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; @@ -110,7 +109,6 @@ public class HandleData implements EclipseAnnotationHandler { List nodesForEquality = new ArrayList(); List nodesForConstructor = new ArrayList(); - List nodesForToString = new ArrayList(); for ( Node child : typeNode.down() ) { if ( child.getKind() != Kind.FIELD ) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); @@ -118,16 +116,12 @@ public class HandleData implements EclipseAnnotationHandler { if ( (fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0 ) continue; if ( (fieldDecl.modifiers & ClassFileConstants.AccTransient) == 0 ) nodesForEquality.add(child); boolean isFinal = (fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0; - nodesForToString.add(child); if ( isFinal && fieldDecl.initialization == null ) nodesForConstructor.add(child); new HandleGetter().generateGetterForField(child, annotationNode.get()); if ( !isFinal ) new HandleSetter().generateSetterForField(child, annotationNode.get()); } - if ( methodExists("toString", typeNode) == MemberExistsResult.NOT_EXISTS ) { - MethodDeclaration toString = createToString(typeNode, nodesForToString, ast); - injectMethod(typeNode, toString); - } + new HandleToString().generateToStringForType(typeNode, annotationNode); if ( methodExists("equals", typeNode) == MemberExistsResult.NOT_EXISTS ) { MethodDeclaration equals = createEquals(typeNode, nodesForEquality, ast); @@ -162,61 +156,6 @@ public class HandleData implements EclipseAnnotationHandler { return false; } - private MethodDeclaration createToString(Node type, Collection fields, ASTNode pos) { - char[] rawTypeName = ((TypeDeclaration)type.get()).name; - String typeName = rawTypeName == null ? "" : new String(rawTypeName); - char[] prefix = (typeName + "(").toCharArray(); - char[] suffix = ")".toCharArray(); - char[] infix = ", ".toCharArray(); - long p = (long)pos.sourceStart << 32 | pos.sourceEnd; - final int PLUS = OperatorIds.PLUS; - - boolean first = true; - Expression current = new StringLiteral(prefix, 0, 0, 0); - for ( Node field : fields ) { - FieldDeclaration f = (FieldDeclaration)field.get(); - if ( f.name == null || f.type == null ) continue; - if ( !first ) { - current = new BinaryExpression(current, new StringLiteral(infix, 0, 0, 0), PLUS); - } - else first = false; - - Expression ex; - if ( f.type.dimensions() > 0 ) { - MessageSend arrayToString = new MessageSend(); - arrayToString.receiver = generateQualifiedNameRef(TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); - arrayToString.arguments = new Expression[] { new SingleNameReference(f.name, p) }; - if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(f.type.getLastToken())) ) { - arrayToString.selector = "deepToString".toCharArray(); - } else { - arrayToString.selector = "toString".toCharArray(); - } - ex = arrayToString; - } else ex = new SingleNameReference(f.name, p); - - current = new BinaryExpression(current, ex, PLUS); - } - current = new BinaryExpression(current, new StringLiteral(suffix, 0, 0, 0), PLUS); - - ReturnStatement returnStatement = new ReturnStatement(current, (int)(p >> 32), (int)p); - - MethodDeclaration method = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); - method.modifiers = PKG.toModifier(AccessLevel.PUBLIC); - method.returnType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING, new long[] {0, 0, 0}); - method.annotations = new Annotation[] { - new MarkerAnnotation(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OVERRIDE, new long[] { 0, 0, 0}), 0) - }; - method.arguments = null; - method.selector = "toString".toCharArray(); - method.thrownExceptions = null; - method.typeParameters = null; - method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; - method.bodyStart = method.declarationSourceStart = method.sourceStart = pos.sourceStart; - method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = pos.sourceEnd; - method.statements = new Statement[] { returnStatement }; - return method; - } - private ConstructorDeclaration createConstructor(boolean isPublic, Node type, Collection fields, ASTNode pos) { long p = (long)pos.sourceStart << 32 | pos.sourceEnd; diff --git a/src/lombok/eclipse/handlers/HandleToString.java b/src/lombok/eclipse/handlers/HandleToString.java new file mode 100644 index 00000000..b18906a5 --- /dev/null +++ b/src/lombok/eclipse/handlers/HandleToString.java @@ -0,0 +1,238 @@ +/* + * 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.handlers; + +import static lombok.eclipse.handlers.PKG.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import lombok.AccessLevel; +import lombok.ToString; +import lombok.core.AnnotationValues; +import lombok.core.AST.Kind; +import lombok.eclipse.Eclipse; +import lombok.eclipse.EclipseAnnotationHandler; +import lombok.eclipse.EclipseAST.Node; + +import org.eclipse.jdt.internal.compiler.ast.ASTNode; +import org.eclipse.jdt.internal.compiler.ast.Annotation; +import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; +import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; +import org.eclipse.jdt.internal.compiler.ast.Expression; +import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; +import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; +import org.eclipse.jdt.internal.compiler.ast.MessageSend; +import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.jdt.internal.compiler.ast.NameReference; +import org.eclipse.jdt.internal.compiler.ast.OperatorIds; +import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; +import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; +import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; +import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.jdt.internal.compiler.ast.Statement; +import org.eclipse.jdt.internal.compiler.ast.StringLiteral; +import org.eclipse.jdt.internal.compiler.ast.SuperReference; +import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; +import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; +import org.mangosdk.spi.ProviderFor; + +/** + * Handles the ToString annotation for eclipse. + */ +@ProviderFor(EclipseAnnotationHandler.class) +public class HandleToString implements EclipseAnnotationHandler { + private void checkForBogusExcludes(Node type, AnnotationValues annotation) { + List list = Arrays.asList(annotation.getInstance().exclude()); + boolean[] matched = new boolean[list.size()]; + + for ( Node child : type.down() ) { + if ( list.isEmpty() ) break; + if ( child.getKind() != Kind.FIELD ) continue; + if ( (((FieldDeclaration)child.get()).modifiers & ClassFileConstants.AccStatic) != 0 ) continue; + int idx = list.indexOf(child.getName()); + if ( idx > -1 ) matched[idx] = true; + } + + for ( int i = 0 ; i < list.size() ; i++ ) { + if ( !matched[i] ) { + annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); + } + } + } + + public void generateToStringForType(Node typeNode, Node errorNode) { + for ( Node child : typeNode.down() ) { + if ( child.getKind() == Kind.ANNOTATION ) { + if ( Eclipse.annotationTypeMatches(ToString.class, child) ) { + //The annotation will make it happen, so we can skip it. + return; + } + } + } + + boolean includeFieldNames = false; + boolean callSuper = false; + try { + includeFieldNames = ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue(); + } catch ( Exception ignore ) {} + try { + callSuper = ((Boolean)ToString.class.getMethod("callSuper").getDefaultValue()).booleanValue(); + } catch ( Exception ignore ) {} + generateToString(typeNode, errorNode, Collections.emptyList(),includeFieldNames, callSuper, false); + } + + public boolean handle(AnnotationValues annotation, Annotation ast, Node annotationNode) { + ToString ann = annotation.getInstance(); + List excludes = Arrays.asList(ann.exclude()); + Node typeNode = annotationNode.up(); + + checkForBogusExcludes(typeNode, annotation); + + return generateToString(typeNode, annotationNode, excludes, ann.includeFieldNames(), ann.callSuper(), true); + } + + public boolean generateToString(Node typeNode, Node errorNode, List excludes, + boolean includeFieldNames, boolean callSuper, boolean whineIfExists) { + TypeDeclaration typeDecl = null; + + if ( typeNode.get() instanceof TypeDeclaration ) typeDecl = (TypeDeclaration) typeNode.get(); + int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; + boolean notAClass = (modifiers & + (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; + + if ( typeDecl == null || notAClass ) { + errorNode.addError("@ToString is only supported on a class."); + return false; + } + + List nodesForToString = new ArrayList(); + for ( Node child : typeNode.down() ) { + if ( child.getKind() != Kind.FIELD ) continue; + FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); + //Skip static fields. + if ( (fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0 ) continue; + //Skip excluded fields + if ( excludes.contains(new String(fieldDecl.name)) ) continue; + nodesForToString.add(child); + } + + switch ( methodExists("toString", typeNode) ) { + case NOT_EXISTS: + MethodDeclaration toString = createToString(typeNode, nodesForToString, includeFieldNames, callSuper, errorNode.get()); + injectMethod(typeNode, toString); + return true; + case EXISTS_BY_LOMBOK: + return true; + default: + case EXISTS_BY_USER: + if ( whineIfExists ) { + errorNode.addWarning("Not generating toString(): A method with that name already exists"); + } + return true; + } + } + + private MethodDeclaration createToString(Node type, Collection fields, boolean includeFieldNames, boolean callSuper, ASTNode pos) { + char[] rawTypeName = ((TypeDeclaration)type.get()).name; + String typeName = rawTypeName == null ? "" : new String(rawTypeName); + char[] prefix = (typeName + "(").toCharArray(); + char[] suffix = ")".toCharArray(); + char[] infix = ", ".toCharArray(); + long p = (long)pos.sourceStart << 32 | pos.sourceEnd; + final int PLUS = OperatorIds.PLUS; + + boolean first = true; + Expression current = new StringLiteral(prefix, 0, 0, 0); + if ( callSuper ) { + MessageSend callToSuper = new MessageSend(); + callToSuper.receiver = new SuperReference(0, 0); + callToSuper.selector = "toString".toCharArray(); + current = new BinaryExpression(current, new StringLiteral("super=[".toCharArray(), 0, 0, 0), PLUS); + current = new BinaryExpression(current, callToSuper, PLUS); + current = new BinaryExpression(current, new StringLiteral(new char[] { ']' }, 0, 0, 0), PLUS); + first = false; + } + + for ( Node field : fields ) { + FieldDeclaration f = (FieldDeclaration)field.get(); + if ( f.name == null || f.type == null ) continue; + if ( !first ) { + current = new BinaryExpression(current, new StringLiteral(infix, 0, 0, 0), PLUS); + } + else first = false; + + Expression ex; + if ( f.type.dimensions() > 0 ) { + MessageSend arrayToString = new MessageSend(); + arrayToString.receiver = generateQualifiedNameRef(TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); + arrayToString.arguments = new Expression[] { new SingleNameReference(f.name, p) }; + if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(f.type.getLastToken())) ) { + arrayToString.selector = "deepToString".toCharArray(); + } else { + arrayToString.selector = "toString".toCharArray(); + } + ex = arrayToString; + } else ex = new SingleNameReference(f.name, p); + + if ( includeFieldNames ) { + char[] namePlusEqualsSign = (new String(f.name) + "=").toCharArray(); + current = new BinaryExpression(current, new StringLiteral(namePlusEqualsSign, 0, 0, 0), PLUS); + } + current = new BinaryExpression(current, ex, PLUS); + } + current = new BinaryExpression(current, new StringLiteral(suffix, 0, 0, 0), PLUS); + + ReturnStatement returnStatement = new ReturnStatement(current, (int)(p >> 32), (int)p); + + MethodDeclaration method = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); + method.modifiers = PKG.toModifier(AccessLevel.PUBLIC); + method.returnType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING, new long[] {0, 0, 0}); + method.annotations = new Annotation[] { + new MarkerAnnotation(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OVERRIDE, new long[] { 0, 0, 0}), 0) + }; + method.arguments = null; + method.selector = "toString".toCharArray(); + method.thrownExceptions = null; + method.typeParameters = null; + method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; + method.bodyStart = method.declarationSourceStart = method.sourceStart = pos.sourceStart; + method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = pos.sourceEnd; + method.statements = new Statement[] { returnStatement }; + return method; + } + + private static final Set BUILT_IN_TYPES = Collections.unmodifiableSet(new HashSet(Arrays.asList( + "byte", "short", "int", "long", "char", "boolean", "double", "float"))); + + private NameReference generateQualifiedNameRef(char[]... varNames) { + if ( varNames.length > 1 ) + return new QualifiedNameReference(varNames, new long[varNames.length], 0, 0); + else return new SingleNameReference(varNames[0], 0); + } +} diff --git a/src/lombok/javac/handlers/HandleData.java b/src/lombok/javac/handlers/HandleData.java index e2754d59..dd0c4128 100644 --- a/src/lombok/javac/handlers/HandleData.java +++ b/src/lombok/javac/handlers/HandleData.java @@ -92,6 +92,8 @@ public class HandleData implements JavacAnnotationHandler { if ( !isFinal ) new HandleSetter().generateSetterForField(child, annotationNode.get()); } + new HandleToString().generateToStringForType(typeNode, annotationNode); + if ( methodExists("equals", typeNode) == MemberExistsResult.NOT_EXISTS ) { JCMethodDecl method = createEquals(typeNode, nodesForEquality); injectMethod(typeNode, method); @@ -102,11 +104,6 @@ public class HandleData implements JavacAnnotationHandler { injectMethod(typeNode, method); } - if ( methodExists("toString", typeNode) == MemberExistsResult.NOT_EXISTS ) { - JCMethodDecl method = createToString(typeNode, nodesForToString); - injectMethod(typeNode, method); - } - String staticConstructorName = annotation.getInstance().staticConstructor(); if ( constructorExists(typeNode) == MemberExistsResult.NOT_EXISTS ) { @@ -122,41 +119,6 @@ public class HandleData implements JavacAnnotationHandler { return true; } - private JCMethodDecl createToString(Node typeNode, List fields) { - TreeMaker maker = typeNode.getTreeMaker(); - - JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.nil()); - JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); - JCExpression returnType = chainDots(maker, typeNode, "java", "lang", "String"); - - JCExpression current = maker.Literal(((JCClassDecl) typeNode.get()).name.toString() + "("); - boolean first = true; - - for ( Node fieldNode : fields ) { - JCVariableDecl field = (JCVariableDecl) fieldNode.get(); - if ( !first ) current = maker.Binary(JCTree.PLUS, current, maker.Literal(", ")); - first = false; - if ( field.vartype instanceof JCArrayTypeTree ) { - boolean multiDim = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCArrayTypeTree; - boolean primitiveArray = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCPrimitiveTypeTree; - boolean useDeepTS = multiDim || !primitiveArray; - - JCExpression hcMethod = chainDots(maker, typeNode, "java", "util", "Arrays", useDeepTS ? "deepToString" : "toString"); - current = maker.Binary(JCTree.PLUS, current, maker.Apply( - List.nil(), hcMethod, List.of(maker.Ident(field.name)))); - } else current = maker.Binary(JCTree.PLUS, current, maker.Ident(field.name)); - } - - current = maker.Binary(JCTree.PLUS, current, maker.Literal(")")); - - JCStatement returnStatement = maker.Return(current); - - JCBlock body = maker.Block(0, List.of(returnStatement)); - - return maker.MethodDef(mods, typeNode.toName("toString"), returnType, - List.nil(), List.nil(), List.nil(), body, null); - } - private JCMethodDecl createHashCode(Node typeNode, List fields) { TreeMaker maker = typeNode.getTreeMaker(); diff --git a/src/lombok/javac/handlers/HandleToString.java b/src/lombok/javac/handlers/HandleToString.java new file mode 100644 index 00000000..2d50cda5 --- /dev/null +++ b/src/lombok/javac/handlers/HandleToString.java @@ -0,0 +1,196 @@ +/* + * 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.javac.handlers; + +import static lombok.javac.handlers.PKG.*; + +import lombok.ToString; +import lombok.core.AnnotationValues; +import lombok.core.AST.Kind; +import lombok.javac.Javac; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacAST.Node; + +import org.mangosdk.spi.ProviderFor; + +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; +import com.sun.tools.javac.tree.JCTree.JCBlock; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; +import com.sun.tools.javac.tree.JCTree.JCModifiers; +import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; +import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.util.List; + +/** + * Handles the ToString annotation for javac. + */ +@ProviderFor(JavacAnnotationHandler.class) +public class HandleToString implements JavacAnnotationHandler { + private void checkForBogusExcludes(Node type, AnnotationValues annotation) { + List list = List.from(annotation.getInstance().exclude()); + boolean[] matched = new boolean[list.size()]; + + for ( Node child : type.down() ) { + if ( list.isEmpty() ) break; + if ( child.getKind() != Kind.FIELD ) continue; + if ( (((JCVariableDecl)child.get()).mods.flags & Flags.STATIC) != 0 ) continue; + int idx = list.indexOf(child.getName()); + if ( idx > -1 ) matched[idx] = true; + } + + for ( int i = 0 ; i < list.size() ; i++ ) { + if ( !matched[i] ) { + annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); + } + } + } + + @Override public boolean handle(AnnotationValues annotation, JCAnnotation ast, Node annotationNode) { + ToString ann = annotation.getInstance(); + List excludes = List.from(ann.exclude()); + Node typeNode = annotationNode.up(); + + checkForBogusExcludes(typeNode, annotation); + + return generateToString(typeNode, annotationNode, excludes, ann.includeFieldNames(), ann.callSuper(), true); + } + + public void generateToStringForType(Node typeNode, Node errorNode) { + for ( Node child : typeNode.down() ) { + if ( child.getKind() == Kind.ANNOTATION ) { + if ( Javac.annotationTypeMatches(ToString.class, child) ) { + //The annotation will make it happen, so we can skip it. + return; + } + } + } + + boolean includeFieldNames = false; + boolean callSuper = false; + try { + includeFieldNames = ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue(); + } catch ( Exception ignore ) {} + try { + callSuper = ((Boolean)ToString.class.getMethod("callSuper").getDefaultValue()).booleanValue(); + } catch ( Exception ignore ) {} + generateToString(typeNode, errorNode, List.nil(),includeFieldNames, callSuper, false); + } + + private boolean generateToString(Node typeNode, Node errorNode, List excludes, + boolean includeFieldNames, boolean callSuper, boolean whineIfExists) { + boolean notAClass = true; + if ( typeNode.get() instanceof JCClassDecl ) { + long flags = ((JCClassDecl)typeNode.get()).mods.flags; + notAClass = (flags & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; + } + + if ( notAClass ) { + errorNode.addError("@ToString is only supported on a class."); + return false; + } + + List nodesForToString = List.nil(); + for ( Node child : typeNode.down() ) { + if ( child.getKind() != Kind.FIELD ) continue; + JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); + //Skip static fields. + if ( (fieldDecl.mods.flags & Flags.STATIC) != 0 ) continue; + //Skip excluded fields + if ( excludes.contains(fieldDecl.name.toString()) ) continue; + nodesForToString = nodesForToString.append(child); + } + + switch ( methodExists("toString", typeNode) ) { + case NOT_EXISTS: + JCMethodDecl method = createToString(typeNode, nodesForToString, includeFieldNames, callSuper); + injectMethod(typeNode, method); + return true; + case EXISTS_BY_LOMBOK: + return true; + default: + case EXISTS_BY_USER: + if ( whineIfExists ) { + errorNode.addWarning("Not generating toString(): A method with that name already exists"); + } + return true; + } + + } + + private JCMethodDecl createToString(Node typeNode, List fields, boolean includeFieldNames, boolean callSuper) { + TreeMaker maker = typeNode.getTreeMaker(); + + JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.nil()); + JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); + JCExpression returnType = chainDots(maker, typeNode, "java", "lang", "String"); + + JCExpression current = maker.Literal(((JCClassDecl) typeNode.get()).name.toString() + "("); + boolean first = true; + + if ( callSuper ) { + current = maker.Binary(JCTree.PLUS, current, maker.Literal("super=[")); + JCMethodInvocation callToSuper = maker.Apply(List.nil(), + maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")), + List.nil()); + current = maker.Binary(JCTree.PLUS, current, callToSuper); + current = maker.Binary(JCTree.PLUS, current, maker.Literal("]")); + first = false; + } + + for ( Node fieldNode : fields ) { + JCVariableDecl field = (JCVariableDecl) fieldNode.get(); + if ( !first ) current = maker.Binary(JCTree.PLUS, current, maker.Literal(", ")); + first = false; + if ( includeFieldNames ) { + current = maker.Binary(JCTree.PLUS, current, maker.Literal(fieldNode.getName() + "=")); + } + if ( field.vartype instanceof JCArrayTypeTree ) { + boolean multiDim = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCArrayTypeTree; + boolean primitiveArray = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCPrimitiveTypeTree; + boolean useDeepTS = multiDim || !primitiveArray; + + JCExpression hcMethod = chainDots(maker, typeNode, "java", "util", "Arrays", useDeepTS ? "deepToString" : "toString"); + current = maker.Binary(JCTree.PLUS, current, maker.Apply( + List.nil(), hcMethod, List.of(maker.Ident(field.name)))); + } else current = maker.Binary(JCTree.PLUS, current, maker.Ident(field.name)); + } + + current = maker.Binary(JCTree.PLUS, current, maker.Literal(")")); + + JCStatement returnStatement = maker.Return(current); + + JCBlock body = maker.Block(0, List.of(returnStatement)); + + return maker.MethodDef(mods, typeNode.toName("toString"), returnType, + List.nil(), List.nil(), List.nil(), body, null); + } + +} -- cgit