bug: DefaultJavaPrettyPrinter misses line breaks with enums
- Dominant language
- Java
- Stars
- 2k
- Forks
- 392
- Avg merge
- 11h 24m
- Merged PRs (30d)
- 36
Description
I found some issues when writing enums:
1. If an enum only contains enum values but no other type members, code like
```java
enum SimpleEnum {
CONSTANT
}
```
is transformed into
```java
enum SimpleEnum {
CONSTANT;}
```
This comes from the printList call here: https://github.com/INRIA/spoon/blob/e8c0d1b75e694e6dea8c70ef82bc3b6e8cb7cb0b/src/main/java/spoon/reflect/visitor/DefaultJavaPrettyPrinter.java#L753
It writes a line break before each enum value but does not add one after the `;`. This isn't a problem if there are any other type members to write because `ElementPrinterHelper#writeElementList` will add the line break (although there is no empty line then, but that breaks a test here due to the expected output: https://github.com/INRIA/spoon/blob/cd339e2c5f0e5c1e42c66b890f02bc282c3a0ea1/src/test/java/spoon/test/prettyprinter/DefaultPrettyPrinterTest.java#L303-L311)
Only writing a new line if enum values were written but no type members makes it work.
2. Using `preserveLineNumbers` writes an initial code
```java
enum AlmostEmptyEnum {
;
@Override
public void toString() {
return name().toLowerCase();
}
}
```
as
```java
enum AlmostEmptyEnum {
;
@Override
public void toString() {
return name().toLowerCase();
}}
```
This only happens with that option, without the option it looks like
```java
enum AlmostEmptyEnum {
;
@Override
public void toString() {
return name().toLowerCase();
}
}
```
Note that without preserving line numbers, a new line is added before the method. This line is not added with that option but due to https://github.com/INRIA/spoon/blob/2fff4c50266f79bc06b961e3b01ca6c6e0fcc1ab/src/main/java/spoon/reflect/visitor/ElementPrinterHelper.java#L185-L187 the last line break is still skipped (this might be an issue with normal classes too(?)).
Another - rather unrelated - issue I encountered with printing of enum values is that an enum
```java
enum SimpleEnum {
CONSTANT {
}
}
```
is written as
```java
enum SimpleEnum {
CONSTANT() {};}
```
The added `()` and the `;` also appear with the Sniper printer.
----
### Edit
The added `()` come from the `!isImplicit` check here https://github.com/INRIA/spoon/blob/e8c0d1b75e694e6dea8c70ef82bc3b6e8cb7cb0b/src/main/java/spoon/reflect/visitor/DefaultJavaPrettyPrinter.java#L795-L797 which indicates that the **default expression** is not implicit but it is handled as if the **constructor** is not implicit.
Contributor guide
Assessment
This issue has not been assessed yet.