001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.whitespace;
021
022import com.puppycrawl.tools.checkstyle.StatelessCheck;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.TokenTypes;
026import com.puppycrawl.tools.checkstyle.utils.CodePointUtil;
027import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
028
029/**
030 * <div>
031 * Checks that there is no whitespace before a token.
032 * More specifically, it checks that it is not preceded with whitespace,
033 * or (if linebreaks are allowed) all characters on the line before are
034 * whitespace. To allow linebreaks before a token, set property
035 * {@code allowLineBreaks} to {@code true}. No check occurs before semicolons in empty
036 * for loop initializers or conditions.
037 * </div>
038 *
039 * @since 3.0
040 */
041@StatelessCheck
042public class NoWhitespaceBeforeCheck extends AbstractCheck {
043
044    /**
045     * A key is pointing to the warning message text in "messages.properties" file.
046     */
047    public static final String MSG_KEY = "ws.preceded";
048
049    /** Control whether whitespace is allowed if the token is at a linebreak. */
050    private boolean allowLineBreaks;
051
052    /**
053     * Creates a new {@code NoWhitespaceBeforeCheck} instance.
054     */
055    public NoWhitespaceBeforeCheck() {
056        // no code by default
057    }
058
059    @Override
060    public int[] getDefaultTokens() {
061        return new int[] {
062            TokenTypes.COMMA,
063            TokenTypes.SEMI,
064            TokenTypes.POST_INC,
065            TokenTypes.POST_DEC,
066            TokenTypes.ELLIPSIS,
067            TokenTypes.LABELED_STAT,
068        };
069    }
070
071    @Override
072    public int[] getAcceptableTokens() {
073        return new int[] {
074            TokenTypes.COMMA,
075            TokenTypes.SEMI,
076            TokenTypes.POST_INC,
077            TokenTypes.POST_DEC,
078            TokenTypes.DOT,
079            TokenTypes.GENERIC_START,
080            TokenTypes.GENERIC_END,
081            TokenTypes.ELLIPSIS,
082            TokenTypes.LABELED_STAT,
083            TokenTypes.METHOD_REF,
084        };
085    }
086
087    @Override
088    public int[] getRequiredTokens() {
089        return CommonUtil.EMPTY_INT_ARRAY;
090    }
091
092    @Override
093    public void visitToken(DetailAST ast) {
094        final int[] line = getLineCodePoints(ast.getLineNo() - 1);
095        final int columnNoBeforeToken = ast.getColumnNo() - 1;
096        final boolean isFirstToken = columnNoBeforeToken == -1;
097
098        if ((isFirstToken || CommonUtil.isCodePointWhitespace(line, columnNoBeforeToken))
099                && !isInEmptyForInitializerOrCondition(ast)) {
100            final boolean isViolation = !allowLineBreaks
101                    || !isFirstToken
102                    && !CodePointUtil.hasWhitespaceBefore(columnNoBeforeToken, line);
103
104            if (isViolation) {
105                log(ast, MSG_KEY, ast.getText());
106            }
107        }
108    }
109
110    /**
111     * Checks that semicolon is in empty for initializer or condition.
112     *
113     * @param semicolonAst DetailAST of semicolon.
114     * @return true if semicolon is in empty for initializer or condition.
115     */
116    private static boolean isInEmptyForInitializerOrCondition(DetailAST semicolonAst) {
117        boolean result = false;
118        final DetailAST sibling = semicolonAst.getPreviousSibling();
119        if (sibling != null
120                && (sibling.getType() == TokenTypes.FOR_INIT
121                        || sibling.getType() == TokenTypes.FOR_CONDITION)
122                && !sibling.hasChildren()) {
123            result = true;
124        }
125        return result;
126    }
127
128    /**
129     * Setter to control whether whitespace is allowed if the token is at a linebreak.
130     *
131     * @param allowLineBreaks whether whitespace should be flagged at line breaks.
132     * @since 3.0
133     */
134    public void setAllowLineBreaks(boolean allowLineBreaks) {
135        this.allowLineBreaks = allowLineBreaks;
136    }
137
138}