001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2018 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.CommonUtils;
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 * @author Rick Giles
063 * @author lkuehne
064 */
065@StatelessCheck
066public class NoWhitespaceBeforeCheck
067    extends AbstractCheck {
068
069    /**
070     * A key is pointing to the warning message text in "messages.properties"
071     * file.
072     */
073    public static final String MSG_KEY = "ws.preceded";
074
075    /** Whether whitespace is allowed if the AST is at a linebreak. */
076    private boolean allowLineBreaks;
077
078    @Override
079    public int[] getDefaultTokens() {
080        return new int[] {
081            TokenTypes.COMMA,
082            TokenTypes.SEMI,
083            TokenTypes.POST_INC,
084            TokenTypes.POST_DEC,
085            TokenTypes.ELLIPSIS,
086        };
087    }
088
089    @Override
090    public int[] getAcceptableTokens() {
091        return new int[] {
092            TokenTypes.COMMA,
093            TokenTypes.SEMI,
094            TokenTypes.POST_INC,
095            TokenTypes.POST_DEC,
096            TokenTypes.DOT,
097            TokenTypes.GENERIC_START,
098            TokenTypes.GENERIC_END,
099            TokenTypes.ELLIPSIS,
100            TokenTypes.METHOD_REF,
101        };
102    }
103
104    @Override
105    public int[] getRequiredTokens() {
106        return CommonUtils.EMPTY_INT_ARRAY;
107    }
108
109    @Override
110    public void visitToken(DetailAST ast) {
111        final String line = getLine(ast.getLineNo() - 1);
112        final int before = ast.getColumnNo() - 1;
113
114        if ((before == -1 || Character.isWhitespace(line.charAt(before)))
115                && !isInEmptyForInitializerOrCondition(ast)) {
116            boolean flag = !allowLineBreaks;
117            // verify all characters before '.' are whitespace
118            for (int i = 0; !flag && i <= before - 1; i++) {
119                if (!Character.isWhitespace(line.charAt(i))) {
120                    flag = true;
121                    break;
122                }
123            }
124            if (flag) {
125                log(ast.getLineNo(), before, MSG_KEY, ast.getText());
126            }
127        }
128    }
129
130    /**
131     * Checks that semicolon is in empty for initializer or condition.
132     * @param semicolonAst DetailAST of semicolon.
133     * @return true if semicolon is in empty for initializer or condition.
134     */
135    private static boolean isInEmptyForInitializerOrCondition(DetailAST semicolonAst) {
136        boolean result = false;
137        if (semicolonAst.getType() == TokenTypes.SEMI) {
138            final DetailAST sibling = semicolonAst.getPreviousSibling();
139            if (sibling != null
140                    && (sibling.getType() == TokenTypes.FOR_INIT
141                            || sibling.getType() == TokenTypes.FOR_CONDITION)
142                    && sibling.getChildCount() == 0) {
143                result = true;
144            }
145        }
146        return result;
147    }
148
149    /**
150     * Control whether whitespace is flagged at line breaks.
151     * @param allowLineBreaks whether whitespace should be
152     *     flagged at line breaks.
153     */
154    public void setAllowLineBreaks(boolean allowLineBreaks) {
155        this.allowLineBreaks = allowLineBreaks;
156    }
157
158}