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;
21  
22  import java.util.BitSet;
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  import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
29  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
30  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
31  
32  /**
33   * <p>
34   * Checks that parameters for methods, constructors, catch and for-each blocks are final.
35   * Interface, abstract, and native methods are not checked: the final keyword
36   * does not make sense for interface, abstract, and native method parameters as
37   * there is no code that could modify the parameter.
38   * </p>
39   * <p>
40   * Rationale: Changing the value of parameters during the execution of the method's
41   * algorithm can be confusing and should be avoided. A great way to let the Java compiler
42   * prevent this coding style is to declare parameters final.
43   * </p>
44   * <ul>
45   * <li>
46   * Property {@code ignorePrimitiveTypes} - Ignore primitive types as parameters.
47   * Type is {@code boolean}.
48   * Default value is {@code false}.
49   * </li>
50   * <li>
51   * Property {@code tokens} - tokens to check
52   * Type is {@code java.lang.String[]}.
53   * Validation type is {@code tokenSet}.
54   * Default value is:
55   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#METHOD_DEF">
56   * METHOD_DEF</a>,
57   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#CTOR_DEF">
58   * CTOR_DEF</a>.
59   * </li>
60   * </ul>
61   * <p>
62   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
63   * </p>
64   * <p>
65   * Violation Message Keys:
66   * </p>
67   * <ul>
68   * <li>
69   * {@code final.parameter}
70   * </li>
71   * </ul>
72   *
73   * @since 3.0
74   */
75  @StatelessCheck
76  public class FinalParametersCheck extends AbstractCheck {
77  
78      /**
79       * A key is pointing to the warning message text in "messages.properties"
80       * file.
81       */
82      public static final String MSG_KEY = "final.parameter";
83  
84      /**
85       * Contains
86       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">
87       * primitive datatypes</a>.
88       */
89      private final BitSet primitiveDataTypes = TokenUtil.asBitSet(
90          TokenTypes.LITERAL_BYTE,
91          TokenTypes.LITERAL_SHORT,
92          TokenTypes.LITERAL_INT,
93          TokenTypes.LITERAL_LONG,
94          TokenTypes.LITERAL_FLOAT,
95          TokenTypes.LITERAL_DOUBLE,
96          TokenTypes.LITERAL_BOOLEAN,
97          TokenTypes.LITERAL_CHAR
98      );
99  
100     /**
101      * Ignore primitive types as parameters.
102      */
103     private boolean ignorePrimitiveTypes;
104 
105     /**
106      * Setter to ignore primitive types as parameters.
107      *
108      * @param ignorePrimitiveTypes true or false.
109      * @since 6.2
110      */
111     public void setIgnorePrimitiveTypes(boolean ignorePrimitiveTypes) {
112         this.ignorePrimitiveTypes = ignorePrimitiveTypes;
113     }
114 
115     @Override
116     public int[] getDefaultTokens() {
117         return new int[] {
118             TokenTypes.METHOD_DEF,
119             TokenTypes.CTOR_DEF,
120         };
121     }
122 
123     @Override
124     public int[] getAcceptableTokens() {
125         return new int[] {
126             TokenTypes.METHOD_DEF,
127             TokenTypes.CTOR_DEF,
128             TokenTypes.LITERAL_CATCH,
129             TokenTypes.FOR_EACH_CLAUSE,
130         };
131     }
132 
133     @Override
134     public int[] getRequiredTokens() {
135         return CommonUtil.EMPTY_INT_ARRAY;
136     }
137 
138     @Override
139     public void visitToken(DetailAST ast) {
140         // don't flag interfaces
141         final DetailAST container = ast.getParent().getParent();
142         if (container.getType() != TokenTypes.INTERFACE_DEF) {
143             if (ast.getType() == TokenTypes.LITERAL_CATCH) {
144                 visitCatch(ast);
145             }
146             else if (ast.getType() == TokenTypes.FOR_EACH_CLAUSE) {
147                 visitForEachClause(ast);
148             }
149             else {
150                 visitMethod(ast);
151             }
152         }
153     }
154 
155     /**
156      * Checks parameters of the method or ctor.
157      *
158      * @param method method or ctor to check.
159      */
160     private void visitMethod(final DetailAST method) {
161         final DetailAST modifiers =
162             method.findFirstToken(TokenTypes.MODIFIERS);
163 
164         // ignore abstract and native methods
165         if (modifiers.findFirstToken(TokenTypes.ABSTRACT) == null
166                 && modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) == null) {
167             final DetailAST parameters =
168                 method.findFirstToken(TokenTypes.PARAMETERS);
169             TokenUtil.forEachChild(parameters, TokenTypes.PARAMETER_DEF, this::checkParam);
170         }
171     }
172 
173     /**
174      * Checks parameter of the catch block.
175      *
176      * @param catchClause catch block to check.
177      */
178     private void visitCatch(final DetailAST catchClause) {
179         checkParam(catchClause.findFirstToken(TokenTypes.PARAMETER_DEF));
180     }
181 
182     /**
183      * Checks parameter of the for each clause.
184      *
185      * @param forEachClause for each clause to check.
186      */
187     private void visitForEachClause(final DetailAST forEachClause) {
188         checkParam(forEachClause.findFirstToken(TokenTypes.VARIABLE_DEF));
189     }
190 
191     /**
192      * Checks if the given parameter is final.
193      *
194      * @param param parameter to check.
195      */
196     private void checkParam(final DetailAST param) {
197         if (param.findFirstToken(TokenTypes.MODIFIERS).findFirstToken(TokenTypes.FINAL) == null
198                 && !isIgnoredParam(param)
199                 && !CheckUtil.isReceiverParameter(param)) {
200             final DetailAST paramName = param.findFirstToken(TokenTypes.IDENT);
201             final DetailAST firstNode = CheckUtil.getFirstNode(param);
202             log(firstNode,
203                 MSG_KEY, paramName.getText());
204         }
205     }
206 
207     /**
208      * Checks for skip current param due to <b>ignorePrimitiveTypes</b> option.
209      *
210      * @param paramDef {@link TokenTypes#PARAMETER_DEF PARAMETER_DEF}
211      * @return true if param has to be skipped.
212      */
213     private boolean isIgnoredParam(DetailAST paramDef) {
214         boolean result = false;
215         if (ignorePrimitiveTypes) {
216             final DetailAST type = paramDef.findFirstToken(TokenTypes.TYPE);
217             final DetailAST parameterType = type.getFirstChild();
218             final DetailAST arrayDeclarator = type
219                     .findFirstToken(TokenTypes.ARRAY_DECLARATOR);
220             if (arrayDeclarator == null
221                     && primitiveDataTypes.get(parameterType.getType())) {
222                 result = true;
223             }
224         }
225         return result;
226     }
227 
228 }