001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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 * <div>
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 * </div>
037 *
038 * @since 5.8
039 */
040@StatelessCheck
041public class OverloadMethodsDeclarationOrderCheck extends AbstractCheck {
042
043    /**
044     * A key is pointing to the warning message text in "messages.properties" file.
045     */
046    public static final String MSG_KEY = "overload.methods.declaration";
047
048    /**
049     * A key is pointing to the warning message text in "messages.properties" file.
050     */
051    public static final String MSG_ORDER = "overload.methods.declaration.order";
052
053    /**
054     * Control whether to order overloaded methods by increasing parameter count.
055     */
056    private boolean orderByIncreasingParameterCount;
057
058    /**
059     * Creates a new {@code OverloadMethodsDeclarationOrderCheck} instance.
060     */
061    public OverloadMethodsDeclarationOrderCheck() {
062        // no code by default
063    }
064
065    /**
066     * Setter to control whether to enforce order by increasing parameter count (arity) or not.
067     *
068     * @param orderByIncreasingParameterCount true if order by increasing parameter
069     *               count is required.
070     * @since 13.7.0
071     */
072    public void setOrderByIncreasingParameterCount(boolean orderByIncreasingParameterCount) {
073        this.orderByIncreasingParameterCount = orderByIncreasingParameterCount;
074    }
075
076    @Override
077    public int[] getDefaultTokens() {
078        return getRequiredTokens();
079    }
080
081    @Override
082    public int[] getAcceptableTokens() {
083        return getRequiredTokens();
084    }
085
086    @Override
087    public int[] getRequiredTokens() {
088        return new int[] {
089            TokenTypes.OBJBLOCK,
090            TokenTypes.COMPACT_COMPILATION_UNIT,
091        };
092    }
093
094    @Override
095    public void visitToken(DetailAST ast) {
096        final int[] objectBlockParentTypes = {
097            TokenTypes.CLASS_DEF,
098            TokenTypes.ENUM_DEF,
099            TokenTypes.INTERFACE_DEF,
100            TokenTypes.LITERAL_NEW,
101            TokenTypes.RECORD_DEF,
102        };
103
104        if (ast.getType() == TokenTypes.COMPACT_COMPILATION_UNIT
105            || TokenUtil.isOfType(ast.getParent().getType(), objectBlockParentTypes)) {
106            checkOverloadMethodsGrouping(ast);
107        }
108    }
109
110    /**
111     * Checks that if overload methods are grouped together they should not be
112     * separated from each other.
113     *
114     * @param objectBlock
115     *        is a class, interface, enum object block, or a compact
116     *        compilation unit for a JEP 512 compact source file.
117     */
118    private void checkOverloadMethodsGrouping(DetailAST objectBlock) {
119        final int allowedDistance = 1;
120        DetailAST currentToken = objectBlock.getFirstChild();
121        final Map<String, Integer> methodIndexMap = new HashMap<>();
122        final Map<String, Integer> methodLineNumberMap = new HashMap<>();
123
124        final Map<String, Integer> methodParameterCountMap = new HashMap<>();
125        final Map<String, Boolean> methodIsOrderedMap = new HashMap<>();
126
127        int currentIndex = 0;
128        while (currentToken != null) {
129            if (currentToken.getType() == TokenTypes.METHOD_DEF) {
130                currentIndex++;
131                final String methodName =
132                        currentToken.findFirstToken(TokenTypes.IDENT).getText();
133                final Integer previousIndex = methodIndexMap.get(methodName);
134
135                if (previousIndex != null) {
136                    final DetailAST previousSibling = currentToken.getPreviousSibling();
137                    final boolean isMethod = previousSibling.getType() == TokenTypes.METHOD_DEF;
138
139                    if (!isMethod || currentIndex - previousIndex > allowedDistance) {
140                        final int previousLineWithOverloadMethod =
141                                methodLineNumberMap.get(methodName);
142                        log(currentToken, MSG_KEY,
143                                previousLineWithOverloadMethod);
144                    }
145
146                    if (orderByIncreasingParameterCount) {
147                        checkMethodOrdering(currentToken, methodName,
148                                methodIsOrderedMap, methodParameterCountMap);
149                    }
150                }
151                methodIsOrderedMap.putIfAbsent(methodName, Boolean.TRUE);
152                methodIndexMap.put(methodName, currentIndex);
153                methodLineNumberMap.put(methodName, currentToken.getLineNo());
154                methodParameterCountMap.put(methodName, getParameterCount(currentToken));
155            }
156            currentToken = currentToken.getNextSibling();
157        }
158    }
159
160    /**
161     * Checks that overloaded methods are ordered with increasing parameter count or not.
162     *
163     * @param currentMethod ast of the method.
164     * @param methodName method name.
165     * @param methodIsOrderedMap
166     *        is a map of method names to booleans indicating whether the method is ordered.
167     * @param methodParameterCountMap
168     *        is a map of method names to integers indicating the parameter count of the previous
169     *        similar method.
170     */
171    private void checkMethodOrdering(DetailAST currentMethod, String methodName,
172        Map<String, Boolean> methodIsOrderedMap, Map<String, Integer> methodParameterCountMap) {
173
174        final int currentParamCount = getParameterCount(currentMethod);
175        final boolean isOrdered = methodIsOrderedMap.get(methodName)
176                            && currentParamCount >= methodParameterCountMap.get(methodName);
177        if (!isOrdered) {
178            methodIsOrderedMap.put(methodName, Boolean.FALSE);
179            log(currentMethod, MSG_ORDER);
180        }
181    }
182
183    /**
184     * Get the parameter count of a method.
185     *
186     * @param method the method AST
187     * @return the parameter count of the method
188     */
189    private static int getParameterCount(DetailAST method) {
190        final DetailAST params = method.findFirstToken(TokenTypes.PARAMETERS);
191        return params.getChildCount(TokenTypes.PARAMETER_DEF);
192    }
193
194}