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