View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.naming;
21  
22  import com.puppycrawl.tools.checkstyle.api.DetailAST;
23  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
24  import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
25  
26  /**
27   * <div>
28   * Checks that local, non-{@code final} variable names conform to a specified pattern.
29   * A catch parameter is considered to be a local variable.
30   * </div>
31   *
32   * <p>
33   * This check does not support pattern variables. Instead, use
34   * <a href="https://checkstyle.org/checks/naming/patternvariablename.html">
35   * PatternVariableName</a>.
36   * </p>
37   *
38   * @since 3.0
39   */
40  public class LocalVariableNameCheck
41      extends AbstractNameCheck {
42  
43      /**
44       * A key is pointing to the warning message text in "messages.properties"
45       * file.
46       */
47      public static final String MSG_INVALID_PATTERN = "name.invalidPattern";
48  
49      /**
50       * Allow one character variable name in
51       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
52       * initialization expressions</a>
53       * in FOR loop if one char variable name is prohibited by {@code format} regexp.
54       */
55      private boolean allowOneCharVarInForLoop;
56  
57      /** Creates a new {@code LocalVariableNameCheck} instance. */
58      public LocalVariableNameCheck() {
59          super("^([a-z][a-zA-Z0-9]*|_)$", MSG_INVALID_PATTERN);
60      }
61  
62      /**
63       * Setter to allow one character variable name in
64       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
65       * initialization expressions</a>
66       * in FOR loop if one char variable name is prohibited by {@code format} regexp.
67       *
68       * @param allow Flag for allowing or not one character name in FOR loop.
69       * @since 5.8
70       */
71      public final void setAllowOneCharVarInForLoop(boolean allow) {
72          allowOneCharVarInForLoop = allow;
73      }
74  
75      @Override
76      public int[] getDefaultTokens() {
77          return getRequiredTokens();
78      }
79  
80      @Override
81      public int[] getAcceptableTokens() {
82          return getRequiredTokens();
83      }
84  
85      @Override
86      public int[] getRequiredTokens() {
87          return new int[] {
88              TokenTypes.VARIABLE_DEF,
89          };
90      }
91  
92      @Override
93      protected final boolean mustCheckName(DetailAST ast) {
94          final boolean result;
95          if (allowOneCharVarInForLoop && isForLoopVariable(ast)) {
96              final String variableName = ast.findFirstToken(TokenTypes.IDENT).getText();
97              result = variableName.length() != 1;
98          }
99          else {
100             final DetailAST modifiersAST = ast.findFirstToken(TokenTypes.MODIFIERS);
101             final boolean isFinal = modifiersAST.findFirstToken(TokenTypes.FINAL) != null;
102             result = !isFinal && ScopeUtil.isLocalVariableDef(ast);
103         }
104         return result;
105     }
106 
107     /**
108      * Checks if a variable is the loop's one.
109      *
110      * @param variableDef variable definition.
111      * @return true if a variable is the loop's one.
112      */
113     private static boolean isForLoopVariable(DetailAST variableDef) {
114         final int parentType = variableDef.getParent().getType();
115         return parentType == TokenTypes.FOR_INIT
116                 || parentType == TokenTypes.FOR_EACH_CLAUSE;
117     }
118 
119 }