View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 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   * <ul>
38   * <li>
39   * Property {@code allowOneCharVarInForLoop} - Allow one character variable name in
40   * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
41   * initialization expressions</a>
42   * in FOR loop if one char variable name is prohibited by {@code format} regexp.
43   * Type is {@code boolean}.
44   * Default value is {@code false}.
45   * </li>
46   * <li>
47   * Property {@code format} - Sets the pattern to match valid identifiers.
48   * Type is {@code java.util.regex.Pattern}.
49   * Default value is {@code "^([a-z][a-zA-Z0-9]*|_)$"}.
50   * </li>
51   * </ul>
52   *
53   * <p>
54   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
55   * </p>
56   *
57   * <p>
58   * Violation Message Keys:
59   * </p>
60   * <ul>
61   * <li>
62   * {@code name.invalidPattern}
63   * </li>
64   * </ul>
65   *
66   * @since 3.0
67   */
68  public class LocalVariableNameCheck
69      extends AbstractNameCheck {
70  
71      /**
72       * Allow one character variable name in
73       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
74       * initialization expressions</a>
75       * in FOR loop if one char variable name is prohibited by {@code format} regexp.
76       */
77      private boolean allowOneCharVarInForLoop;
78  
79      /** Creates a new {@code LocalVariableNameCheck} instance. */
80      public LocalVariableNameCheck() {
81          super("^([a-z][a-zA-Z0-9]*|_)$");
82      }
83  
84      /**
85       * Setter to allow one character variable name in
86       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
87       * initialization expressions</a>
88       * in FOR loop if one char variable name is prohibited by {@code format} regexp.
89       *
90       * @param allow Flag for allowing or not one character name in FOR loop.
91       * @since 5.8
92       */
93      public final void setAllowOneCharVarInForLoop(boolean allow) {
94          allowOneCharVarInForLoop = allow;
95      }
96  
97      @Override
98      public int[] getDefaultTokens() {
99          return getRequiredTokens();
100     }
101 
102     @Override
103     public int[] getAcceptableTokens() {
104         return getRequiredTokens();
105     }
106 
107     @Override
108     public int[] getRequiredTokens() {
109         return new int[] {
110             TokenTypes.VARIABLE_DEF,
111         };
112     }
113 
114     @Override
115     protected final boolean mustCheckName(DetailAST ast) {
116         final boolean result;
117         if (allowOneCharVarInForLoop && isForLoopVariable(ast)) {
118             final String variableName = ast.findFirstToken(TokenTypes.IDENT).getText();
119             result = variableName.length() != 1;
120         }
121         else {
122             final DetailAST modifiersAST = ast.findFirstToken(TokenTypes.MODIFIERS);
123             final boolean isFinal = modifiersAST.findFirstToken(TokenTypes.FINAL) != null;
124             result = !isFinal && ScopeUtil.isLocalVariableDef(ast);
125         }
126         return result;
127     }
128 
129     /**
130      * Checks if a variable is the loop's one.
131      *
132      * @param variableDef variable definition.
133      * @return true if a variable is the loop's one.
134      */
135     private static boolean isForLoopVariable(DetailAST variableDef) {
136         final int parentType = variableDef.getParent().getType();
137         return parentType == TokenTypes.FOR_INIT
138                 || parentType == TokenTypes.FOR_EACH_CLAUSE;
139     }
140 
141 }