Skip to content

Commit 5a7ac1e

Browse files
BuzzMSMartinWitt
authored andcommitted
fix: NullPointerException in the 'insertCommentInAST' method for an empty switch statement. (INRIA#3191)
1 parent f4156ff commit 5a7ac1e

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

src/main/java/spoon/support/compiler/jdt/JDTCommentBuilder.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,7 @@ public <E> void visitCtSwitch(CtSwitch<E> e) {
372372
}
373373
previous = ctCase;
374374
}
375-
if (previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart()) {
375+
if (previous != null && previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart()) {
376376
addCommentToNear(comment, new ArrayList<>(previous.getStatements()));
377377
try {
378378
comment.getParent();

src/test/java/spoon/test/comment/CommentTest.java

+8-2
Original file line numberDiff line numberDiff line change
@@ -1120,17 +1120,23 @@ public void testCommentGetRawContent() {
11201120
" * @version 1.0\r" +
11211121
" */", type.getComments().get(0).getRawContent());
11221122
}
1123+
11231124
@Test
11241125
public void testEmptyStatementComments() {
11251126
//contract: model building should not produce NPE, comments should exist
11261127
Launcher launcher = new Launcher();
11271128
launcher.addInputResource("./src/test/java/spoon/test/comment/testclasses/EmptyStatementComments.java");
11281129
launcher.getEnvironment().setCommentEnabled(true);
11291130

1130-
CtModel model = launcher.buildModel();
1131-
List<CtIf> conditions = model.getElements(new TypeFilter<>(CtIf.class));
1131+
List<CtMethod<?>> methods = launcher.buildModel().getElements(new TypeFilter<>(CtMethod.class));
1132+
1133+
List<CtIf> conditions = methods.get(0).getElements(new TypeFilter<>(CtIf.class));
11321134
assertEquals("comment", conditions.get(0).getComments().get(0).getContent());
11331135
assertEquals("comment", conditions.get(1).getComments().get(0).getContent());
1136+
1137+
List<CtSwitch<?>> switches = methods.get(1).getElements(new TypeFilter<>(CtSwitch.class));
1138+
assertEquals("commentInline", switches.get(0).getComments().get(0).getContent());
1139+
assertEquals("commentBlock", switches.get(1).getComments().get(0).getContent());
11341140
}
11351141

11361142
@Test

src/test/java/spoon/test/comment/testclasses/EmptyStatementComments.java

+10
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,14 @@ void m1() {
88
if (true) /* comment */
99
;
1010
}
11+
12+
void m2(int value) {
13+
switch (value) {
14+
// commentInline
15+
}
16+
17+
switch (value) {
18+
/* commentBlock */
19+
}
20+
}
1121
}

0 commit comments

Comments
 (0)