1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2019 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 java.util.Arrays;
23  
24  import com.puppycrawl.tools.checkstyle.StatelessCheck;
25  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
26  import com.puppycrawl.tools.checkstyle.api.DetailAST;
27  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
28  
29  /**
30   * <p>
31   * Checks for assignments in subexpressions, such as in
32   * {@code String s = Integer.toString(i = 2);}.
33   * </p>
34   * <p>
35   * Rationale: With the exception of {@code for} iterators and assignment in {@code while} idiom,
36   * all assignments should occur in their own top-level statement to increase readability.
37   * With inner assignments like the one given above, it is difficult to see all places
38   * where a variable is set.
39   * </p>
40   * <p>
41   * Note: Check allows usage of the popular assignment in {@code while} idiom:
42   * </p>
43   * <pre>
44   * String line;
45   * while ((line = bufferedReader.readLine()) != null) {
46   *   // process the line
47   * }
48   * </pre>
49   * <p>
50   * Assignment inside a condition is not a problem here, as the assignment is surrounded
51   * by an extra pair of parentheses. The comparison is {@code != null} and there is no chance that
52   * intention was to write {@code line == reader.readLine()}.
53   * </p>
54   * <p>
55   * To configure the check:
56   * </p>
57   * <pre>
58   * &lt;module name=&quot;InnerAssignment"/&gt;
59   * </pre>
60   *
61   * @since 3.0
62   */
63  @StatelessCheck
64  public class InnerAssignmentCheck
65          extends AbstractCheck {
66  
67      /**
68       * A key is pointing to the warning message text in "messages.properties"
69       * file.
70       */
71      public static final String MSG_KEY = "assignment.inner.avoid";
72  
73      /**
74       * List of allowed AST types from an assignment AST node
75       * towards the root.
76       */
77      private static final int[][] ALLOWED_ASSIGNMENT_CONTEXT = {
78          {TokenTypes.EXPR, TokenTypes.SLIST},
79          {TokenTypes.VARIABLE_DEF},
80          {TokenTypes.EXPR, TokenTypes.ELIST, TokenTypes.FOR_INIT},
81          {TokenTypes.EXPR, TokenTypes.ELIST, TokenTypes.FOR_ITERATOR},
82          {TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR}, {
83              TokenTypes.RESOURCE,
84              TokenTypes.RESOURCES,
85              TokenTypes.RESOURCE_SPECIFICATION,
86          },
87          {TokenTypes.EXPR, TokenTypes.LAMBDA},
88      };
89  
90      /**
91       * List of allowed AST types from an assignment AST node
92       * towards the root.
93       */
94      private static final int[][] CONTROL_CONTEXT = {
95          {TokenTypes.EXPR, TokenTypes.LITERAL_DO},
96          {TokenTypes.EXPR, TokenTypes.LITERAL_FOR},
97          {TokenTypes.EXPR, TokenTypes.LITERAL_WHILE},
98          {TokenTypes.EXPR, TokenTypes.LITERAL_IF},
99          {TokenTypes.EXPR, TokenTypes.LITERAL_ELSE},
100     };
101 
102     /**
103      * List of allowed AST types from a comparison node (above an assignment)
104      * towards the root.
105      */
106     private static final int[][] ALLOWED_ASSIGNMENT_IN_COMPARISON_CONTEXT = {
107         {TokenTypes.EXPR, TokenTypes.LITERAL_WHILE, },
108     };
109 
110     /**
111      * The token types that identify comparison operators.
112      */
113     private static final int[] COMPARISON_TYPES = {
114         TokenTypes.EQUAL,
115         TokenTypes.GE,
116         TokenTypes.GT,
117         TokenTypes.LE,
118         TokenTypes.LT,
119         TokenTypes.NOT_EQUAL,
120     };
121 
122     static {
123         Arrays.sort(COMPARISON_TYPES);
124     }
125 
126     @Override
127     public int[] getDefaultTokens() {
128         return getRequiredTokens();
129     }
130 
131     @Override
132     public int[] getAcceptableTokens() {
133         return getRequiredTokens();
134     }
135 
136     @Override
137     public int[] getRequiredTokens() {
138         return new int[] {
139             TokenTypes.ASSIGN,            // '='
140             TokenTypes.DIV_ASSIGN,        // "/="
141             TokenTypes.PLUS_ASSIGN,       // "+="
142             TokenTypes.MINUS_ASSIGN,      //"-="
143             TokenTypes.STAR_ASSIGN,       // "*="
144             TokenTypes.MOD_ASSIGN,        // "%="
145             TokenTypes.SR_ASSIGN,         // ">>="
146             TokenTypes.BSR_ASSIGN,        // ">>>="
147             TokenTypes.SL_ASSIGN,         // "<<="
148             TokenTypes.BXOR_ASSIGN,       // "^="
149             TokenTypes.BOR_ASSIGN,        // "|="
150             TokenTypes.BAND_ASSIGN,       // "&="
151         };
152     }
153 
154     @Override
155     public void visitToken(DetailAST ast) {
156         if (!isInContext(ast, ALLOWED_ASSIGNMENT_CONTEXT)
157                 && !isInNoBraceControlStatement(ast)
158                 && !isInWhileIdiom(ast)) {
159             log(ast, MSG_KEY);
160         }
161     }
162 
163     /**
164      * Determines if ast is in the body of a flow control statement without
165      * braces. An example of such a statement would be
166      * <p>
167      * <pre>
168      * if (y < 0)
169      *     x = y;
170      * </pre>
171      * </p>
172      * <p>
173      * This leads to the following AST structure:
174      * </p>
175      * <p>
176      * <pre>
177      * LITERAL_IF
178      *     LPAREN
179      *     EXPR // test
180      *     RPAREN
181      *     EXPR // body
182      *     SEMI
183      * </pre>
184      * </p>
185      * <p>
186      * We need to ensure that ast is in the body and not in the test.
187      * </p>
188      *
189      * @param ast an assignment operator AST
190      * @return whether ast is in the body of a flow control statement
191      */
192     private static boolean isInNoBraceControlStatement(DetailAST ast) {
193         boolean result = false;
194         if (isInContext(ast, CONTROL_CONTEXT)) {
195             final DetailAST expr = ast.getParent();
196             final DetailAST exprNext = expr.getNextSibling();
197             result = exprNext.getType() == TokenTypes.SEMI;
198         }
199         return result;
200     }
201 
202     /**
203      * Tests whether the given AST is used in the "assignment in while" idiom.
204      * <pre>
205      * String line;
206      * while ((line = bufferedReader.readLine()) != null) {
207      *    // process the line
208      * }
209      * </pre>
210      * Assignment inside a condition is not a problem here, as the assignment is surrounded by an
211      * extra pair of parentheses. The comparison is {@code != null} and there is no chance that
212      * intention was to write {@code line == reader.readLine()}.
213      *
214      * @param ast assignment AST
215      * @return whether the context of the assignment AST indicates the idiom
216      */
217     private static boolean isInWhileIdiom(DetailAST ast) {
218         boolean result = false;
219         if (isComparison(ast.getParent())) {
220             result = isInContext(
221                     ast.getParent(), ALLOWED_ASSIGNMENT_IN_COMPARISON_CONTEXT);
222         }
223         return result;
224     }
225 
226     /**
227      * Checks if an AST is a comparison operator.
228      * @param ast the AST to check
229      * @return true iff ast is a comparison operator.
230      */
231     private static boolean isComparison(DetailAST ast) {
232         final int astType = ast.getType();
233         return Arrays.binarySearch(COMPARISON_TYPES, astType) >= 0;
234     }
235 
236     /**
237      * Tests whether the provided AST is in
238      * one of the given contexts.
239      *
240      * @param ast the AST from which to start walking towards root
241      * @param contextSet the contexts to test against.
242      *
243      * @return whether the parents nodes of ast match one of the allowed type paths.
244      */
245     private static boolean isInContext(DetailAST ast, int[]... contextSet) {
246         boolean found = false;
247         for (int[] element : contextSet) {
248             DetailAST current = ast;
249             for (int anElement : element) {
250                 current = current.getParent();
251                 if (current.getType() == anElement) {
252                     found = true;
253                 }
254                 else {
255                     found = false;
256                     break;
257                 }
258             }
259 
260             if (found) {
261                 break;
262             }
263         }
264         return found;
265     }
266 
267 }