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;
21  
22  import java.util.Arrays;
23  import java.util.Collections;
24  import java.util.Set;
25  import java.util.stream.Collectors;
26  
27  import com.puppycrawl.tools.checkstyle.StatelessCheck;
28  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
29  import com.puppycrawl.tools.checkstyle.api.DetailAST;
30  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
31  import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
32  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
33  
34  /**
35   * Check that method/constructor/catch/foreach parameters are final.
36   * The user can set the token set to METHOD_DEF, CONSTRUCTOR_DEF,
37   * LITERAL_CATCH, FOR_EACH_CLAUSE or any combination of these token
38   * types, to control the scope of this check.
39   * Default scope is both METHOD_DEF and CONSTRUCTOR_DEF.
40   * <p>
41   * Check has an option <b>ignorePrimitiveTypes</b> which allows ignoring lack of
42   * final modifier at
43   * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">
44   *  primitive data type</a> parameter. Default value <b>false</b>.
45   * </p>
46   * E.g.:
47   * <p>
48   * {@code
49   * private void foo(int x) { ... } //parameter is of primitive type
50   * }
51   * </p>
52   *
53   */
54  @StatelessCheck
55  public class FinalParametersCheck extends AbstractCheck {
56  
57      /**
58       * A key is pointing to the warning message text in "messages.properties"
59       * file.
60       */
61      public static final String MSG_KEY = "final.parameter";
62  
63      /**
64       * Contains
65       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">
66       * primitive datatypes</a>.
67       */
68      private final Set<Integer> primitiveDataTypes = Collections.unmodifiableSet(
69          Arrays.stream(new Integer[] {
70              TokenTypes.LITERAL_BYTE,
71              TokenTypes.LITERAL_SHORT,
72              TokenTypes.LITERAL_INT,
73              TokenTypes.LITERAL_LONG,
74              TokenTypes.LITERAL_FLOAT,
75              TokenTypes.LITERAL_DOUBLE,
76              TokenTypes.LITERAL_BOOLEAN,
77              TokenTypes.LITERAL_CHAR, })
78          .collect(Collectors.toSet()));
79  
80      /**
81       * Option to ignore primitive types as params.
82       */
83      private boolean ignorePrimitiveTypes;
84  
85      /**
86       * Sets ignoring primitive types as params.
87       * @param ignorePrimitiveTypes true or false.
88       */
89      public void setIgnorePrimitiveTypes(boolean ignorePrimitiveTypes) {
90          this.ignorePrimitiveTypes = ignorePrimitiveTypes;
91      }
92  
93      @Override
94      public int[] getDefaultTokens() {
95          return new int[] {
96              TokenTypes.METHOD_DEF,
97              TokenTypes.CTOR_DEF,
98          };
99      }
100 
101     @Override
102     public int[] getAcceptableTokens() {
103         return new int[] {
104             TokenTypes.METHOD_DEF,
105             TokenTypes.CTOR_DEF,
106             TokenTypes.LITERAL_CATCH,
107             TokenTypes.FOR_EACH_CLAUSE,
108         };
109     }
110 
111     @Override
112     public int[] getRequiredTokens() {
113         return CommonUtil.EMPTY_INT_ARRAY;
114     }
115 
116     @Override
117     public void visitToken(DetailAST ast) {
118         // don't flag interfaces
119         final DetailAST container = ast.getParent().getParent();
120         if (container.getType() != TokenTypes.INTERFACE_DEF) {
121             if (ast.getType() == TokenTypes.LITERAL_CATCH) {
122                 visitCatch(ast);
123             }
124             else if (ast.getType() == TokenTypes.FOR_EACH_CLAUSE) {
125                 visitForEachClause(ast);
126             }
127             else {
128                 visitMethod(ast);
129             }
130         }
131     }
132 
133     /**
134      * Checks parameters of the method or ctor.
135      * @param method method or ctor to check.
136      */
137     private void visitMethod(final DetailAST method) {
138         final DetailAST modifiers =
139             method.findFirstToken(TokenTypes.MODIFIERS);
140 
141         // ignore abstract and native methods
142         if (modifiers.findFirstToken(TokenTypes.ABSTRACT) == null
143                 && modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) == null) {
144             final DetailAST parameters =
145                 method.findFirstToken(TokenTypes.PARAMETERS);
146             DetailAST child = parameters.getFirstChild();
147             while (child != null) {
148                 // children are PARAMETER_DEF and COMMA
149                 if (child.getType() == TokenTypes.PARAMETER_DEF) {
150                     checkParam(child);
151                 }
152                 child = child.getNextSibling();
153             }
154         }
155     }
156 
157     /**
158      * Checks parameter of the catch block.
159      * @param catchClause catch block to check.
160      */
161     private void visitCatch(final DetailAST catchClause) {
162         checkParam(catchClause.findFirstToken(TokenTypes.PARAMETER_DEF));
163     }
164 
165     /**
166      * Checks parameter of the for each clause.
167      * @param forEachClause for each clause to check.
168      */
169     private void visitForEachClause(final DetailAST forEachClause) {
170         checkParam(forEachClause.findFirstToken(TokenTypes.VARIABLE_DEF));
171     }
172 
173     /**
174      * Checks if the given parameter is final.
175      * @param param parameter to check.
176      */
177     private void checkParam(final DetailAST param) {
178         if (param.findFirstToken(TokenTypes.MODIFIERS).findFirstToken(TokenTypes.FINAL) == null
179                 && !isIgnoredParam(param)
180                 && !CheckUtil.isReceiverParameter(param)) {
181             final DetailAST paramName = param.findFirstToken(TokenTypes.IDENT);
182             final DetailAST firstNode = CheckUtil.getFirstNode(param);
183             log(firstNode,
184                 MSG_KEY, paramName.getText());
185         }
186     }
187 
188     /**
189      * Checks for skip current param due to <b>ignorePrimitiveTypes</b> option.
190      * @param paramDef {@link TokenTypes#PARAMETER_DEF PARAMETER_DEF}
191      * @return true if param has to be skipped.
192      */
193     private boolean isIgnoredParam(DetailAST paramDef) {
194         boolean result = false;
195         if (ignorePrimitiveTypes) {
196             final DetailAST parameterType = paramDef
197                 .findFirstToken(TokenTypes.TYPE).getFirstChild();
198             if (primitiveDataTypes.contains(parameterType.getType())) {
199                 result = true;
200             }
201         }
202         return result;
203     }
204 
205 }