Skip to content

A constructor keeps the comments in front of its closing brace - #102

Merged
bnaudts merged 1 commit into
mainfrom
comment-in-empty-constructor
Oct 5, 2026
Merged

bnaudts merged 1 commit into
mainfrom
comment-in-empty-constructor

Conversation

@tomtourwe

Copy link
Copy Markdown

A comment in front of a constructor's closing brace was lost: C() { // inside } parsed to a constructor with no comment anywhere and printed as C(){}, and D() { int i = 0; // after } printed as D(){int i=0;}. The same bodies in a method keep
their comments.

Cause. In the parser's tree a constructor's body is not a CodeBlock: its {, statements and } are children of the ConstructorDeclaration itself, where a method's body is one CodeBlock child. SourceCodeScan recorded the comments in
front of a closing } for CodeBlocks only, so for a constructor it recorded nowhere.

Fix. SourceCodeScan records them for a constructor too, under the body's source from { to }, which is where ScanCompilationUnit.parseBlock looks them up.

Why it matters. A tool that rewrites a constructor cannot see a comment that is not in the model. A dependency-injection migration removed empty constructors whose only content was a comment (// TODO Auto-generated constructor stub,
commented-out code), because the model said the constructor was empty.

Tests. TestCommentInEmptyConstructor: the two constructor cases, and the same two bodies in a method as controls. All four compare the whole printed member. maddi-java-openjdk: 671 tests, 0 failures, 9 skipped.

A constructor's body is not a CodeBlock in the parser's tree: its '{', statements and '}' are children of the
ConstructorDeclaration itself, where a method's body is one CodeBlock child. The comments in front of a body's
closing '}' were recorded for CodeBlocks only, so in a constructor they were recorded nowhere:
`C() { // inside }` parsed and printed as `C(){}`, `D() { int i = 0; // after }` as `D(){int i=0;}`.
SourceCodeScan now records them for a constructor too, under the body's source from '{' to '}', where
ScanCompilationUnit.parseBlock looks them up.

TestCommentInEmptyConstructor: both constructor cases, and the same two bodies in a method as controls; all four
compare the whole printed member. maddi-java-openjdk: 671 tests, 0 failures, 9 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015GLk2yT8ii4MQN3oTGaEXQ
Signed-off-by: Tom Tourwe <Tom.Tourwe@codelaser.io>
@bnaudts
bnaudts merged commit 23557a3 into main Oct 5, 2026
3 checks passed
@bnaudts
bnaudts deleted the comment-in-empty-constructor branch October 5, 2026 17:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants