001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.coding;
021
022import antlr.collections.AST;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.TokenTypes;
026
027/**
028 * <p>
029 * Checks for overly complicated boolean return statements.
030 * Idea shamelessly stolen from the equivalent PMD rule (pmd.sourceforge.net).
031 * </p>
032 * <p>
033 * An example of how to configure the check is:
034 * </p>
035 * <pre>
036 * &lt;module name="SimplifyBooleanReturn"/&gt;
037 * </pre>
038 * @author Lars Kühne
039 */
040public class SimplifyBooleanReturnCheck
041    extends AbstractCheck {
042
043    /**
044     * A key is pointing to the warning message text in "messages.properties"
045     * file.
046     */
047    public static final String MSG_KEY = "simplify.boolReturn";
048
049    @Override
050    public int[] getAcceptableTokens() {
051        return new int[] {TokenTypes.LITERAL_IF};
052    }
053
054    @Override
055    public int[] getDefaultTokens() {
056        return getAcceptableTokens();
057    }
058
059    @Override
060    public int[] getRequiredTokens() {
061        return getAcceptableTokens();
062    }
063
064    @Override
065    public void visitToken(DetailAST ast) {
066        // LITERAL_IF has the following four or five children:
067        // '('
068        // condition
069        // ')'
070        // thenStatement
071        // [ LITERAL_ELSE (with the elseStatement as a child) ]
072
073        // don't bother if this is not if then else
074        final AST elseLiteral =
075            ast.findFirstToken(TokenTypes.LITERAL_ELSE);
076        if (elseLiteral != null) {
077            final AST elseStatement = elseLiteral.getFirstChild();
078
079            // skip '(' and ')'
080            final AST condition = ast.getFirstChild().getNextSibling();
081            final AST thenStatement = condition.getNextSibling().getNextSibling();
082
083            if (canReturnOnlyBooleanLiteral(thenStatement)
084                && canReturnOnlyBooleanLiteral(elseStatement)) {
085                log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY);
086            }
087        }
088    }
089
090    /**
091     * Returns if an AST is a return statement with a boolean literal
092     * or a compound statement that contains only such a return statement.
093     *
094     * <p>Returns {@code true} iff ast represents
095     * <br/>
096     * <pre>
097     * return true/false;
098     * </pre>
099     * or
100     * <br/>
101     * <pre>
102     * {
103     *   return true/false;
104     * }
105     * </pre>
106     *
107     * @param ast the syntax tree to check
108     * @return if ast is a return statement with a boolean literal.
109     */
110    private static boolean canReturnOnlyBooleanLiteral(AST ast) {
111        if (isBooleanLiteralReturnStatement(ast)) {
112            return true;
113        }
114
115        final AST firstStatement = ast.getFirstChild();
116        return isBooleanLiteralReturnStatement(firstStatement);
117    }
118
119    /**
120     * Returns if an AST is a return statement with a boolean literal.
121     *
122     * <p>Returns {@code true} iff ast represents
123     * <br/>
124     * <pre>
125     * return true/false;
126     * </pre>
127     *
128     * @param ast the syntax tree to check
129     * @return if ast is a return statement with a boolean literal.
130     */
131    private static boolean isBooleanLiteralReturnStatement(AST ast) {
132        boolean booleanReturnStatement = false;
133
134        if (ast != null && ast.getType() == TokenTypes.LITERAL_RETURN) {
135            final AST expr = ast.getFirstChild();
136
137            if (expr.getType() != TokenTypes.SEMI) {
138                final AST value = expr.getFirstChild();
139                booleanReturnStatement = isBooleanLiteralType(value.getType());
140            }
141        }
142        return booleanReturnStatement;
143    }
144
145    /**
146     * Checks if a token type is a literal true or false.
147     * @param tokenType the TokenType
148     * @return true iff tokenType is LITERAL_TRUE or LITERAL_FALSE
149     */
150    private static boolean isBooleanLiteralType(final int tokenType) {
151        final boolean isTrue = tokenType == TokenTypes.LITERAL_TRUE;
152        final boolean isFalse = tokenType == TokenTypes.LITERAL_FALSE;
153        return isTrue || isFalse;
154    }
155}