001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 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.api.AbstractCheck;
023import com.puppycrawl.tools.checkstyle.api.DetailAST;
024import com.puppycrawl.tools.checkstyle.api.TokenTypes;
025import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
026
027/**
028 * <p>
029 * Checks that there is no whitespace before a token.
030 * More specifically, it checks that it is not preceded with whitespace,
031 * or (if line breaks are allowed) all characters on the line before are
032 * whitespace. To allow line breaks before a token, set property
033 * allowLineBreaks to true. No check occurs before semi-colons in empty
034 * for loop initializers or conditions.
035 * </p>
036 * <p> By default the check will check the following operators:
037 *  {@link TokenTypes#COMMA COMMA},
038 *  {@link TokenTypes#SEMI SEMI},
039 *  {@link TokenTypes#POST_DEC POST_DEC},
040 *  {@link TokenTypes#POST_INC POST_INC},
041 *  {@link TokenTypes#ELLIPSIS ELLIPSIS}.
042 * {@link TokenTypes#DOT DOT} is also an acceptable token in a configuration
043 * of this check.
044 * </p>
045 *
046 * <p>
047 * An example of how to configure the check is:
048 * </p>
049 * <pre>
050 * &lt;module name="NoWhitespaceBefore"/&gt;
051 * </pre>
052 * <p> An example of how to configure the check to allow line breaks before
053 * a {@link TokenTypes#DOT DOT} token is:
054 * </p>
055 * <pre>
056 * &lt;module name="NoWhitespaceBefore"&gt;
057 *     &lt;property name="tokens" value="DOT"/&gt;
058 *     &lt;property name="allowLineBreaks" value="true"/&gt;
059 * &lt;/module&gt;
060 * </pre>
061 * @author Rick Giles
062 * @author lkuehne
063 */
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 CommonUtils.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
115            boolean flag = !allowLineBreaks;
116            // verify all characters before '.' are whitespace
117            for (int i = 0; !flag && i <= before - 1; i++) {
118                if (!Character.isWhitespace(line.charAt(i))) {
119                    flag = true;
120                    break;
121                }
122            }
123            if (flag) {
124                log(ast.getLineNo(), before, MSG_KEY, ast.getText());
125            }
126        }
127    }
128
129    /**
130     * Checks that semicolon is in empty for initializer or condition.
131     * @param semicolonAst DetailAST of semicolon.
132     * @return true if semicolon is in empty for initializer or condition.
133     */
134    private static boolean isInEmptyForInitializerOrCondition(DetailAST semicolonAst) {
135        boolean result = false;
136        if (semicolonAst.getType() == TokenTypes.SEMI) {
137            final DetailAST sibling = semicolonAst.getPreviousSibling();
138            if (sibling != null
139                    && (sibling.getType() == TokenTypes.FOR_INIT
140                            || sibling.getType() == TokenTypes.FOR_CONDITION)
141                    && sibling.getChildCount() == 0) {
142                result = true;
143            }
144        }
145        return result;
146    }
147
148    /**
149     * Control whether whitespace is flagged at line breaks.
150     * @param allowLineBreaks whether whitespace should be
151     *     flagged at line breaks.
152     */
153    public void setAllowLineBreaks(boolean allowLineBreaks) {
154        this.allowLineBreaks = allowLineBreaks;
155    }
156}