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