1 20 package com.puppycrawl.tools.checkstyle.checks.coding; 21 22 import antlr.collections.AST; 23 import com.puppycrawl.tools.checkstyle.api.Check; 24 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 25 import com.puppycrawl.tools.checkstyle.api.DetailAST; 26 27 28 41 public class SimplifyBooleanReturnCheck 42 extends Check 43 { 44 45 public int[] getDefaultTokens() 46 { 47 return new int[] {TokenTypes.LITERAL_IF}; 48 } 49 50 51 public void visitToken(DetailAST aAST) 52 { 53 60 final AST elseLiteral = 62 aAST.findFirstToken(TokenTypes.LITERAL_ELSE); 63 if (elseLiteral == null) { 64 return; 65 } 66 final AST elseStatement = elseLiteral.getFirstChild(); 67 68 final AST condition = aAST.getFirstChild().getNextSibling(); 71 final AST thenStatement = condition.getNextSibling().getNextSibling(); 72 73 if (returnsOnlyBooleanLiteral(thenStatement) 74 && returnsOnlyBooleanLiteral(elseStatement)) 75 { 76 log(aAST.getLineNo(), aAST.getColumnNo(), "simplify.boolreturn"); 77 } 78 } 79 80 100 private static boolean returnsOnlyBooleanLiteral(AST aAST) 101 { 102 if (isBooleanLiteralReturnStatement(aAST)) { 103 return true; 104 } 105 106 final AST firstStmnt = aAST.getFirstChild(); 107 return isBooleanLiteralReturnStatement(firstStmnt); 108 } 109 110 122 private static boolean isBooleanLiteralReturnStatement(AST aAST) 123 { 124 if ((aAST == null) || (aAST.getType() != TokenTypes.LITERAL_RETURN)) { 125 return false; 126 } 127 128 final AST expr = aAST.getFirstChild(); 129 130 if ((expr == null) || (expr.getType() == TokenTypes.SEMI)) { 131 return false; 132 } 133 134 final AST value = expr.getFirstChild(); 135 return isBooleanLiteralType(value.getType()); 136 } 137 138 143 private static boolean isBooleanLiteralType(final int aTokenType) 144 { 145 final boolean isTrue = (aTokenType == TokenTypes.LITERAL_TRUE); 146 final boolean isFalse = (aTokenType == TokenTypes.LITERAL_FALSE); 147 return isTrue || isFalse; 148 } 149 } 150 | Popular Tags |