001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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.ScopeUtil;
025
026/**
027 * <p>
028 * Checks that constant names conform to a specified pattern.
029 * A <em>constant</em> is a <strong>static</strong> and <strong>final</strong>
030 * field or an interface/annotation field, except
031 * <strong>serialVersionUID</strong> and <strong>serialPersistentFields
032 * </strong>.
033 * </p>
034 * <ul>
035 * <li>
036 * Property {@code format} - Specifies valid identifiers.
037 * Type is {@code java.util.regex.Pattern}.
038 * Default value is {@code "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"}.
039 * </li>
040 * <li>
041 * Property {@code applyToPublic} - Controls whether to apply the check to public member.
042 * Type is {@code boolean}.
043 * Default value is {@code true}.
044 * </li>
045 * <li>
046 * Property {@code applyToProtected} - Controls whether to apply the check to protected member.
047 * Type is {@code boolean}.
048 * Default value is {@code true}.
049 * </li>
050 * <li>
051 * Property {@code applyToPackage} - Controls whether to apply the check to package-private member.
052 * Type is {@code boolean}.
053 * Default value is {@code true}.
054 * </li>
055 * <li>
056 * Property {@code applyToPrivate} - Controls whether to apply the check to private member.
057 * Type is {@code boolean}.
058 * Default value is {@code true}.
059 * </li>
060 * </ul>
061 * <p>
062 * An example of how to configure the check is:
063 * </p>
064 * <pre>
065 * &lt;module name="ConstantName"/&gt;
066 * </pre>
067 *
068 * <p>
069 * The following configuration apart from names allowed by default allows {@code log}
070 * or {@code logger}:
071 * </p>
072 * <pre>
073 * &lt;module name=&quot;ConstantName&quot;&gt;
074 *   &lt;property name=&quot;format&quot;
075 *     value=&quot;^log(ger)?$|^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$&quot;/&gt;
076 * &lt;/module&gt;
077 * </pre>
078 * <p>Code Example:</p>
079 * <pre>
080 * class MyClass {
081 *   final static int log = 10; // OK
082 *   final static int logger = 50; // OK
083 *   final static int logMYSELF = 10; // violation, name 'logMYSELF' must match
084 *                                    // pattern '^log(ger)?$|^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'
085 *   final static int loggerMYSELF = 5; // violation, name 'loggerMYSELF' must match
086 *                                      // pattern '^log(ger)?$|^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'
087 *   final static int MYSELF = 100; // OK
088 *   final static int myselfConstant = 1; // violation, name 'myselfConstant' must match pattern
089 *                                        // '^log(ger)?$|^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'
090 * }
091 * </pre>
092 * <p>
093 * The following configuration skip validation on
094 * public constant field and protected constant field.
095 * </p>
096 * <pre>
097 * &lt;module name=&quot;ConstantName&quot;&gt;
098 *   &lt;property name="applyToPublic" value="false"/&gt;
099 *   &lt;property name="applyToProtected" value="false"/&gt;
100 * &lt;/module&gt;
101 * </pre>
102 * <p>Code Example:</p>
103 * <pre>
104 * class MyClass {
105 *   public final static int firstConstant = 10; // OK
106 *   protected final static int secondConstant = 100; // OK
107 *   final static int thirdConstant = 1000; // violation, name 'thirdConstant' must
108 *                                          // match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'
109 *   private final static int fourthConstant = 50; // violation, name 'fourthConstant' must match
110 *                                                 // pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'
111 * }
112 * </pre>
113 * <p>
114 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
115 * </p>
116 * <p>
117 * Violation Message Keys:
118 * </p>
119 * <ul>
120 * <li>
121 * {@code name.invalidPattern}
122 * </li>
123 * </ul>
124 *
125 * @since 3.0
126 */
127public class ConstantNameCheck
128    extends AbstractAccessControlNameCheck {
129
130    /** Creates a new {@code ConstantNameCheck} instance. */
131    public ConstantNameCheck() {
132        super("^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$");
133    }
134
135    @Override
136    public int[] getDefaultTokens() {
137        return getRequiredTokens();
138    }
139
140    @Override
141    public int[] getAcceptableTokens() {
142        return getRequiredTokens();
143    }
144
145    @Override
146    public int[] getRequiredTokens() {
147        return new int[] {TokenTypes.VARIABLE_DEF};
148    }
149
150    @Override
151    protected final boolean mustCheckName(DetailAST ast) {
152        boolean returnValue = false;
153
154        final DetailAST modifiersAST =
155            ast.findFirstToken(TokenTypes.MODIFIERS);
156        final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
157        final boolean isFinal = modifiersAST.findFirstToken(TokenTypes.FINAL) != null;
158
159        if (isStatic && isFinal && shouldCheckInScope(modifiersAST)
160                || ScopeUtil.isInAnnotationBlock(ast)
161                || ScopeUtil.isInInterfaceBlock(ast)
162                        && !ScopeUtil.isInCodeBlock(ast)) {
163            // Handle the serialVersionUID and serialPersistentFields constants
164            // which are used for Serialization. Cannot enforce rules on it. :-)
165            final DetailAST nameAST = ast.findFirstToken(TokenTypes.IDENT);
166            if (!"serialVersionUID".equals(nameAST.getText())
167                && !"serialPersistentFields".equals(nameAST.getText())) {
168                returnValue = true;
169            }
170        }
171
172        return returnValue;
173    }
174
175}