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.naming;
021
022import com.puppycrawl.tools.checkstyle.api.DetailAST;
023import com.puppycrawl.tools.checkstyle.api.TokenTypes;
024import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
025
026/**
027 * <div>
028 * Checks that local, non-{@code final} variable names conform to a specified pattern.
029 * A catch parameter is considered to be a local variable.
030 * </div>
031 *
032 * <p>
033 * This check does not support pattern variables. Instead, use
034 * <a href="https://checkstyle.org/checks/naming/patternvariablename.html">
035 * PatternVariableName</a>.
036 * </p>
037 *
038 * @since 3.0
039 */
040public class LocalVariableNameCheck extends AbstractNameCheck {
041
042    /**
043     * A key is pointing to the warning message text in "messages.properties" file.
044     */
045    public static final String MSG_INVALID_PATTERN = "name.invalidPattern";
046
047    /**
048     * Allow one character variable name in
049     * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
050     * initialization expressions</a>
051     * in FOR loop if one char variable name is prohibited by {@code format} regexp.
052     */
053    private boolean allowOneCharVarInForLoop;
054
055    /** Creates a new {@code LocalVariableNameCheck} instance. */
056    public LocalVariableNameCheck() {
057        super("^([a-z][a-zA-Z0-9]*|_)$", MSG_INVALID_PATTERN);
058    }
059
060    /**
061     * Setter to allow one character variable name in
062     * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
063     * initialization expressions</a>
064     * in FOR loop if one char variable name is prohibited by {@code format} regexp.
065     *
066     * @param allow Flag for allowing or not one character name in FOR loop.
067     * @since 5.8
068     */
069    public final void setAllowOneCharVarInForLoop(boolean allow) {
070        allowOneCharVarInForLoop = allow;
071    }
072
073    @Override
074    public int[] getDefaultTokens() {
075        return getRequiredTokens();
076    }
077
078    @Override
079    public int[] getAcceptableTokens() {
080        return getRequiredTokens();
081    }
082
083    @Override
084    public int[] getRequiredTokens() {
085        return new int[] {
086            TokenTypes.VARIABLE_DEF,
087        };
088    }
089
090    @Override
091    protected final boolean mustCheckName(DetailAST ast) {
092        final boolean result;
093        if (allowOneCharVarInForLoop && isForLoopVariable(ast)) {
094            final String variableName = ast.findFirstToken(TokenTypes.IDENT).getText();
095            result = variableName.length() != 1;
096        }
097        else {
098            final DetailAST modifiersAST = ast.findFirstToken(TokenTypes.MODIFIERS);
099            final boolean isFinal = modifiersAST.findFirstToken(TokenTypes.FINAL) != null;
100            result = !isFinal && ScopeUtil.isLocalVariableDef(ast);
101        }
102        return result;
103    }
104
105    /**
106     * Checks if a variable is the loop's one.
107     *
108     * @param variableDef variable definition.
109     * @return true if a variable is the loop's one.
110     */
111    private static boolean isForLoopVariable(DetailAST variableDef) {
112        final int parentType = variableDef.getParent().getType();
113        return parentType == TokenTypes.FOR_INIT
114                || parentType == TokenTypes.FOR_EACH_CLAUSE;
115    }
116
117}