INRIA / INRIA/spoon

Type javadoc comment is added to compilation unit if it's at the very start of the file

Open
#3,300 9 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
2k
Forks
392
Avg merge
11h 24m
Merged PRs (30d)
36

Description

Hi!

I found some behavior that I think is a bug. If a file starts with a Javadoc comment (i.e. no package statement, and the very first byte is a `/`), then that comment is attached to the compilation unit instead of the type. For example, this file will have the comment attached to the CU:

```java
/**
* A comment!
*/
class Cls {}
```

But this file will have it attached to the type (note leading space before first `/`):

```java
/**
* A comment!
*/
class Cls {}
```

I would expect both those examples to have the comment attached to the type. The problem is that, in the first case, the source start position of the type is set to 30 bytes, and the source start of the comment is set to 0 bytes, so the check below fails on the type/comment pair, and the type is not set as the comment's parent.

https://github.com/INRIA/spoon/blob/471a91214ef1ab62e4f9de417e096bf28ef56c30/src/main/java/spoon/support/compiler/jdt/JDTCommentBuilder.java#L547

In the second case, the source start position of the type is set to 1 byte, and so is the start position of the comment, so the above check passes and the comment is added to the type.

A workaround is to use a `VirtualFile` as a resource, as then the case below is hit and the comment is added to the type regardless of position.

https://github.com/INRIA/spoon/blob/471a91214ef1ab62e4f9de417e096bf28ef56c30/src/main/java/spoon/support/compiler/jdt/JDTCommentBuilder.java#L194-L203

I'm not sure if this is a bug in Spoon, or in JDT. If the source start for the type was set to 0 in the first example, then it would be fine, but it's set to 30, which breaks it all. Anyway, here's a small test case that reproduces the issue.

```java
@Test
public void commentIsAttachedToType_whenCommentAtStartOfFile() {
Launcher launcher = new Launcher();
launcher.addInputResource("Cls.java");
CtModel model = launcher.buildModel();

CtType type = model.getAllTypes().iterator().next();

assertEquals(1, type.getComments().size());
}
```

With `Cls.java` being this file:

```java
/**
* A comment!
*/
class Cls {}
```

I'm well aware that this is a corner case of corner cases and may not be worth fixing at all, but after spending over an hour figuring out where my comments were disappearing to I wanted to report it anyway :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.