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;
021
022import java.util.HashSet;
023import java.util.List;
024import java.util.Map;
025import java.util.Set;
026import java.util.regex.Pattern;
027
028import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
029import com.puppycrawl.tools.checkstyle.api.DetailAST;
030import com.puppycrawl.tools.checkstyle.api.TextBlock;
031import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
032
033/**
034 * <p>
035 * The check to ensure that comments are the only thing on a line.
036 * For the case of // comments that means that the only thing that should
037 * precede it is whitespace.
038 * It doesn't check comments if they do not end line, i.e. it accept
039 * the following:
040 * {@code Thread.sleep( 10 &lt;some comment here&gt; );}
041 * Format property is intended to deal with the "} // while" example.
042 * </p>
043 *
044 * <p>Rationale: Steve McConnell in &quot;Code Complete&quot; suggests that endline
045 * comments are a bad practice. An end line comment would
046 * be one that is on the same line as actual code. For example:
047 * <pre>
048 *  a = b + c;      // Some insightful comment
049 *  d = e / f;        // Another comment for this line
050 * </pre>
051 * Quoting &quot;Code Complete&quot; for the justification:
052 * <ul>
053 * <li>
054 * &quot;The comments have to be aligned so that they do not
055 * interfere with the visual structure of the code. If you don't
056 * align them neatly, they'll make your listing look like it's been
057 * through a washing machine.&quot;
058 * </li>
059 * <li>
060 * &quot;Endline comments tend to be hard to format...It takes time
061 * to align them. Such time is not spent learning more about
062 * the code; it's dedicated solely to the tedious task of
063 * pressing the spacebar or tab key.&quot;
064 * </li>
065 * <li>
066 * &quot;Endline comments are also hard to maintain. If the code on
067 * any line containing an endline comment grows, it bumps the
068 * comment farther out, and all the other endline comments will
069 * have to bumped out to match. Styles that are hard to
070 * maintain aren't maintained....&quot;
071 * </li>
072 * <li>
073 * &quot;Endline comments also tend to be cryptic. The right side of
074 * the line doesn't offer much room and the desire to keep the
075 * comment on one line means the comment must be short.
076 * Work then goes into making the line as short as possible
077 * instead of as clear as possible. The comment usually ends
078 * up as cryptic as possible....&quot;
079 * </li>
080 * <li>
081 * &quot;A systemic problem with endline comments is that it's hard
082 * to write a meaningful comment for one line of code. Most
083 * endline comments just repeat the line of code, which hurts
084 * more than it helps.&quot;
085 * </li>
086 * </ul>
087 * His comments on being hard to maintain when the size of
088 * the line changes are even more important in the age of
089 * automated refactorings.
090 *
091 * <p>To configure the check so it enforces only comment on a line:
092 * <pre>
093 * &lt;module name=&quot;TrailingComment&quot;&gt;
094 *    &lt;property name=&quot;format&quot; value=&quot;^\\s*$&quot;/&gt;
095 * &lt;/module&gt;
096 * </pre>
097 *
098 * @author o_sukhodolsky
099 */
100public class TrailingCommentCheck extends AbstractCheck {
101
102    /**
103     * A key is pointing to the warning message text in "messages.properties"
104     * file.
105     */
106    public static final String MSG_KEY = "trailing.comments";
107
108    /** Pattern for legal trailing comment. */
109    private Pattern legalComment;
110
111    /** The regexp to match against. */
112    private Pattern format = Pattern.compile("^[\\s});]*$");
113
114    /**
115     * Sets patter for legal trailing comments.
116     * @param legalComment pattern to set.
117     */
118    public void setLegalComment(final Pattern legalComment) {
119        this.legalComment = legalComment;
120    }
121
122    /**
123     * Set the format for the specified regular expression.
124     * @param pattern a pattern
125     */
126    public final void setFormat(Pattern pattern) {
127        format = pattern;
128    }
129
130    @Override
131    public int[] getDefaultTokens() {
132        return CommonUtils.EMPTY_INT_ARRAY;
133    }
134
135    @Override
136    public int[] getAcceptableTokens() {
137        return CommonUtils.EMPTY_INT_ARRAY;
138    }
139
140    @Override
141    public int[] getRequiredTokens() {
142        return CommonUtils.EMPTY_INT_ARRAY;
143    }
144
145    @Override
146    public void visitToken(DetailAST ast) {
147        throw new IllegalStateException("visitToken() shouldn't be called.");
148    }
149
150    @Override
151    public void beginTree(DetailAST rootAST) {
152        final Map<Integer, TextBlock> cppComments = getFileContents()
153                .getSingleLineComments();
154        final Map<Integer, List<TextBlock>> cComments = getFileContents()
155                .getBlockComments();
156        final Set<Integer> lines = new HashSet<>();
157        lines.addAll(cppComments.keySet());
158        lines.addAll(cComments.keySet());
159
160        for (Integer lineNo : lines) {
161            final String line = getLines()[lineNo - 1];
162            final String lineBefore;
163            final TextBlock comment;
164            if (cppComments.containsKey(lineNo)) {
165                comment = cppComments.get(lineNo);
166                lineBefore = line.substring(0, comment.getStartColNo());
167            }
168            else {
169                final List<TextBlock> commentList = cComments.get(lineNo);
170                comment = commentList.get(commentList.size() - 1);
171                lineBefore = line.substring(0, comment.getStartColNo());
172
173                // do not check comment which doesn't end line
174                if (comment.getText().length == 1
175                        && !CommonUtils.isBlank(line
176                            .substring(comment.getEndColNo() + 1))) {
177                    continue;
178                }
179            }
180            if (!format.matcher(lineBefore).find()
181                && !isLegalComment(comment)) {
182                log(lineNo, MSG_KEY);
183            }
184        }
185    }
186
187    /**
188     * Checks if given comment is legal (single-line and matches to the
189     * pattern).
190     * @param comment comment to check.
191     * @return true if the comment if legal.
192     */
193    private boolean isLegalComment(final TextBlock comment) {
194        final boolean legal;
195
196        // multi-line comment can not be legal
197        if (legalComment == null || comment.getStartLineNo() != comment.getEndLineNo()) {
198            legal = false;
199        }
200        else {
201            String commentText = comment.getText()[0];
202            // remove chars which start comment
203            commentText = commentText.substring(2);
204            // if this is a C-style comment we need to remove its end
205            if (commentText.endsWith("*/")) {
206                commentText = commentText.substring(0, commentText.length() - 2);
207            }
208            commentText = commentText.trim();
209            legal = legalComment.matcher(commentText).find();
210        }
211        return legal;
212    }
213}