View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.checkstyle;
6   
7   import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
8   import com.puppycrawl.tools.checkstyle.api.DetailAST;
9   import com.puppycrawl.tools.checkstyle.api.TokenTypes;
10  import java.util.regex.Pattern;
11  
12  /**
13   * Checks that enum constant names conform to the same naming convention
14   * as {@code static final} fields (i.e., the default Checkstyle
15   * {@code ConstantName} pattern {@code ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$}).
16   *
17   * <p>Since enum constants are effectively {@code public static final}
18   * references, they must follow the same upper-case, underscore-separated
19   * naming convention. Names like {@code anyName} or {@code MixedCase} are
20   * forbidden.</p>
21   *
22   * @since 0.24
23   */
24  public final class EnumValueNameCheck extends AbstractCheck {
25  
26      /**
27       * Required pattern for enum constant names.
28       */
29      private static final Pattern FORMAT = Pattern.compile(
30          "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"
31      );
32  
33      /**
34       * Default constructor.
35       */
36      public EnumValueNameCheck() {
37          // nothing to initialize
38      }
39  
40      @Override
41      public int[] getDefaultTokens() {
42          return new int[] {TokenTypes.ENUM_CONSTANT_DEF};
43      }
44  
45      @Override
46      public int[] getAcceptableTokens() {
47          return this.getDefaultTokens();
48      }
49  
50      @Override
51      public int[] getRequiredTokens() {
52          return this.getDefaultTokens();
53      }
54  
55      @Override
56      public void visitToken(final DetailAST ast) {
57          final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
58          final String name = ident.getText();
59          if (!EnumValueNameCheck.FORMAT.matcher(name).matches()) {
60              this.log(
61                  ident.getLineNo(),
62                  ident.getColumnNo(),
63                  String.format(
64                      "Enum value %s must match pattern %s",
65                      name,
66                      EnumValueNameCheck.FORMAT.pattern()
67                  )
68              );
69          }
70      }
71  }