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.ArrayDeque;
023import java.util.Deque;
024import java.util.Optional;
025
026import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
027import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
028import com.puppycrawl.tools.checkstyle.api.DetailAST;
029import com.puppycrawl.tools.checkstyle.api.TokenTypes;
030import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
031
032/**
033 * <div>
034 * Ensures that catch parameters that are not used are declared as an unnamed variable.
035 * </div>
036 *
037 * <p>
038 * Rationale:
039 * </p>
040 * <ul>
041 *     <li>
042 *         Improves code readability by clearly indicating which parameters are unused.
043 *     </li>
044 *     <li>
045 *         Follows Java conventions for denoting unused parameters with an underscore ({@code _}).
046 *     </li>
047 * </ul>
048 *
049 * <p>
050 * See the <a href="https://docs.oracle.com/en/java/javase/21/docs/specs/unnamed-jls.html">
051 * Java Language Specification</a> for more information about unnamed variables.
052 * </p>
053 *
054 * <p>
055 * <b>Attention</b>: This check should be activated only on source code
056 * that is compiled by jdk21 or higher;
057 * unnamed catch parameters came out as the first preview in Java 21.
058 * </p>
059 *
060 * @since 10.18.0
061 */
062
063@FileStatefulCheck
064public class UnusedCatchParameterShouldBeUnnamedCheck extends AbstractCheck {
065
066    /**
067     * A key is pointing to the warning message text in "messages.properties" file.
068     */
069    public static final String MSG_UNUSED_CATCH_PARAMETER = "unused.catch.parameter";
070
071    /**
072     * Invalid parents of the catch parameter identifier.
073     */
074    private static final int[] INVALID_CATCH_PARAM_IDENT_PARENTS = {
075        TokenTypes.DOT,
076        TokenTypes.LITERAL_NEW,
077        TokenTypes.METHOD_CALL,
078        TokenTypes.TYPE,
079    };
080
081    /**
082     * Keeps track of the catch parameters in a block.
083     */
084    private final Deque<CatchParameterDetails> catchParameters = new ArrayDeque<>();
085
086    /**
087     * Creates a new {@code UnusedCatchParameterShouldBeUnnamedCheck} instance.
088     */
089    public UnusedCatchParameterShouldBeUnnamedCheck() {
090        // no code by default
091    }
092
093    @Override
094    public int[] getDefaultTokens() {
095        return getRequiredTokens();
096    }
097
098    @Override
099    public int[] getAcceptableTokens() {
100        return getRequiredTokens();
101    }
102
103    @Override
104    public int[] getRequiredTokens() {
105        return new int[] {
106            TokenTypes.LITERAL_CATCH,
107            TokenTypes.IDENT,
108        };
109    }
110
111    @Override
112    public void beginTree(DetailAST rootAST) {
113        catchParameters.clear();
114    }
115
116    @Override
117    public void visitToken(DetailAST ast) {
118        if (ast.getType() == TokenTypes.LITERAL_CATCH) {
119            final CatchParameterDetails catchParameter = new CatchParameterDetails(ast);
120            catchParameters.push(catchParameter);
121        }
122        else if (isCatchParameterIdentifierCandidate(ast) && !isLeftHandOfAssignment(ast)) {
123            // we do not count reassignment as usage
124            catchParameters.stream()
125                    .filter(parameter -> parameter.getName().equals(ast.getText()))
126                    .findFirst()
127                    .ifPresent(CatchParameterDetails::registerAsUsed);
128        }
129    }
130
131    @Override
132    public void leaveToken(DetailAST ast) {
133        if (ast.getType() == TokenTypes.LITERAL_CATCH) {
134            final Optional<CatchParameterDetails> unusedCatchParameter =
135                    Optional.ofNullable(catchParameters.peek())
136                            .filter(parameter -> !parameter.isUsed())
137                            .filter(parameter -> !"_".equals(parameter.getName()));
138
139            unusedCatchParameter.ifPresent(parameter -> {
140                log(parameter.getParameterDefinition(),
141                        MSG_UNUSED_CATCH_PARAMETER,
142                        parameter.getName());
143            });
144            catchParameters.pop();
145        }
146    }
147
148    /**
149     * Visit ast of type {@link TokenTypes#IDENT}
150     * and check if it is a candidate for a catch parameter identifier.
151     *
152     * @param identifierAst token representing {@code TokenTypes#IDENT}
153     * @return true if the given {@code TokenTypes#IDENT} could be a catch parameter identifier
154     */
155    private static boolean isCatchParameterIdentifierCandidate(DetailAST identifierAst) {
156        // we should ignore the ident if it is in the exception declaration
157        return identifierAst.getParent().getParent().getType() != TokenTypes.LITERAL_CATCH
158            && (!TokenUtil.isOfType(identifierAst.getParent(), INVALID_CATCH_PARAM_IDENT_PARENTS)
159                 || isMethodInvocation(identifierAst));
160    }
161
162    /**
163     * Check if the given {@link TokenTypes#IDENT} is a child of a dot operator
164     * and is a candidate for catch parameter.
165     *
166     * @param identAst token representing {@code TokenTypes#IDENT}
167     * @return true if the given {@code TokenTypes#IDENT} is a child of a dot operator
168     *     and a candidate for catch parameter.
169     */
170    private static boolean isMethodInvocation(DetailAST identAst) {
171        final DetailAST parent = identAst.getParent();
172        return parent.getType() == TokenTypes.DOT
173                && identAst.equals(parent.getFirstChild());
174    }
175
176    /**
177     * Check if the given {@link TokenTypes#IDENT} is a left hand side value.
178     *
179     * @param identAst token representing {@code TokenTypes#IDENT}
180     * @return true if the given {@code TokenTypes#IDENT} is a left hand side value.
181     */
182    private static boolean isLeftHandOfAssignment(DetailAST identAst) {
183        final DetailAST parent = identAst.getParent();
184        return parent.getType() == TokenTypes.ASSIGN
185                && !identAst.equals(parent.getLastChild());
186    }
187
188    /**
189     * Maintains information about the catch parameter.
190     */
191    private static final class CatchParameterDetails {
192
193        /**
194         * The name of the catch parameter.
195         */
196        private final String name;
197
198        /**
199         * Ast of type {@link TokenTypes#PARAMETER_DEF} to use it when logging.
200         */
201        private final DetailAST parameterDefinition;
202
203        /**
204         * Is the variable used.
205         */
206        private boolean used;
207
208        /**
209         * Create a new catch parameter instance.
210         *
211         * @param enclosingCatchClause ast of type {@link TokenTypes#LITERAL_CATCH}
212         */
213        private CatchParameterDetails(DetailAST enclosingCatchClause) {
214            parameterDefinition =
215                    enclosingCatchClause.findFirstToken(TokenTypes.PARAMETER_DEF);
216            name = parameterDefinition.findFirstToken(TokenTypes.IDENT).getText();
217        }
218
219        /**
220         * Register the catch parameter as used.
221         */
222        private void registerAsUsed() {
223            used = true;
224        }
225
226        /**
227         * Get the name of the catch parameter.
228         *
229         * @return the name of the catch parameter
230         */
231        private String getName() {
232            return name;
233        }
234
235        /**
236         * Check if the catch parameter is used.
237         *
238         * @return true if the catch parameter is used
239         */
240        private boolean isUsed() {
241            return used;
242        }
243
244        /**
245         * Get the parameter definition token of the catch parameter
246         * represented by ast of type {@link TokenTypes#PARAMETER_DEF}.
247         *
248         * @return the ast of type {@code TokenTypes#PARAMETER_DEF}
249         */
250        private DetailAST getParameterDefinition() {
251            return parameterDefinition;
252        }
253
254    }
255
256}