1 package com.puppycrawl.tools.checkstyle.checks.blocks; 20 21 import com.puppycrawl.tools.checkstyle.api.DetailAST; 22 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 23 import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; 24 25 60 public class EmptyBlockCheck 61 extends AbstractOptionCheck 62 { 63 66 public EmptyBlockCheck() 67 { 68 super(BlockOption.STMT); 69 } 70 71 72 public int[] getDefaultTokens() 73 { 74 return new int[] { 75 TokenTypes.LITERAL_WHILE, 76 TokenTypes.LITERAL_TRY, 77 TokenTypes.LITERAL_CATCH, 78 TokenTypes.LITERAL_FINALLY, 79 TokenTypes.LITERAL_DO, 80 TokenTypes.LITERAL_IF, 81 TokenTypes.LITERAL_ELSE, 82 TokenTypes.LITERAL_FOR, 83 TokenTypes.INSTANCE_INIT, 84 TokenTypes.STATIC_INIT, 85 }; 89 } 90 91 92 public void visitToken(DetailAST aAST) 93 { 94 final DetailAST slistAST = aAST.findFirstToken(TokenTypes.SLIST); 95 if (slistAST != null) { 96 if (getAbstractOption() == BlockOption.STMT) { 97 if (slistAST.getChildCount() <= 1) { 98 log(slistAST.getLineNo(), 99 slistAST.getColumnNo(), 100 "block.noStmt", 101 aAST.getText()); 102 } 103 } 104 else if (getAbstractOption() == BlockOption.TEXT) { 105 if (!hasText(slistAST)) { 106 log(slistAST.getLineNo(), 107 slistAST.getColumnNo(), 108 "block.empty", 109 aAST.getText()); 110 } 111 } 112 } 113 } 114 115 119 private boolean hasText(final DetailAST aSlistAST) 120 { 121 boolean retVal = false; 122 123 final DetailAST rcurlyAST = aSlistAST.findFirstToken(TokenTypes.RCURLY); 124 if (rcurlyAST != null) { 125 final int slistLineNo = aSlistAST.getLineNo(); 126 final int slistColNo = aSlistAST.getColumnNo(); 127 final int rcurlyLineNo = rcurlyAST.getLineNo(); 128 final int rcurlyColNo = rcurlyAST.getColumnNo(); 129 final String [] lines = getLines(); 130 if (slistLineNo == rcurlyLineNo) { 131 final String txt = lines[slistLineNo - 1] 133 .substring(slistColNo + 1, rcurlyColNo); 134 if (txt.trim().length() != 0) { 135 retVal = true; 136 } 137 } 138 else { 139 if ((lines[slistLineNo - 1] 141 .substring(slistColNo + 1).trim().length() != 0) 142 || (lines[rcurlyLineNo - 1] 143 .substring(0, rcurlyColNo).trim().length() != 0)) 144 { 145 retVal = true; 146 } 147 else { 148 for (int i = slistLineNo; i < (rcurlyLineNo - 1); i++) { 150 if (lines[i].trim().length() > 0) { 151 retVal = true; 152 break; 153 } 154 } 155 } 156 } 157 } 158 return retVal; 159 } 160 } 161 | Popular Tags |