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