001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018///////////////////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.naming;
021
022import java.util.Arrays;
023import java.util.Optional;
024
025import com.puppycrawl.tools.checkstyle.api.DetailAST;
026import com.puppycrawl.tools.checkstyle.api.TokenTypes;
027import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
028
029/**
030 * <p>
031 * Checks that method parameter names conform to a specified pattern.
032 * By using {@code accessModifiers} property it is possible
033 * to specify different formats for methods at different visibility levels.
034 * </p>
035 * <p>
036 * To validate {@code catch} parameters please use
037 * <a href="https://checkstyle.org/checks/naming/catchparametername.html#CatchParameterName">
038 * CatchParameterName</a>.
039 * </p>
040 * <p>
041 * To validate lambda parameters please use
042 * <a href="https://checkstyle.org/checks/naming/lambdaparametername.html#LambdaParameterName">
043 * LambdaParameterName</a>.
044 * </p>
045 * <ul>
046 * <li>
047 * Property {@code accessModifiers} - Access modifiers of methods where parameters are
048 * checked.
049 * Type is {@code com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption[]}.
050 * Default value is {@code public, protected, package, private}.
051 * </li>
052 * <li>
053 * Property {@code format} - Sets the pattern to match valid identifiers.
054 * Type is {@code java.util.regex.Pattern}.
055 * Default value is {@code "^[a-z][a-zA-Z0-9]*$"}.
056 * </li>
057 * <li>
058 * Property {@code ignoreOverridden} - Allows to skip methods with Override annotation from
059 * validation.
060 * Type is {@code boolean}.
061 * Default value is {@code false}.
062 * </li>
063 * </ul>
064 * <p>
065 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
066 * </p>
067 * <p>
068 * Violation Message Keys:
069 * </p>
070 * <ul>
071 * <li>
072 * {@code name.invalidPattern}
073 * </li>
074 * </ul>
075 *
076 * @since 3.0
077 */
078public class ParameterNameCheck extends AbstractNameCheck {
079
080    /**
081     * Allows to skip methods with Override annotation from validation.
082     */
083    private boolean ignoreOverridden;
084
085    /** Access modifiers of methods where parameters are checked. */
086    private AccessModifierOption[] accessModifiers = {
087        AccessModifierOption.PUBLIC,
088        AccessModifierOption.PROTECTED,
089        AccessModifierOption.PACKAGE,
090        AccessModifierOption.PRIVATE,
091    };
092
093    /**
094     * Creates a new {@code ParameterNameCheck} instance.
095     */
096    public ParameterNameCheck() {
097        super("^[a-z][a-zA-Z0-9]*$");
098    }
099
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}