Skip to content

Commit

Permalink
fix(comment): fixes pretty-printing bug for inline arrays with commen…
Browse files Browse the repository at this point in the history
…ts (closes #911)
  • Loading branch information
pvojtechovsky authored and monperrus committed Oct 30, 2016
1 parent a694956 commit b2951a7
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/main/java/spoon/reflect/visitor/DefaultJavaPrettyPrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -1240,24 +1240,32 @@ public <T> void visitCtNewArray(CtNewArray<T> newArray) {
}
if (newArray.getDimensionExpressions().size() == 0) {
printer.write("{ ");
for (CtExpression e : newArray.getElements()) {
List<CtExpression<?>> l_elements = newArray.getElements();
for (int i = 0; i < l_elements.size(); i++) {
CtExpression e = l_elements.get(i);
if (!(e instanceof CtStatement)) {
elementPrinterHelper.writeComment(e, CommentOffset.BEFORE);
}
scan(e);
printer.write(" , ");
if (i + 1 == l_elements.size()) {
/*
* we have to remove last char before we writeComment.
* We cannot simply skip adding of " , ",
* because it influences formatting and EOL too
*/
printer.removeLastChar();
}
if (!(e instanceof CtStatement)) {
elementPrinterHelper.writeComment(e, CommentOffset.AFTER);
}
}
if (newArray.getElements().size() > 0) {
printer.removeLastChar();
}
printer.write(" }");
}
exitCtExpression(newArray);
}


@Override
public <T> void visitCtConstructorCall(CtConstructorCall<T> ctConstructorCall) {
enterCtStatement(ctConstructorCall);
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/spoon/test/arrays/ArraysTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,19 @@ public void testCtNewArrayInnerCtNewArray() throws Exception {
fail(e.getMessage());
}
}

@Test
public void testCtNewArrayWitComments() throws Exception {
final Launcher launcher = new Launcher();
launcher.addInputResource("src/test/java/spoon/test/arrays/testclasses/NewArrayWithComment.java");
launcher.getEnvironment().setCommentEnabled(true);
launcher.setSourceOutputDirectory("target/foo2");
launcher.buildModel();
launcher.prettyprint();
try {
launcher.getModelBuilder().compile();
} catch (Exception e) {
fail(e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package spoon.test.arrays.testclasses;

public class NewArrayWithComment
{
String[] anArray1 = new String[]{"a","b"/*,"c"*/};
String[] anArray2 = new String[]{
"a", //a comment
"b", //b comment
"c" //c comment
};
}

0 comments on commit b2951a7

Please sign in to comment.