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.naming;
21  
22  import java.util.Arrays;
23  import java.util.Optional;
24  
25  import com.puppycrawl.tools.checkstyle.api.DetailAST;
26  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
27  import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
28  
29  /**
30   * <div>
31   * Checks that method parameter names conform to a specified pattern.
32   * By using {@code accessModifiers} property it is possible
33   * to specify different formats for methods at different visibility levels.
34   * </div>
35   *
36   * <p>
37   * To validate {@code catch} parameters please use
38   * <a href="https://checkstyle.org/checks/naming/catchparametername.html#CatchParameterName">
39   * CatchParameterName</a>.
40   * </p>
41   *
42   * <p>
43   * To validate lambda parameters please use
44   * <a href="https://checkstyle.org/checks/naming/lambdaparametername.html#LambdaParameterName">
45   * LambdaParameterName</a>.
46   * </p>
47   * <ul>
48   * <li>
49   * Property {@code accessModifiers} - Access modifiers of methods where parameters are
50   * checked.
51   * Type is {@code com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption[]}.
52   * Default value is {@code public, protected, package, private}.
53   * </li>
54   * <li>
55   * Property {@code format} - Sets the pattern to match valid identifiers.
56   * Type is {@code java.util.regex.Pattern}.
57   * Default value is {@code "^[a-z][a-zA-Z0-9]*$"}.
58   * </li>
59   * <li>
60   * Property {@code ignoreOverridden} - Allows to skip methods with Override annotation from
61   * validation.
62   * Type is {@code boolean}.
63   * Default value is {@code false}.
64   * </li>
65   * </ul>
66   *
67   * <p>
68   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
69   * </p>
70   *
71   * <p>
72   * Violation Message Keys:
73   * </p>
74   * <ul>
75   * <li>
76   * {@code name.invalidPattern}
77   * </li>
78   * </ul>
79   *
80   * @since 3.0
81   */
82  public class ParameterNameCheck extends AbstractNameCheck {
83  
84      /**
85       * Allows to skip methods with Override annotation from validation.
86       */
87      private boolean ignoreOverridden;
88  
89      /** Access modifiers of methods where parameters are checked. */
90      private AccessModifierOption[] accessModifiers = {
91          AccessModifierOption.PUBLIC,
92          AccessModifierOption.PROTECTED,
93          AccessModifierOption.PACKAGE,
94          AccessModifierOption.PRIVATE,
95      };
96  
97      /**
98       * Creates a new {@code ParameterNameCheck} instance.
99       */
100     public ParameterNameCheck() {
101         super("^[a-z][a-zA-Z0-9]*$");
102     }
103 
104     /**
105      * Setter to allows to skip methods with Override annotation from validation.
106      *
107      * @param ignoreOverridden Flag for skipping methods with Override annotation.
108      * @since 6.12.1
109      */
110     public void setIgnoreOverridden(boolean ignoreOverridden) {
111         this.ignoreOverridden = ignoreOverridden;
112     }
113 
114     /**
115      * Setter to access modifiers of methods where parameters are checked.
116      *
117      * @param accessModifiers access modifiers of methods which should be checked.
118      * @since 7.5
119      */
120     public void setAccessModifiers(AccessModifierOption... accessModifiers) {
121         this.accessModifiers =
122             Arrays.copyOf(accessModifiers, accessModifiers.length);
123     }
124 
125     @Override
126     public int[] getDefaultTokens() {
127         return getRequiredTokens();
128     }
129 
130     @Override
131     public int[] getAcceptableTokens() {
132         return getRequiredTokens();
133     }
134 
135     @Override
136     public int[] getRequiredTokens() {
137         return new int[] {TokenTypes.PARAMETER_DEF};
138     }
139 
140     @Override
141     protected boolean mustCheckName(DetailAST ast) {
142         boolean checkName = true;
143         final DetailAST parent = ast.getParent();
144         if (ignoreOverridden && isOverriddenMethod(ast)
145                 || parent.getType() == TokenTypes.LITERAL_CATCH
146                 || parent.getParent().getType() == TokenTypes.LAMBDA
147                 || CheckUtil.isReceiverParameter(ast)
148                 || !matchAccessModifiers(
149                         CheckUtil.getAccessModifierFromModifiersToken(parent.getParent()))) {
150             checkName = false;
151         }
152         return checkName;
153     }
154 
155     /**
156      * Checks whether a method has the correct access modifier to be checked.
157      *
158      * @param accessModifier the access modifier of the method.
159      * @return whether the method matches the expected access modifier.
160      */
161     private boolean matchAccessModifiers(final AccessModifierOption accessModifier) {
162         return Arrays.stream(accessModifiers)
163                 .anyMatch(modifier -> modifier == accessModifier);
164     }
165 
166     /**
167      * Checks whether a method is annotated with Override annotation.
168      *
169      * @param ast method parameter definition token.
170      * @return true if a method is annotated with Override annotation.
171      */
172     private static boolean isOverriddenMethod(DetailAST ast) {
173         boolean overridden = false;
174 
175         final DetailAST parent = ast.getParent().getParent();
176         final Optional<DetailAST> annotation =
177             Optional.ofNullable(parent.getFirstChild().getFirstChild());
178 
179         if (annotation.isPresent()) {
180             final Optional<DetailAST> overrideToken =
181                 Optional.ofNullable(annotation.orElseThrow().findFirstToken(TokenTypes.IDENT));
182             if (overrideToken.isPresent()
183                 && "Override".equals(overrideToken.orElseThrow().getText())) {
184                 overridden = true;
185             }
186         }
187         return overridden;
188     }
189 
190 }