View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 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   * <p>
28   * Checks that local, non-{@code final} variable names conform to a specified pattern.
29   * A catch parameter is considered to be
30   * a local variable.
31   * </p>
32   * <p>
33   * This check does not support pattern variables. Instead, use
34   * <a href="https://checkstyle.org/checks/naming/patternvariablename.html#PatternVariableName">
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   * <p>
53   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
54   * </p>
55   * <p>
56   * Violation Message Keys:
57   * </p>
58   * <ul>
59   * <li>
60   * {@code name.invalidPattern}
61   * </li>
62   * </ul>
63   *
64   * @since 3.0
65   */
66  public class LocalVariableNameCheck
67      extends AbstractNameCheck {
68  
69      /**
70       * Allow one character variable name in
71       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
72       * initialization expressions</a>
73       * in FOR loop if one char variable name is prohibited by {@code format} regexp.
74       */
75      private boolean allowOneCharVarInForLoop;
76  
77      /** Creates a new {@code LocalVariableNameCheck} instance. */
78      public LocalVariableNameCheck() {
79          super("^([a-z][a-zA-Z0-9]*|_)$");
80      }
81  
82      /**
83       * Setter to allow one character variable name in
84       * <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html">
85       * initialization expressions</a>
86       * in FOR loop if one char variable name is prohibited by {@code format} regexp.
87       *
88       * @param allow Flag for allowing or not one character name in FOR loop.
89       * @since 5.8
90       */
91      public final void setAllowOneCharVarInForLoop(boolean allow) {
92          allowOneCharVarInForLoop = allow;
93      }
94  
95      @Override
96      public int[] getDefaultTokens() {
97          return getRequiredTokens();
98      }
99  
100     @Override
101     public int[] getAcceptableTokens() {
102         return getRequiredTokens();
103     }
104 
105     @Override
106     public int[] getRequiredTokens() {
107         return new int[] {
108             TokenTypes.VARIABLE_DEF,
109         };
110     }
111 
112     @Override
113     protected final boolean mustCheckName(DetailAST ast) {
114         final boolean result;
115         if (allowOneCharVarInForLoop && isForLoopVariable(ast)) {
116             final String variableName = ast.findFirstToken(TokenTypes.IDENT).getText();
117             result = variableName.length() != 1;
118         }
119         else {
120             final DetailAST modifiersAST = ast.findFirstToken(TokenTypes.MODIFIERS);
121             final boolean isFinal = modifiersAST.findFirstToken(TokenTypes.FINAL) != null;
122             result = !isFinal && ScopeUtil.isLocalVariableDef(ast);
123         }
124         return result;
125     }
126 
127     /**
128      * Checks if a variable is the loop's one.
129      *
130      * @param variableDef variable definition.
131      * @return true if a variable is the loop's one.
132      */
133     private static boolean isForLoopVariable(DetailAST variableDef) {
134         final int parentType = variableDef.getParent().getType();
135         return parentType == TokenTypes.FOR_INIT
136                 || parentType == TokenTypes.FOR_EACH_CLAUSE;
137     }
138 
139 }