Permalink
Browse files

GROOVY-4654: groovy.transform.ToString annotation does not handle cyc…

…les (handle easy case of self-reference)
  • Loading branch information...
1 parent 5cbe57d commit d9d4feb923443ef90f03887cdca79a5696bc8181 @paulk-asert paulk-asert committed Nov 18, 2012
@@ -210,7 +210,7 @@ private static BooleanExpression notEqualsPropertyExpr(PropertyNode pNode, Expre
return new BooleanExpression(new BinaryExpression(selfGetter, COMPARE_NOT_EQUAL, otherGetter));
}
- private static BooleanExpression identicalExpr(Expression self, Expression other) {
+ public static BooleanExpression identicalExpr(Expression self, Expression other) {
return new BooleanExpression(new MethodCallExpression(self, "is", new ArgumentListExpression(other)));
}
@@ -40,12 +40,7 @@
import java.util.ArrayList;
import java.util.List;
-import static org.codehaus.groovy.transform.AbstractASTTransformUtil.assignStatement;
-import static org.codehaus.groovy.transform.AbstractASTTransformUtil.declStatement;
-import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstanceNonPropertyFields;
-import static org.codehaus.groovy.transform.AbstractASTTransformUtil.getInstanceProperties;
-import static org.codehaus.groovy.transform.AbstractASTTransformUtil.hasDeclaredMethod;
-import static org.codehaus.groovy.transform.AbstractASTTransformUtil.notNullExpr;
+import static org.codehaus.groovy.transform.AbstractASTTransformUtil.*;
/**
* Handles generation of code for the @ToString annotation.
@@ -157,7 +152,9 @@ private static void appendValue(BlockStatement body, Expression result, Variable
final Statement appendValue = ignoreNulls ? new IfStatement(notNullExpr(value), thenBlock, EmptyStatement.INSTANCE) : thenBlock;
appendCommaIfNotFirst(thenBlock, result, first);
appendPrefix(thenBlock, result, name, includeNames);
- thenBlock.addStatement(append(result, new StaticMethodCallExpression(INVOKER_TYPE, "toString", value)));
+ thenBlock.addStatement(new IfStatement(identicalExpr(value, VariableExpression.THIS_EXPRESSION),
+ append(result, new ConstantExpression("(this)")),
+ append(result, new StaticMethodCallExpression(INVOKER_TYPE, "toString", value))));
body.addStatement(appendValue);
}
@@ -220,4 +220,24 @@ class ToStringTransformTest extends GroovyShellTestCase {
assertEquals("Person()", toString)
}
+
+ void testSelfReference() {
+
+ def toString = evaluate("""
+ import groovy.transform.*
+
+ @ToString(includeFields=true, includeNames=true) class Tree {
+ String val
+ Tree left
+ private Tree right
+ }
+
+ def self = new Tree(val:'foo', left:null, right:null)
+ self.left = self
+ self.right = self
+ self.toString()
+ """)
+
+ assert toString == 'Tree(val:foo, left:(this), right:(this))'
+ }
}

0 comments on commit d9d4feb

Please sign in to comment.