View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.coding;
21  
22  import com.puppycrawl.tools.checkstyle.StatelessCheck;
23  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
24  import com.puppycrawl.tools.checkstyle.api.DetailAST;
25  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
26  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
27  
28  /**
29   * <p>
30   * Checks for over-complicated boolean return statements.
31   * For example the following code
32   * </p>
33   * <pre>
34   * if (valid())
35   *   return false;
36   * else
37   *   return true;
38   * </pre>
39   * <p>
40   * could be written as
41   * </p>
42   * <pre>
43   * return !valid();
44   * </pre>
45   * <p>
46   * The idea for this Check has been shamelessly stolen from the equivalent
47   * <a href="https://pmd.github.io/pmd/pmd_rules_java_design.html#simplifybooleanreturns">
48   *     PMD</a> rule.
49   * </p>
50   * <p>
51   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
52   * </p>
53   * <p>
54   * Violation Message Keys:
55   * </p>
56   * <ul>
57   * <li>
58   * {@code simplify.boolReturn}
59   * </li>
60   * </ul>
61   *
62   * @since 3.0
63   */
64  @StatelessCheck
65  public class SimplifyBooleanReturnCheck
66      extends AbstractCheck {
67  
68      /**
69       * A key is pointing to the warning message text in "messages.properties"
70       * file.
71       */
72      public static final String MSG_KEY = "simplify.boolReturn";
73  
74      @Override
75      public int[] getAcceptableTokens() {
76          return getRequiredTokens();
77      }
78  
79      @Override
80      public int[] getDefaultTokens() {
81          return getRequiredTokens();
82      }
83  
84      @Override
85      public int[] getRequiredTokens() {
86          return new int[] {TokenTypes.LITERAL_IF};
87      }
88  
89      @Override
90      public void visitToken(DetailAST ast) {
91          // LITERAL_IF has the following four or five children:
92          // '('
93          // condition
94          // ')'
95          // thenStatement
96          // [ LITERAL_ELSE (with the elseStatement as a child) ]
97  
98          // don't bother if this is not if then else
99          final DetailAST elseLiteral =
100             ast.findFirstToken(TokenTypes.LITERAL_ELSE);
101         if (elseLiteral != null) {
102             final DetailAST elseStatement = elseLiteral.getFirstChild();
103 
104             // skip '(' and ')'
105             final DetailAST condition = ast.getFirstChild().getNextSibling();
106             final DetailAST thenStatement = condition.getNextSibling().getNextSibling();
107 
108             if (canReturnOnlyBooleanLiteral(thenStatement)
109                 && canReturnOnlyBooleanLiteral(elseStatement)) {
110                 log(ast, MSG_KEY);
111             }
112         }
113     }
114 
115     /**
116      * Returns if an AST is a return statement with a boolean literal
117      * or a compound statement that contains only such a return statement.
118      *
119      * <p>Returns {@code true} iff ast represents
120      * <pre>
121      * return true/false;
122      * </pre>
123      * or
124      * <pre>
125      * {
126      *   return true/false;
127      * }
128      * </pre>
129      *
130      * @param ast the syntax tree to check
131      * @return if ast is a return statement with a boolean literal.
132      */
133     private static boolean canReturnOnlyBooleanLiteral(DetailAST ast) {
134         boolean result = true;
135         if (!isBooleanLiteralReturnStatement(ast)) {
136             final DetailAST firstStatement = ast.getFirstChild();
137             result = isBooleanLiteralReturnStatement(firstStatement);
138         }
139         return result;
140     }
141 
142     /**
143      * Returns if an AST is a return statement with a boolean literal.
144      *
145      * <p>Returns {@code true} iff ast represents
146      * <pre>
147      * return true/false;
148      * </pre>
149      *
150      * @param ast the syntax tree to check
151      * @return if ast is a return statement with a boolean literal.
152      */
153     private static boolean isBooleanLiteralReturnStatement(DetailAST ast) {
154         boolean booleanReturnStatement = false;
155 
156         if (ast != null && ast.getType() == TokenTypes.LITERAL_RETURN) {
157             final DetailAST expr = ast.getFirstChild();
158 
159             if (expr.getType() != TokenTypes.SEMI) {
160                 final DetailAST value = expr.getFirstChild();
161                 booleanReturnStatement = TokenUtil.isBooleanLiteralType(value.getType());
162             }
163         }
164         return booleanReturnStatement;
165     }
166 }