001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2017 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.ScopeUtils; 025 026/** 027 * <p> 028 * Checks that instance variable names conform to a format specified 029 * by the format property. The format is a 030 * {@link java.util.regex.Pattern regular expression} 031 * and defaults to 032 * <strong>^[a-z][a-zA-Z0-9]*$</strong>. 033 * </p> 034 * <p> 035 * An example of how to configure the check is: 036 * </p> 037 * <pre> 038 * <module name="MemberName"/> 039 * </pre> 040 * <p> 041 * An example of how to configure the check for names that begin with 042 * "m", followed by an upper case letter, and then letters and 043 * digits is: 044 * </p> 045 * <pre> 046 * <module name="MemberName"> 047 * <property name="format" value="^m[A-Z][a-zA-Z0-9]*$"/> 048 * </module> 049 * </pre> 050 * @author Rick Giles 051 */ 052public class MemberNameCheck 053 extends AbstractAccessControlNameCheck { 054 /** Creates a new {@code MemberNameCheck} instance. */ 055 public MemberNameCheck() { 056 super("^[a-z][a-zA-Z0-9]*$"); 057 } 058 059 @Override 060 public int[] getDefaultTokens() { 061 return getAcceptableTokens(); 062 } 063 064 @Override 065 public int[] getAcceptableTokens() { 066 return new int[] {TokenTypes.VARIABLE_DEF}; 067 } 068 069 @Override 070 public int[] getRequiredTokens() { 071 return getAcceptableTokens(); 072 } 073 074 @Override 075 protected final boolean mustCheckName(DetailAST ast) { 076 final DetailAST modifiersAST = 077 ast.findFirstToken(TokenTypes.MODIFIERS); 078 final boolean isStatic = modifiersAST.branchContains(TokenTypes.LITERAL_STATIC); 079 080 return !isStatic && !ScopeUtils.isInInterfaceOrAnnotationBlock(ast) 081 && !ScopeUtils.isLocalVariableDef(ast) 082 && shouldCheckInScope(modifiersAST); 083 } 084}