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 com.puppycrawl.tools.checkstyle.api.DetailAST;
023import com.puppycrawl.tools.checkstyle.api.TokenTypes;
024import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility;
025
026/**
027 * <p>
028 * Checks that method names conform to a format specified
029 * by the format property. The format is a
030 * {@link java.util.regex.Pattern regular expression}
031 * and defaults to
032 * <strong>^[a-z][a-zA-Z0-9]*$</strong>.
033 * </p>
034 *
035 * <p>Also, checks if a method name has the same name as the residing class.
036 * The default is false (it is not allowed).  It is legal in Java to have
037 * method with the same name as a class.  As long as a return type is specified
038 * it is a method and not a constructor which it could be easily confused as.
039 * <h3>Does not check-style the name of an overridden methods</h3> because the developer does not
040 * have a choice in renaming such methods.
041 *
042 * <p>
043 * An example of how to configure the check is:
044 * </p>
045 * <pre>
046 * &lt;module name="MethodName"/&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 is:
051 * </p>
052 * <pre>
053 * &lt;module name="MethodName"&gt;
054 *    &lt;property name="format" value="^[a-z](_?[a-zA-Z0-9]+)*$"/&gt;
055 * &lt;/module&gt;
056 * </pre>
057 *
058 * <p>
059 * An example of how to configure the check to allow method names
060 * to be equal to the residing class name is:
061 * </p>
062 * <pre>
063 * &lt;module name="MethodName"&gt;
064 *    &lt;property name="allowClassName" value="true"/&gt;
065 * &lt;/module&gt;
066 * </pre>
067 */
068public class MethodNameCheck
069    extends AbstractAccessControlNameCheck {
070
071    /**
072     * A key is pointing to the warning message text in "messages.properties"
073     * file.
074     */
075    public static final String MSG_KEY = "method.name.equals.class.name";
076
077    /**
078     * {@link Override Override} annotation name.
079     */
080    private static final String OVERRIDE = "Override";
081
082    /**
083     * Canonical {@link Override Override} annotation name.
084     */
085    private static final String CANONICAL_OVERRIDE = "java.lang." + OVERRIDE;
086
087    /**
088     * For allowing method name to be the same as the class name.
089     */
090    private boolean allowClassName;
091
092    /** Creates a new {@code MethodNameCheck} instance. */
093    public MethodNameCheck() {
094        super("^[a-z][a-zA-Z0-9]*$");
095    }
096
097    @Override
098    public int[] getDefaultTokens() {
099        return getRequiredTokens();
100    }
101
102    @Override
103    public int[] getAcceptableTokens() {
104        return getRequiredTokens();
105    }
106
107    @Override
108    public int[] getRequiredTokens() {
109        return new int[] {TokenTypes.METHOD_DEF, };
110    }
111
112    @Override
113    public void visitToken(DetailAST ast) {
114        if (!AnnotationUtility.containsAnnotation(ast, OVERRIDE)
115            && !AnnotationUtility.containsAnnotation(ast, CANONICAL_OVERRIDE)) {
116            // Will check the name against the format.
117            super.visitToken(ast);
118        }
119
120        if (!allowClassName) {
121            final DetailAST method =
122                ast.findFirstToken(TokenTypes.IDENT);
123            //in all cases this will be the classDef type except anon inner
124            //with anon inner classes this will be the Literal_New keyword
125            final DetailAST classDefOrNew = ast.getParent().getParent();
126            final DetailAST classIdent =
127                classDefOrNew.findFirstToken(TokenTypes.IDENT);
128            // Following logic is to handle when a classIdent can not be
129            // found. This is when you have a Literal_New keyword followed
130            // a DOT, which is when you have:
131            // new Outclass.InnerInterface(x) { ... }
132            // Such a rare case, will not have the logic to handle parsing
133            // down the tree looking for the first ident.
134            if (classIdent != null
135                && method.getText().equals(classIdent.getText())) {
136                log(method.getLineNo(), method.getColumnNo(),
137                    MSG_KEY, method.getText());
138            }
139        }
140    }
141
142    /**
143     * Sets the property for allowing a method to be the same name as a class.
144     * @param allowClassName true to allow false to disallow
145     */
146    public void setAllowClassName(boolean allowClassName) {
147        this.allowClassName = allowClassName;
148    }
149
150}