LPP doesn't handle new switch entries well
As a user using LexicalPreservingPrinter, I expect new switch statement entries to use the same whitespace alignment as the other entries.
This test case shows (using 3.25.4) that inserting a new SwitchEntry ends up with a very different, misaligned whitespace:
@Test
void it_doesnt_handle_switch() {
String code =
"""
class Foo {
void foo() {
switch(bar) {
case 1:
break;
case 2:
break;
default:
break;
}
}
}
""";
CompilationUnit cu = StaticJavaParser.parse(code);
LexicalPreservingPrinter.setup(cu);
SwitchStmt switchStmt = cu.findAll(SwitchStmt.class).stream().findFirst().orElseThrow();
SwitchEntry newEntry = new SwitchEntry();
newEntry.setLabels(NodeList.nodeList(new IntegerLiteralExpr(0)));
newEntry.setStatements(NodeList.nodeList(new BreakStmt()));
switchStmt.getEntries().addLast(newEntry);
System.out.println(LexicalPreservingPrinter.print(cu));
}
The output:
class Foo {
void foo() {
switch(bar) {
case 1:
break;
case 2:
break;
default:
break;
case 0:
break;
}
}
}
I tried the usual kinds of "tricking it" which sometimes works for other kinds of Node types when I run into similar issues, but no luck here yet.
Is there any way for me (without crazy reflection hacks) to affect the behavior of LexicalPreservingPrinter and give it any hints on how to render this new node?
Hi @nahsra Unfortunately LPP has over the years reached a significant level of complexity and the formatting rules are not clearly identified. I will look into this problem as soon as possible but you can't tell LPP how it should print the source code (except for a few parameters).
Is the expected result the following?
class Foo {
void foo() {
switch(bar) {
case 1:
break;
case 2:
break;
default:
break;
case 0:
break;
}
}
}
Yes it is! Thanks.
For the moment what I can propose is a solution which gives you back this. Would you be interested?
class Foo {
void foo() {
switch(bar) {
case 1:
break;
case 2:
break;
default:
break;
case 0:
break; <-- this is the default indentation
} <-- bad indentation caused probably because there is no eol char generated after the break statement
}
}
That looks much better. I think people would definitely appreciate that. Thank you!
Is there any thoughts on the next generation of LexicalPreservingPrinter? When I look around JP issues, it seems that we may need a v2 of this component. I'd like to contribute, but I probably can't lead that effort.
There is no next generation planned. I'm just trying to fix ongoing bugs and possibly simplify it when I have some time.
The community appreciates the hard work!
I am not closing this PR as the PR only partially fixes the issue. There is a bad indentation on the right brace of the switch statement.