1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle.checks.indentation;
21
22 import java.util.ArrayDeque;
23 import java.util.Deque;
24 import java.util.Locale;
25
26 import com.puppycrawl.tools.checkstyle.StatelessCheck;
27 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
28 import com.puppycrawl.tools.checkstyle.api.DetailAST;
29 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30 import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
31 import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
32
33
34
35
36
37
38
39
40
41
42
43
44 @StatelessCheck
45 public class CommentsIndentationCheck extends AbstractCheck {
46
47
48
49
50 public static final String MSG_KEY_SINGLE = "comments.indentation.single";
51
52
53
54
55 public static final String MSG_KEY_BLOCK = "comments.indentation.block";
56
57
58
59
60 public CommentsIndentationCheck() {
61
62 }
63
64 @Override
65 public int[] getDefaultTokens() {
66 return new int[] {
67 TokenTypes.SINGLE_LINE_COMMENT,
68 TokenTypes.BLOCK_COMMENT_BEGIN,
69 };
70 }
71
72 @Override
73 public int[] getAcceptableTokens() {
74 return new int[] {
75 TokenTypes.SINGLE_LINE_COMMENT,
76 TokenTypes.BLOCK_COMMENT_BEGIN,
77 };
78 }
79
80 @Override
81 public int[] getRequiredTokens() {
82 return CommonUtil.EMPTY_INT_ARRAY;
83 }
84
85 @Override
86 public boolean isCommentNodesRequired() {
87 return true;
88 }
89
90 @Override
91 public void visitToken(DetailAST commentAst) {
92 switch (commentAst.getType()) {
93 case TokenTypes.SINGLE_LINE_COMMENT, TokenTypes.BLOCK_COMMENT_BEGIN ->
94 visitComment(commentAst);
95
96 default -> {
97 final String exceptionMsg = "Unexpected token type: " + commentAst.getText();
98 throw new IllegalArgumentException(exceptionMsg);
99 }
100 }
101 }
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 private void visitComment(DetailAST comment) {
118 if (!isTrailingComment(comment)) {
119 final DetailAST prevStmt = getPreviousStatement(comment);
120 final DetailAST nextStmt = getNextStmt(comment);
121
122 if (isInEmptyCaseBlock(prevStmt, nextStmt)) {
123 handleCommentInEmptyCaseBlock(prevStmt, comment, nextStmt);
124 }
125 else if (isFallThroughComment(prevStmt, nextStmt)) {
126 handleFallThroughComment(prevStmt, comment, nextStmt);
127 }
128 else if (isInEmptyCodeBlock(prevStmt, nextStmt)) {
129 handleCommentInEmptyCodeBlock(comment, nextStmt);
130 }
131 else if (isCommentAtTheEndOfTheCodeBlock(nextStmt)) {
132 handleCommentAtTheEndOfTheCodeBlock(prevStmt, comment, nextStmt);
133 }
134 else if (nextStmt != null && !areSameLevelIndented(comment, nextStmt, nextStmt)
135 && !areInSameMethodCallWithSameIndent(comment)) {
136 log(comment, getMessageKey(comment), nextStmt.getLineNo(),
137 comment.getColumnNo(), nextStmt.getColumnNo());
138 }
139 }
140 }
141
142
143
144
145
146
147
148 private static DetailAST getNextStmt(DetailAST comment) {
149 DetailAST nextStmt = comment.getNextSibling();
150 while (nextStmt != null
151 && isComment(nextStmt)
152 && comment.getColumnNo() != nextStmt.getColumnNo()) {
153 nextStmt = nextStmt.getNextSibling();
154 }
155 return nextStmt;
156 }
157
158
159
160
161
162
163
164 private DetailAST getPreviousStatement(DetailAST comment) {
165 final DetailAST prevStatement;
166 if (isDistributedPreviousStatement(comment)) {
167 prevStatement = getDistributedPreviousStatement(comment);
168 }
169 else {
170 prevStatement = getOneLinePreviousStatement(comment);
171 }
172 return prevStatement;
173 }
174
175
176
177
178
179
180
181 private boolean isDistributedPreviousStatement(DetailAST comment) {
182 final DetailAST previousSibling = comment.getPreviousSibling();
183 return isDistributedExpression(comment)
184 || isDistributedReturnStatement(previousSibling)
185 || isDistributedThrowStatement(previousSibling);
186 }
187
188
189
190
191
192
193
194
195 private boolean isDistributedExpression(DetailAST comment) {
196 DetailAST previousSibling = comment.getPreviousSibling();
197 while (previousSibling != null && isComment(previousSibling)) {
198 previousSibling = previousSibling.getPreviousSibling();
199 }
200 boolean isDistributed = false;
201 if (previousSibling != null) {
202 if (previousSibling.getType() == TokenTypes.SEMI
203 && isOnPreviousLineIgnoringComments(comment, previousSibling)) {
204 DetailAST currentToken = previousSibling.getPreviousSibling();
205 while (currentToken.getFirstChild() != null) {
206 currentToken = currentToken.getFirstChild();
207 }
208 if (!TokenUtil.areOnSameLine(previousSibling, currentToken)) {
209 isDistributed = true;
210 }
211 }
212 else {
213 isDistributed = isStatementWithPossibleCurlies(previousSibling);
214 }
215 }
216 return isDistributed;
217 }
218
219
220
221
222
223
224
225 private static boolean isStatementWithPossibleCurlies(DetailAST previousSibling) {
226 return previousSibling.getType() == TokenTypes.LITERAL_IF
227 || previousSibling.getType() == TokenTypes.LITERAL_TRY
228 || previousSibling.getType() == TokenTypes.LITERAL_FOR
229 || previousSibling.getType() == TokenTypes.LITERAL_DO
230 || previousSibling.getType() == TokenTypes.LITERAL_WHILE
231 || previousSibling.getType() == TokenTypes.LITERAL_SWITCH
232 || isDefinition(previousSibling);
233 }
234
235
236
237
238
239
240
241 private static boolean isDefinition(DetailAST previousSibling) {
242 return TokenUtil.isTypeDeclaration(previousSibling.getType())
243 || previousSibling.getType() == TokenTypes.METHOD_DEF;
244 }
245
246
247
248
249
250
251
252 private static boolean isDistributedReturnStatement(DetailAST commentPreviousSibling) {
253 boolean isDistributed = false;
254 if (commentPreviousSibling != null
255 && commentPreviousSibling.getType() == TokenTypes.LITERAL_RETURN) {
256 final DetailAST firstChild = commentPreviousSibling.getFirstChild();
257 final DetailAST nextSibling = firstChild.getNextSibling();
258 if (nextSibling != null) {
259 isDistributed = true;
260 }
261 }
262 return isDistributed;
263 }
264
265
266
267
268
269
270
271 private static boolean isDistributedThrowStatement(DetailAST commentPreviousSibling) {
272 boolean isDistributed = false;
273 if (commentPreviousSibling != null
274 && commentPreviousSibling.getType() == TokenTypes.LITERAL_THROW) {
275 final DetailAST firstChild = commentPreviousSibling.getFirstChild();
276 final DetailAST nextSibling = firstChild.getNextSibling();
277 if (!TokenUtil.areOnSameLine(nextSibling, commentPreviousSibling)) {
278 isDistributed = true;
279 }
280 }
281 return isDistributed;
282 }
283
284
285
286
287
288
289
290 private static DetailAST getDistributedPreviousStatement(DetailAST comment) {
291 DetailAST currentToken = comment.getPreviousSibling();
292 while (isComment(currentToken)) {
293 currentToken = currentToken.getPreviousSibling();
294 }
295 final DetailAST previousStatement;
296 if (currentToken.getType() == TokenTypes.SEMI) {
297 currentToken = currentToken.getPreviousSibling();
298 while (currentToken.getFirstChild() != null) {
299 if (isComment(currentToken)) {
300 currentToken = currentToken.getNextSibling();
301 }
302 else {
303 currentToken = currentToken.getFirstChild();
304 }
305 }
306 previousStatement = currentToken;
307 }
308 else {
309 previousStatement = currentToken;
310 }
311 return previousStatement;
312 }
313
314
315
316
317
318
319
320
321 private static boolean isInEmptyCaseBlock(DetailAST prevStmt, DetailAST nextStmt) {
322 return prevStmt != null
323 && nextStmt != null
324 && (prevStmt.getType() == TokenTypes.LITERAL_CASE
325 || prevStmt.getType() == TokenTypes.CASE_GROUP)
326 && (nextStmt.getType() == TokenTypes.LITERAL_CASE
327 || nextStmt.getType() == TokenTypes.LITERAL_DEFAULT);
328 }
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351 private static boolean isFallThroughComment(DetailAST prevStmt, DetailAST nextStmt) {
352 return prevStmt != null
353 && nextStmt != null
354 && prevStmt.getType() != TokenTypes.LITERAL_CASE
355 && (nextStmt.getType() == TokenTypes.LITERAL_CASE
356 || nextStmt.getType() == TokenTypes.LITERAL_DEFAULT);
357 }
358
359
360
361
362
363
364
365 private static boolean isCommentAtTheEndOfTheCodeBlock(DetailAST nextStmt) {
366 return nextStmt != null
367 && nextStmt.getType() == TokenTypes.RCURLY;
368 }
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387 private static boolean isInEmptyCodeBlock(DetailAST prevStmt, DetailAST nextStmt) {
388 return prevStmt != null
389 && nextStmt != null
390 && (prevStmt.getType() == TokenTypes.SLIST
391 || prevStmt.getType() == TokenTypes.LCURLY
392 || prevStmt.getType() == TokenTypes.ARRAY_INIT
393 || prevStmt.getType() == TokenTypes.OBJBLOCK)
394 && nextStmt.getType() == TokenTypes.RCURLY;
395 }
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419 private void handleCommentInEmptyCaseBlock(DetailAST prevStmt, DetailAST comment,
420 DetailAST nextStmt) {
421 if (comment.getColumnNo() < prevStmt.getColumnNo()
422 || comment.getColumnNo() < nextStmt.getColumnNo()) {
423 logMultilineIndentation(prevStmt, comment, nextStmt);
424 }
425 }
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463 private void handleFallThroughComment(DetailAST prevStmt, DetailAST comment,
464 DetailAST nextStmt) {
465 if (!areSameLevelIndented(comment, prevStmt, nextStmt)) {
466 logMultilineIndentation(prevStmt, comment, nextStmt);
467 }
468 }
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488 private void handleCommentAtTheEndOfTheCodeBlock(DetailAST prevStmt, DetailAST comment,
489 DetailAST nextStmt) {
490 if (prevStmt != null) {
491 if (prevStmt.getType() == TokenTypes.LITERAL_CASE
492 || prevStmt.getType() == TokenTypes.CASE_GROUP
493 || prevStmt.getType() == TokenTypes.LITERAL_DEFAULT) {
494 if (comment.getColumnNo() < nextStmt.getColumnNo()) {
495 log(comment, getMessageKey(comment), nextStmt.getLineNo(),
496 comment.getColumnNo(), nextStmt.getColumnNo());
497 }
498 }
499 else if (isCommentForMultiblock(nextStmt)) {
500 if (!areSameLevelIndented(comment, prevStmt, nextStmt)) {
501 logMultilineIndentation(prevStmt, comment, nextStmt);
502 }
503 }
504 else if (!areSameLevelIndented(comment, prevStmt, prevStmt)) {
505 final int prevStmtLineNo = prevStmt.getLineNo();
506 log(comment, getMessageKey(comment), prevStmtLineNo,
507 comment.getColumnNo(), getLineStart(prevStmtLineNo));
508 }
509 }
510 }
511
512
513
514
515
516
517
518
519 private static boolean isCommentForMultiblock(DetailAST endBlockStmt) {
520 final DetailAST nextBlock = endBlockStmt.getParent().getNextSibling();
521 final int endBlockLineNo = endBlockStmt.getLineNo();
522 final DetailAST catchAst = endBlockStmt.getParent().getParent();
523 final DetailAST finallyAst = catchAst.getNextSibling();
524 return nextBlock != null && nextBlock.getLineNo() == endBlockLineNo
525 || finallyAst != null
526 && catchAst.getType() == TokenTypes.LITERAL_CATCH
527 && finallyAst.getLineNo() == endBlockLineNo;
528 }
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549 private void handleCommentInEmptyCodeBlock(DetailAST comment, DetailAST nextStmt) {
550 if (comment.getColumnNo() < nextStmt.getColumnNo()) {
551 log(comment, getMessageKey(comment), nextStmt.getLineNo(),
552 comment.getColumnNo(), nextStmt.getColumnNo());
553 }
554 }
555
556
557
558
559
560
561
562
563
564 private DetailAST getOneLinePreviousStatement(DetailAST comment) {
565 DetailAST root = comment.getParent();
566 while (root != null && !isBlockStart(root)) {
567 root = root.getParent();
568 }
569
570 final Deque<DetailAST> stack = new ArrayDeque<>();
571 DetailAST previousStatement = null;
572 while (root != null || !stack.isEmpty()) {
573 if (!stack.isEmpty()) {
574 root = stack.pop();
575 }
576 while (root != null) {
577 previousStatement = findPreviousStatement(comment, root);
578 if (previousStatement != null) {
579 root = null;
580 stack.clear();
581 break;
582 }
583 if (root.getNextSibling() != null) {
584 stack.push(root.getNextSibling());
585 }
586 root = root.getFirstChild();
587 }
588 }
589 return previousStatement;
590 }
591
592
593
594
595
596
597
598 private static boolean isComment(DetailAST ast) {
599 final int astType = ast.getType();
600 return astType == TokenTypes.SINGLE_LINE_COMMENT
601 || astType == TokenTypes.BLOCK_COMMENT_BEGIN
602 || astType == TokenTypes.COMMENT_CONTENT
603 || astType == TokenTypes.BLOCK_COMMENT_END;
604 }
605
606
607
608
609
610
611
612 private static boolean isBlockStart(DetailAST root) {
613 return root.getType() == TokenTypes.SLIST
614 || root.getType() == TokenTypes.OBJBLOCK
615 || root.getType() == TokenTypes.ARRAY_INIT
616 || root.getType() == TokenTypes.CASE_GROUP;
617 }
618
619
620
621
622
623
624
625
626
627 private DetailAST findPreviousStatement(DetailAST comment, DetailAST root) {
628 DetailAST previousStatement = null;
629 if (Math.max(root.getLineNo(), comment.getLineNo()) == root.getLineNo()) {
630
631
632 previousStatement = getPrevStatementFromSwitchBlock(comment);
633 }
634 final DetailAST tokenWhichBeginsTheLine;
635 if (root.getType() == TokenTypes.EXPR) {
636 tokenWhichBeginsTheLine = findStartTokenOfMethodCallChain(root);
637 }
638 else if (root.getType() == TokenTypes.PLUS) {
639 tokenWhichBeginsTheLine = root.getFirstChild();
640 }
641 else {
642 tokenWhichBeginsTheLine = root;
643 }
644 if (tokenWhichBeginsTheLine != null
645 && !isComment(tokenWhichBeginsTheLine)
646 && isOnPreviousLineIgnoringComments(comment, tokenWhichBeginsTheLine)) {
647 previousStatement = tokenWhichBeginsTheLine;
648 }
649 return previousStatement;
650 }
651
652
653
654
655
656
657
658 private static DetailAST findStartTokenOfMethodCallChain(DetailAST root) {
659 DetailAST startOfMethodCallChain = root;
660 while (startOfMethodCallChain.getFirstChild() != null
661 && TokenUtil.areOnSameLine(startOfMethodCallChain.getFirstChild(), root)) {
662 startOfMethodCallChain = startOfMethodCallChain.getFirstChild();
663 }
664 if (startOfMethodCallChain.getFirstChild() != null) {
665 startOfMethodCallChain = startOfMethodCallChain.getFirstChild().getNextSibling();
666 }
667 return startOfMethodCallChain;
668 }
669
670
671
672
673
674
675
676
677
678
679 private boolean isOnPreviousLineIgnoringComments(DetailAST currentStatement,
680 DetailAST checkedStatement) {
681 DetailAST nextToken = getNextToken(checkedStatement);
682 int distanceAim = 1;
683 if (nextToken != null && isComment(nextToken)) {
684 distanceAim += countEmptyLines(checkedStatement, currentStatement);
685 }
686
687 while (nextToken != null && nextToken != currentStatement && isComment(nextToken)) {
688 if (nextToken.getType() == TokenTypes.BLOCK_COMMENT_BEGIN) {
689 distanceAim += nextToken.getLastChild().getLineNo() - nextToken.getLineNo();
690 }
691 distanceAim++;
692 nextToken = nextToken.getNextSibling();
693 }
694 return currentStatement.getLineNo() - checkedStatement.getLineNo() == distanceAim;
695 }
696
697
698
699
700
701
702
703 private DetailAST getNextToken(DetailAST checkedStatement) {
704 DetailAST nextToken;
705 if (checkedStatement.getType() == TokenTypes.SLIST
706 || checkedStatement.getType() == TokenTypes.ARRAY_INIT
707 || checkedStatement.getType() == TokenTypes.CASE_GROUP) {
708 nextToken = checkedStatement.getFirstChild();
709 }
710 else {
711 nextToken = checkedStatement.getNextSibling();
712 }
713 if (nextToken != null && isComment(nextToken) && isTrailingComment(nextToken)) {
714 nextToken = nextToken.getNextSibling();
715 }
716 return nextToken;
717 }
718
719
720
721
722
723
724
725
726 private int countEmptyLines(DetailAST startStatement, DetailAST endStatement) {
727 int emptyLinesNumber = 0;
728 final String[] lines = getLines();
729 final int endLineNo = endStatement.getLineNo();
730 for (int lineNo = startStatement.getLineNo(); lineNo < endLineNo; lineNo++) {
731 if (CommonUtil.isBlank(lines[lineNo])) {
732 emptyLinesNumber++;
733 }
734 }
735 return emptyLinesNumber;
736 }
737
738
739
740
741
742
743
744
745 private void logMultilineIndentation(DetailAST prevStmt, DetailAST comment,
746 DetailAST nextStmt) {
747 final String multilineNoTemplate = "%d, %d";
748 log(comment, getMessageKey(comment),
749 String.format(Locale.getDefault(), multilineNoTemplate, prevStmt.getLineNo(),
750 nextStmt.getLineNo()), comment.getColumnNo(),
751 String.format(Locale.getDefault(), multilineNoTemplate,
752 getLineStart(prevStmt.getLineNo()), getLineStart(nextStmt.getLineNo())));
753 }
754
755
756
757
758
759
760
761 private static String getMessageKey(DetailAST comment) {
762 final String msgKey;
763 if (comment.getType() == TokenTypes.SINGLE_LINE_COMMENT) {
764 msgKey = MSG_KEY_SINGLE;
765 }
766 else {
767 msgKey = MSG_KEY_BLOCK;
768 }
769 return msgKey;
770 }
771
772
773
774
775
776
777
778 private static DetailAST getPrevStatementFromSwitchBlock(DetailAST comment) {
779 final DetailAST prevStmt;
780 final DetailAST parentStatement = comment.getParent();
781 if (parentStatement.getType() == TokenTypes.CASE_GROUP) {
782 prevStmt = getPrevStatementWhenCommentIsUnderCase(parentStatement);
783 }
784 else {
785 prevStmt = getPrevCaseToken(parentStatement);
786 }
787 return prevStmt;
788 }
789
790
791
792
793
794
795
796 private static DetailAST getPrevStatementWhenCommentIsUnderCase(DetailAST parentStatement) {
797 DetailAST prevStmt = null;
798 final DetailAST prevBlock = parentStatement.getPreviousSibling();
799 if (prevBlock.getLastChild() != null) {
800 DetailAST blockBody = prevBlock.getLastChild().getLastChild();
801 if (blockBody.getType() == TokenTypes.SEMI) {
802 blockBody = blockBody.getPreviousSibling();
803 }
804 if (blockBody.getType() == TokenTypes.EXPR) {
805 prevStmt = findStartTokenOfMethodCallChain(blockBody);
806 }
807 else {
808 if (blockBody.getType() == TokenTypes.SLIST) {
809 prevStmt = blockBody.getParent().getParent();
810 }
811 else {
812 prevStmt = blockBody;
813 }
814 }
815 if (isComment(prevStmt)) {
816 prevStmt = prevStmt.getNextSibling();
817 }
818 }
819 return prevStmt;
820 }
821
822
823
824
825
826
827
828 private static DetailAST getPrevCaseToken(DetailAST parentStatement) {
829 final DetailAST prevCaseToken;
830 final DetailAST parentBlock = parentStatement.getParent();
831 if (parentBlock.getParent().getPreviousSibling() != null
832 && parentBlock.getParent().getPreviousSibling().getType()
833 == TokenTypes.LITERAL_CASE) {
834 prevCaseToken = parentBlock.getParent().getPreviousSibling();
835 }
836 else {
837 prevCaseToken = null;
838 }
839 return prevCaseToken;
840 }
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864 private boolean areSameLevelIndented(DetailAST comment, DetailAST prevStmt,
865 DetailAST nextStmt) {
866 return comment.getColumnNo() == getLineStart(nextStmt.getLineNo())
867 || comment.getColumnNo() == getLineStart(prevStmt.getLineNo());
868 }
869
870
871
872
873
874
875
876 private int getLineStart(int lineNo) {
877 final char[] line = getLines()[lineNo - 1].toCharArray();
878 int lineStart = 0;
879 while (Character.isWhitespace(line[lineStart])) {
880 lineStart++;
881 }
882 return lineStart;
883 }
884
885
886
887
888
889
890
891 private boolean isTrailingComment(DetailAST comment) {
892 final boolean isTrailingComment;
893 if (comment.getType() == TokenTypes.SINGLE_LINE_COMMENT) {
894 isTrailingComment = isTrailingSingleLineComment(comment);
895 }
896 else {
897 isTrailingComment = isTrailingBlockComment(comment);
898 }
899 return isTrailingComment;
900 }
901
902
903
904
905
906
907
908
909
910
911
912
913
914 private boolean isTrailingSingleLineComment(DetailAST singleLineComment) {
915 final String targetSourceLine = getLine(singleLineComment.getLineNo() - 1);
916 final int commentColumnNo = singleLineComment.getColumnNo();
917 return !CommonUtil.hasWhitespaceBefore(commentColumnNo, targetSourceLine);
918 }
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933 private boolean isTrailingBlockComment(DetailAST blockComment) {
934 final String commentLine = getLine(blockComment.getLineNo() - 1);
935 final int commentColumnNo = blockComment.getColumnNo();
936 final DetailAST nextSibling = blockComment.getNextSibling();
937 return !CommonUtil.hasWhitespaceBefore(commentColumnNo, commentLine)
938 || nextSibling != null && TokenUtil.areOnSameLine(nextSibling, blockComment);
939 }
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959 private static boolean areInSameMethodCallWithSameIndent(DetailAST comment) {
960 return comment.getParent().getType() == TokenTypes.METHOD_CALL
961 && comment.getColumnNo()
962 == getFirstExpressionNodeFromMethodCall(comment.getParent()).getColumnNo();
963 }
964
965
966
967
968
969
970
971 private static DetailAST getFirstExpressionNodeFromMethodCall(DetailAST methodCall) {
972
973 return methodCall.findFirstToken(TokenTypes.ELIST);
974 }
975
976 }