001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2022 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.coding;
021
022import java.util.HashMap;
023import java.util.Map;
024
025import com.puppycrawl.tools.checkstyle.StatelessCheck;
026import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
030
031/**
032 * <p>
033 * Checks that overloaded methods are grouped together. Overloaded methods have the same
034 * name but different signatures where the signature can differ by the number of
035 * input parameters or type of input parameters or both.
036 * </p>
037 * <p>
038 * To configure the check:
039 * </p>
040 * <pre>
041 * &lt;module name=&quot;OverloadMethodsDeclarationOrder&quot;/&gt;
042 * </pre>
043 * <p>
044 * Example of correct grouping of overloaded methods:
045 * </p>
046 * <pre>
047 * public void foo(int i) {}
048 * public void foo(String s) {}
049 * public void foo(String s, int i) {}
050 * public void foo(int i, String s) {}
051 * public void notFoo() {}
052 * </pre>
053 * <p>
054 * Example of incorrect grouping of overloaded methods:
055 * </p>
056 * <pre>
057 * public void foo(int i) {} // OK
058 * public void foo(String s) {} // OK
059 * public void notFoo() {} // violation. Have to be after foo(String s, int i)
060 * public void foo(int i, String s) {}
061 * public void foo(String s, int i) {}
062 * </pre>
063 * <p>
064 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
065 * </p>
066 * <p>
067 * Violation Message Keys:
068 * </p>
069 * <ul>
070 * <li>
071 * {@code overload.methods.declaration}
072 * </li>
073 * </ul>
074 *
075 * @since 5.8
076 */
077@StatelessCheck
078public class OverloadMethodsDeclarationOrderCheck extends AbstractCheck {
079
080    /**
081     * A key is pointing to the warning message text in "messages.properties"
082     * file.
083     */
084    public static final String MSG_KEY = "overload.methods.declaration";
085
086    @Override
087    public int[] getDefaultTokens() {
088        return getRequiredTokens();
089    }
090
091    @Override
092    public int[] getAcceptableTokens() {
093        return getRequiredTokens();
094    }
095
096    @Override
097    public int[] getRequiredTokens() {
098        return new int[] {
099            TokenTypes.OBJBLOCK,
100        };
101    }
102
103    @Override
104    public void visitToken(DetailAST ast) {
105        final int parentType = ast.getParent().getType();
106
107        final int[] tokenTypes = {
108            TokenTypes.CLASS_DEF,
109            TokenTypes.ENUM_DEF,
110            TokenTypes.INTERFACE_DEF,
111            TokenTypes.LITERAL_NEW,
112            TokenTypes.RECORD_DEF,
113        };
114
115        if (TokenUtil.isOfType(parentType, tokenTypes)) {
116            checkOverloadMethodsGrouping(ast);
117        }
118    }
119
120    /**
121     * Checks that if overload methods are grouped together they should not be
122     * separated from each other.
123     *
124     * @param objectBlock
125     *        is a class, interface or enum object block.
126     */
127    private void checkOverloadMethodsGrouping(DetailAST objectBlock) {
128        final int allowedDistance = 1;
129        DetailAST currentToken = objectBlock.getFirstChild();
130        final Map<String, Integer> methodIndexMap = new HashMap<>();
131        final Map<String, Integer> methodLineNumberMap = new HashMap<>();
132        int currentIndex = 0;
133        while (currentToken != null) {
134            if (currentToken.getType() == TokenTypes.METHOD_DEF) {
135                currentIndex++;
136                final String methodName =
137                        currentToken.findFirstToken(TokenTypes.IDENT).getText();
138                final Integer previousIndex = methodIndexMap.get(methodName);
139                if (previousIndex != null && currentIndex - previousIndex > allowedDistance) {
140                    final int previousLineWithOverloadMethod =
141                            methodLineNumberMap.get(methodName);
142                    log(currentToken, MSG_KEY,
143                            previousLineWithOverloadMethod);
144                }
145                methodIndexMap.put(methodName, currentIndex);
146                methodLineNumberMap.put(methodName, currentToken.getLineNo());
147            }
148            currentToken = currentToken.getNextSibling();
149        }
150    }
151
152}