diff --git a/src/main/java/spoon/support/compiler/jdt/JDTCommentBuilder.java b/src/main/java/spoon/support/compiler/jdt/JDTCommentBuilder.java index 2b1cbc218ec..10bc6404352 100644 --- a/src/main/java/spoon/support/compiler/jdt/JDTCommentBuilder.java +++ b/src/main/java/spoon/support/compiler/jdt/JDTCommentBuilder.java @@ -372,7 +372,7 @@ public void visitCtSwitch(CtSwitch e) { } previous = ctCase; } - if (previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart()) { + if (previous != null && previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart()) { addCommentToNear(comment, new ArrayList<>(previous.getStatements())); try { comment.getParent(); diff --git a/src/test/java/spoon/test/comment/CommentTest.java b/src/test/java/spoon/test/comment/CommentTest.java index 60c3816f602..4a6977d6df7 100644 --- a/src/test/java/spoon/test/comment/CommentTest.java +++ b/src/test/java/spoon/test/comment/CommentTest.java @@ -1120,6 +1120,7 @@ public void testCommentGetRawContent() { " * @version 1.0\r" + " */", type.getComments().get(0).getRawContent()); } + @Test public void testEmptyStatementComments() { //contract: model building should not produce NPE, comments should exist @@ -1127,10 +1128,15 @@ public void testEmptyStatementComments() { launcher.addInputResource("./src/test/java/spoon/test/comment/testclasses/EmptyStatementComments.java"); launcher.getEnvironment().setCommentEnabled(true); - CtModel model = launcher.buildModel(); - List conditions = model.getElements(new TypeFilter<>(CtIf.class)); + List> methods = launcher.buildModel().getElements(new TypeFilter<>(CtMethod.class)); + + List conditions = methods.get(0).getElements(new TypeFilter<>(CtIf.class)); assertEquals("comment", conditions.get(0).getComments().get(0).getContent()); assertEquals("comment", conditions.get(1).getComments().get(0).getContent()); + + List> switches = methods.get(1).getElements(new TypeFilter<>(CtSwitch.class)); + assertEquals("commentInline", switches.get(0).getComments().get(0).getContent()); + assertEquals("commentBlock", switches.get(1).getComments().get(0).getContent()); } @Test diff --git a/src/test/java/spoon/test/comment/testclasses/EmptyStatementComments.java b/src/test/java/spoon/test/comment/testclasses/EmptyStatementComments.java index 2339b5e73fb..b9f3da6ad6c 100644 --- a/src/test/java/spoon/test/comment/testclasses/EmptyStatementComments.java +++ b/src/test/java/spoon/test/comment/testclasses/EmptyStatementComments.java @@ -8,4 +8,14 @@ void m1() { if (true) /* comment */ ; } + + void m2(int value) { + switch (value) { + // commentInline + } + + switch (value) { + /* commentBlock */ + } + } }