Skip to content

Commit

Permalink
feature(CtCommentImpl): add _setRawContent to be able to bypass clean…
Browse files Browse the repository at this point in the history
…Comment (#2889)
  • Loading branch information
monperrus authored and nharrand committed Mar 5, 2019
1 parent 10ea8b6 commit e6ee14f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/main/java/spoon/support/reflect/code/CtCommentImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,17 @@ public <E extends CtComment> E setContent(String content) {
return (E) this;
}

/**
* FOR ADVANCED USAGE ONLY
* Set the comment content, without cleaning the comment, if the cleaning behavior to get a canonical version does not work for you.
* Does not ensure any AST contract such as calling the change listener
* You have to cast your comment to CtCommentImpl, it's not beautiful, but it's known :-)
*/
public <E extends CtComment> E _setRawContent(String content) {
this.content = content;
return (E) this;
}

@Override
public CommentType getCommentType() {
return type;
Expand Down
23 changes: 23 additions & 0 deletions src/test/java/spoon/test/comment/CommentTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
import spoon.support.JavaOutputProcessor;
import spoon.support.StandardEnvironment;
import spoon.support.compiler.jdt.JDTSnippetCompiler;
import spoon.support.reflect.code.CtCommentImpl;
import spoon.test.comment.testclasses.BlockComment;
import spoon.test.comment.testclasses.Comment1;
import spoon.test.comment.testclasses.Comment2;
Expand Down Expand Up @@ -635,6 +636,28 @@ public void testBlockComment() {
+ "/* comment before name parameter */" + newLine
+ "int i) throws java.lang.Error, java.lang.Exception {" + newLine
+ "}", m2.toString());

// contract: one does not crash when setting a comment starting with '//' in a block comment
// https://github.com/INRIA/spoon/issues/2887
CtComment ctComment = m2.getComments().get(0);
ctComment.setContent("// foo");
assertEquals(CtComment.CommentType.BLOCK, ctComment.getCommentType());
// it's a limitation, you cannot start with ''
assertEquals("/* foo */", ctComment.toString());

// workaround #1: the comment can start with ' //'
ctComment.setContent(" // foo");
assertEquals(CtComment.CommentType.BLOCK, ctComment.getCommentType());
// it's a limitation, you cannot start with ''
assertEquals("/* // foo */", ctComment.toString());

// workaround #2: one can cast and call '_setRawContent'
// without setting the comment field through reflection
((CtCommentImpl) ctComment)._setRawContent("// foo");
assertEquals(CtComment.CommentType.BLOCK, ctComment.getCommentType());
// it's a limitation, you cannot start with ''
assertEquals("/* // foo */", ctComment.toString());

}

@Test
Expand Down

0 comments on commit e6ee14f

Please sign in to comment.