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.
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      @Override
34      public int[] getDefaultTokens() {
35          return new int[] {TokenTypes.ENUM_CONSTANT_DEF};
36      }
37  
38      @Override
39      public int[] getAcceptableTokens() {
40          return this.getDefaultTokens();
41      }
42  
43      @Override
44      public int[] getRequiredTokens() {
45          return this.getDefaultTokens();
46      }
47  
48      @Override
49      public void visitToken(final DetailAST ast) {
50          final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
51          final String name = ident.getText();
52          if (!EnumValueNameCheck.FORMAT.matcher(name).matches()) {
53              this.log(
54                  ident.getLineNo(),
55                  ident.getColumnNo(),
56                  String.format(
57                      "Enum value %s must match pattern %s",
58                      name,
59                      EnumValueNameCheck.FORMAT.pattern()
60                  )
61              );
62          }
63      }
64  }