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 * @author Oliver Burn
068 * @author Travis Schneeberger
069 * @author Utkarsh Srivastava
070 */
071public class MethodNameCheck
072    extends AbstractAccessControlNameCheck {
073
074    /**
075     * A key is pointing to the warning message text in "messages.properties"
076     * file.
077     */
078    public static final String MSG_KEY = "method.name.equals.class.name";
079
080    /**
081     * {@link Override Override} annotation name.
082     */
083    private static final String OVERRIDE = "Override";
084
085    /**
086     * Canonical {@link Override Override} annotation name.
087     */
088    private static final String CANONICAL_OVERRIDE = "java.lang." + OVERRIDE;
089
090    /**
091     * For allowing method name to be the same as the class name.
092     */
093    private boolean allowClassName;
094
095    /** Creates a new {@code MethodNameCheck} instance. */
096    public MethodNameCheck() {
097        super("^[a-z][a-zA-Z0-9]*$");
098    }
099
100    @Override
101    public int[] getDefaultTokens() {
102        return getRequiredTokens();
103    }
104
105    @Override
106    public int[] getAcceptableTokens() {
107        return getRequiredTokens();
108    }
109
110    @Override
111    public int[] getRequiredTokens() {
112        return new int[] {TokenTypes.METHOD_DEF, };
113    }
114
115    @Override
116    public void visitToken(DetailAST ast) {
117        if (!AnnotationUtility.containsAnnotation(ast, OVERRIDE)
118            && !AnnotationUtility.containsAnnotation(ast, CANONICAL_OVERRIDE)) {
119            // Will check the name against the format.
120            super.visitToken(ast);
121        }
122
123        if (!allowClassName) {
124            final DetailAST method =
125                ast.findFirstToken(TokenTypes.IDENT);
126            //in all cases this will be the classDef type except anon inner
127            //with anon inner classes this will be the Literal_New keyword
128            final DetailAST classDefOrNew = ast.getParent().getParent();
129            final DetailAST classIdent =
130                classDefOrNew.findFirstToken(TokenTypes.IDENT);
131            // Following logic is to handle when a classIdent can not be
132            // found. This is when you have a Literal_New keyword followed
133            // a DOT, which is when you have:
134            // new Outclass.InnerInterface(x) { ... }
135            // Such a rare case, will not have the logic to handle parsing
136            // down the tree looking for the first ident.
137            if (classIdent != null
138                && method.getText().equals(classIdent.getText())) {
139                log(method.getLineNo(), method.getColumnNo(),
140                    MSG_KEY, method.getText());
141            }
142        }
143    }
144
145    /**
146     * Sets the property for allowing a method to be the same name as a class.
147     * @param allowClassName true to allow false to disallow
148     */
149    public void setAllowClassName(boolean allowClassName) {
150        this.allowClassName = allowClassName;
151    }
152
153}