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