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