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