javaparser
javaparser copied to clipboard
Disappearing comments with LexicalPreservingPrinter
Moving statements may make their associated comments disappear from LexicalPreservingPrinter output. An example:
String code =
"""
class A{
void f(){
// first comment
int a = 1;
// second comment
int b = 2;
// third comment
int c = 3;
}
}
""";
CompilationUnit cu = StaticJavaParser.parse(code);
LexicalPreservingPrinter.setup(cu);
System.out.println(cu);
System.out.println("----------------------------------");
System.out.println(LexicalPreservingPrinter.print(cu));
var block = cu.findAll(BlockStmt.class).get(0);
var lastStmt = block.getStatements().removeLast();
block.addStatement(lastStmt);
System.out.println("AFTER-----------------------------");
System.out.println(cu);
System.out.println("----------------------------------");
System.out.println(LexicalPreservingPrinter.print(cu));
Output:
class A {
void f() {
// first comment
int a = 1;
// second comment
int b = 2;
// third comment
int c = 3;
}
}
----------------------------------
class A{
void f(){
// first comment
int a = 1;
// second comment
int b = 2;
// third comment
int c = 3;
}
}
AFTER-----------------------------
class A {
void f() {
// first comment
int a = 1;
// second comment
int b = 2;
// third comment
int c = 3;
}
}
----------------------------------
class A{
void f(){
// first comment
int a = 1;
// second comment
int b = 2;
int c = 3;
}
}
Notice the last comment is present with the default printer, but won't be printed with the LexicalPreservingPrinter. There is also an extra empty line at the end of the block.
It's a complicated case and I'm surprised that you're the first person to spot this issue. Unfortunately I'm not going to be able to solve it immediately. No matter how much I think about it, I can't see how to display the comment with the LexicalPreservingPrinter.