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.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.CommonUtil;
027
028/**
029 * <p>
030 * Checks that there is no whitespace before a token.
031 * More specifically, it checks that it is not preceded with whitespace,
032 * or (if line breaks are allowed) all characters on the line before are
033 * whitespace. To allow line breaks before a token, set property
034 * allowLineBreaks to true. No check occurs before semi-colons in empty
035 * for loop initializers or conditions.
036 * </p>
037 * <p> By default the check will check the following operators:
038 *  {@link TokenTypes#COMMA COMMA},
039 *  {@link TokenTypes#SEMI SEMI},
040 *  {@link TokenTypes#POST_DEC POST_DEC},
041 *  {@link TokenTypes#POST_INC POST_INC},
042 *  {@link TokenTypes#ELLIPSIS ELLIPSIS}.
043 * {@link TokenTypes#DOT DOT} is also an acceptable token in a configuration
044 * of this check.
045 * </p>
046 *
047 * <p>
048 * An example of how to configure the check is:
049 * </p>
050 * <pre>
051 * &lt;module name="NoWhitespaceBefore"/&gt;
052 * </pre>
053 * <p> An example of how to configure the check to allow line breaks before
054 * a {@link TokenTypes#DOT DOT} token is:
055 * </p>
056 * <pre>
057 * &lt;module name="NoWhitespaceBefore"&gt;
058 *     &lt;property name="tokens" value="DOT"/&gt;
059 *     &lt;property name="allowLineBreaks" value="true"/&gt;
060 * &lt;/module&gt;
061 * </pre>
062 */
063@StatelessCheck
064public class NoWhitespaceBeforeCheck
065    extends AbstractCheck {
066
067    /**
068     * A key is pointing to the warning message text in "messages.properties"
069     * file.
070     */
071    public static final String MSG_KEY = "ws.preceded";
072
073    /** Whether whitespace is allowed if the AST is at a linebreak. */
074    private boolean allowLineBreaks;
075
076    @Override
077    public int[] getDefaultTokens() {
078        return new int[] {
079            TokenTypes.COMMA,
080            TokenTypes.SEMI,
081            TokenTypes.POST_INC,
082            TokenTypes.POST_DEC,
083            TokenTypes.ELLIPSIS,
084        };
085    }
086
087    @Override
088    public int[] getAcceptableTokens() {
089        return new int[] {
090            TokenTypes.COMMA,
091            TokenTypes.SEMI,
092            TokenTypes.POST_INC,
093            TokenTypes.POST_DEC,
094            TokenTypes.DOT,
095            TokenTypes.GENERIC_START,
096            TokenTypes.GENERIC_END,
097            TokenTypes.ELLIPSIS,
098            TokenTypes.METHOD_REF,
099        };
100    }
101
102    @Override
103    public int[] getRequiredTokens() {
104        return CommonUtil.EMPTY_INT_ARRAY;
105    }
106
107    @Override
108    public void visitToken(DetailAST ast) {
109        final String line = getLine(ast.getLineNo() - 1);
110        final int before = ast.getColumnNo() - 1;
111
112        if ((before == -1 || Character.isWhitespace(line.charAt(before)))
113                && !isInEmptyForInitializerOrCondition(ast)) {
114            boolean flag = !allowLineBreaks;
115            // verify all characters before '.' are whitespace
116            for (int i = 0; i <= before - 1; i++) {
117                if (!Character.isWhitespace(line.charAt(i))) {
118                    flag = true;
119                    break;
120                }
121            }
122            if (flag) {
123                log(ast, MSG_KEY, ast.getText());
124            }
125        }
126    }
127
128    /**
129     * Checks that semicolon is in empty for initializer or condition.
130     * @param semicolonAst DetailAST of semicolon.
131     * @return true if semicolon is in empty for initializer or condition.
132     */
133    private static boolean isInEmptyForInitializerOrCondition(DetailAST semicolonAst) {
134        boolean result = false;
135        final DetailAST sibling = semicolonAst.getPreviousSibling();
136        if (sibling != null
137                && (sibling.getType() == TokenTypes.FOR_INIT
138                        || sibling.getType() == TokenTypes.FOR_CONDITION)
139                && sibling.getChildCount() == 0) {
140            result = true;
141        }
142        return result;
143    }
144
145    /**
146     * Control whether whitespace is flagged at line breaks.
147     * @param allowLineBreaks whether whitespace should be
148     *     flagged at line breaks.
149     */
150    public void setAllowLineBreaks(boolean allowLineBreaks) {
151        this.allowLineBreaks = allowLineBreaks;
152    }
153
154}