View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.whitespace;
21  
22  import com.puppycrawl.tools.checkstyle.StatelessCheck;
23  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
24  import com.puppycrawl.tools.checkstyle.api.DetailAST;
25  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
26  import com.puppycrawl.tools.checkstyle.utils.CodePointUtil;
27  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
28  
29  /**
30   * <div>
31   * Checks that there is no whitespace before a token.
32   * More specifically, it checks that it is not preceded with whitespace,
33   * or (if linebreaks are allowed) all characters on the line before are
34   * whitespace. To allow linebreaks before a token, set property
35   * {@code allowLineBreaks} to {@code true}. No check occurs before semicolons in empty
36   * for loop initializers or conditions.
37   * </div>
38   *
39   * @since 3.0
40   */
41  @StatelessCheck
42  public class NoWhitespaceBeforeCheck
43      extends AbstractCheck {
44  
45      /**
46       * A key is pointing to the warning message text in "messages.properties"
47       * file.
48       */
49      public static final String MSG_KEY = "ws.preceded";
50  
51      /** Control whether whitespace is allowed if the token is at a linebreak. */
52      private boolean allowLineBreaks;
53  
54      /**
55       * Creates a new {@code NoWhitespaceBeforeCheck} instance.
56       */
57      public NoWhitespaceBeforeCheck() {
58          // no code by default
59      }
60  
61      @Override
62      public int[] getDefaultTokens() {
63          return new int[] {
64              TokenTypes.COMMA,
65              TokenTypes.SEMI,
66              TokenTypes.POST_INC,
67              TokenTypes.POST_DEC,
68              TokenTypes.ELLIPSIS,
69              TokenTypes.LABELED_STAT,
70          };
71      }
72  
73      @Override
74      public int[] getAcceptableTokens() {
75          return new int[] {
76              TokenTypes.COMMA,
77              TokenTypes.SEMI,
78              TokenTypes.POST_INC,
79              TokenTypes.POST_DEC,
80              TokenTypes.DOT,
81              TokenTypes.GENERIC_START,
82              TokenTypes.GENERIC_END,
83              TokenTypes.ELLIPSIS,
84              TokenTypes.LABELED_STAT,
85              TokenTypes.METHOD_REF,
86          };
87      }
88  
89      @Override
90      public int[] getRequiredTokens() {
91          return CommonUtil.EMPTY_INT_ARRAY;
92      }
93  
94      @Override
95      public void visitToken(DetailAST ast) {
96          final int[] line = getLineCodePoints(ast.getLineNo() - 1);
97          final int columnNoBeforeToken = ast.getColumnNo() - 1;
98          final boolean isFirstToken = columnNoBeforeToken == -1;
99  
100         if ((isFirstToken || CommonUtil.isCodePointWhitespace(line, columnNoBeforeToken))
101                 && !isInEmptyForInitializerOrCondition(ast)) {
102             final boolean isViolation = !allowLineBreaks
103                     || !isFirstToken
104                     && !CodePointUtil.hasWhitespaceBefore(columnNoBeforeToken, line);
105 
106             if (isViolation) {
107                 log(ast, MSG_KEY, ast.getText());
108             }
109         }
110     }
111 
112     /**
113      * Checks that semicolon is in empty for initializer or condition.
114      *
115      * @param semicolonAst DetailAST of semicolon.
116      * @return true if semicolon is in empty for initializer or condition.
117      */
118     private static boolean isInEmptyForInitializerOrCondition(DetailAST semicolonAst) {
119         boolean result = false;
120         final DetailAST sibling = semicolonAst.getPreviousSibling();
121         if (sibling != null
122                 && (sibling.getType() == TokenTypes.FOR_INIT
123                         || sibling.getType() == TokenTypes.FOR_CONDITION)
124                 && !sibling.hasChildren()) {
125             result = true;
126         }
127         return result;
128     }
129 
130     /**
131      * Setter to control whether whitespace is allowed if the token is at a linebreak.
132      *
133      * @param allowLineBreaks whether whitespace should be
134      *     flagged at line breaks.
135      * @since 3.0
136      */
137     public void setAllowLineBreaks(boolean allowLineBreaks) {
138         this.allowLineBreaks = allowLineBreaks;
139     }
140 
141 }