001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2018 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.CheckUtils;
028import com.puppycrawl.tools.checkstyle.utils.ScopeUtils;
029
030/**
031 * <p>
032 * Checks that method and {@code catch} parameter names conform to a format specified
033 * by the format property. The format is a
034 * {@link java.util.regex.Pattern regular expression}
035 * and defaults to
036 * <strong>^[a-z][a-zA-Z0-9]*$</strong>.
037 * </p>
038 * <p>The check has the following options:</p>
039 * <p><b>ignoreOverridden</b> - allows to skip methods with Override annotation from
040 * validation. Default values is <b>false</b> .</p>
041 * <p><b>accessModifiers</b> - access modifiers of methods which should to be checked.
042 * Default value is <b>public, protected, package, private</b> .</p>
043 * An example of how to configure the check:
044 * <pre>
045 * &lt;module name="ParameterName"/&gt;
046 * </pre>
047 * <p>
048 * An example of how to configure the check for names that begin with
049 * a lower case letter, followed by letters, digits, and underscores:
050 * </p>
051 * <pre>
052 * &lt;module name="ParameterName"&gt;
053 *    &lt;property name="format" value="^[a-z][_a-zA-Z0-9]+$"/&gt;
054 * &lt;/module&gt;
055 * </pre>
056 * <p>
057 * An example of how to configure the check to skip methods with Override annotation from
058 * validation:
059 * </p>
060 * <pre>
061 * &lt;module name="ParameterName"&gt;
062 *    &lt;property name="ignoreOverridden" value="true"/&gt;
063 * &lt;/module&gt;
064 * </pre>
065 *
066 * @author Oliver Burn
067 * @author Andrei Selkin
068 */
069public class ParameterNameCheck extends AbstractNameCheck {
070
071    /**
072     * Allows to skip methods with Override annotation from validation.
073     */
074    private boolean ignoreOverridden;
075
076    /** Access modifiers of methods which should be checked. */
077    private AccessModifier[] accessModifiers = {
078        AccessModifier.PUBLIC,
079        AccessModifier.PROTECTED,
080        AccessModifier.PACKAGE,
081        AccessModifier.PRIVATE,
082    };
083
084    /**
085     * Creates a new {@code ParameterNameCheck} instance.
086     */
087    public ParameterNameCheck() {
088        super("^[a-z][a-zA-Z0-9]*$");
089    }
090
091    /**
092     * Sets whether to skip methods with Override annotation from validation.
093     * @param ignoreOverridden Flag for skipping methods with Override annotation.
094     */
095    public void setIgnoreOverridden(boolean ignoreOverridden) {
096        this.ignoreOverridden = ignoreOverridden;
097    }
098
099    /**
100     * Sets access modifiers of methods which should be checked.
101     * @param accessModifiers access modifiers of methods which should be checked.
102     */
103    public void setAccessModifiers(AccessModifier... accessModifiers) {
104        this.accessModifiers =
105            Arrays.copyOf(accessModifiers, accessModifiers.length);
106    }
107
108    @Override
109    public int[] getDefaultTokens() {
110        return getRequiredTokens();
111    }
112
113    @Override
114    public int[] getAcceptableTokens() {
115        return getRequiredTokens();
116    }
117
118    @Override
119    public int[] getRequiredTokens() {
120        return new int[] {TokenTypes.PARAMETER_DEF};
121    }
122
123    @Override
124    protected boolean mustCheckName(DetailAST ast) {
125        boolean checkName = true;
126        if (ignoreOverridden && isOverriddenMethod(ast)
127                || ast.getParent().getType() == TokenTypes.LITERAL_CATCH
128                || CheckUtils.isReceiverParameter(ast)
129                || !matchAccessModifiers(getAccessModifier(ast))) {
130            checkName = false;
131        }
132        return checkName;
133    }
134
135    /**
136     * Returns the access modifier of the method/constructor at the specified AST. If
137     * the method is in an interface or annotation block, the access modifier is assumed
138     * to be public.
139     *
140     * @param ast the token of the method/constructor.
141     * @return the access modifier of the method/constructor.
142     */
143    private static AccessModifier getAccessModifier(final DetailAST ast) {
144        final DetailAST params = ast.getParent();
145        final DetailAST meth = params.getParent();
146        AccessModifier accessModifier = AccessModifier.PRIVATE;
147
148        if (meth.getType() == TokenTypes.METHOD_DEF
149                || meth.getType() == TokenTypes.CTOR_DEF) {
150            if (ScopeUtils.isInInterfaceOrAnnotationBlock(ast)) {
151                accessModifier = AccessModifier.PUBLIC;
152            }
153            else {
154                final DetailAST modsToken = meth.findFirstToken(TokenTypes.MODIFIERS);
155                accessModifier = CheckUtils.getAccessModifierFromModifiersToken(modsToken);
156            }
157        }
158
159        return accessModifier;
160    }
161
162    /**
163     * Checks whether a method has the correct access modifier to be checked.
164     * @param accessModifier the access modifier of the method.
165     * @return whether the method matches the expected access modifier.
166     */
167    private boolean matchAccessModifiers(final AccessModifier accessModifier) {
168        return Arrays.stream(accessModifiers).anyMatch(el -> el == accessModifier);
169    }
170
171    /**
172     * Checks whether a method is annotated with Override annotation.
173     * @param ast method parameter definition token.
174     * @return true if a method is annotated with Override annotation.
175     */
176    private static boolean isOverriddenMethod(DetailAST ast) {
177        boolean overridden = false;
178
179        final DetailAST parent = ast.getParent().getParent();
180        final Optional<DetailAST> annotation =
181            Optional.ofNullable(parent.getFirstChild().getFirstChild());
182
183        if (annotation.isPresent()
184                && annotation.get().getType() == TokenTypes.ANNOTATION) {
185            final Optional<DetailAST> overrideToken =
186                Optional.ofNullable(annotation.get().findFirstToken(TokenTypes.IDENT));
187            if (overrideToken.isPresent() && "Override".equals(overrideToken.get().getText())) {
188                overridden = true;
189            }
190        }
191        return overridden;
192    }
193
194}