001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2016 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.List; 023import java.util.Map; 024import java.util.Set; 025import java.util.regex.Pattern; 026 027import com.google.common.collect.Sets; 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 requires that comments be 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 <some comment here> );} 041 * Format property is intended to deal with the "} // while" example. 042 * </p> 043 * 044 * <p>Rationale: Steve McConnel in "Code Complete" 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 "Code Complete" for the justification: 052 * <ul> 053 * <li> 054 * "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." 058 * </li> 059 * <li> 060 * "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." 064 * </li> 065 * <li> 066 * "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...." 071 * </li> 072 * <li> 073 * "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...." 079 * </li> 080 * <li> 081 * "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." 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 * <module name="TrailingComment"> 094 * <property name="format" value="^\\s*$"/> 095 * </module> 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 format string of the regexp. */ 112 private String format = "^[\\s\\});]*$"; 113 114 /** The regexp to match against. */ 115 private Pattern regexp = Pattern.compile(format); 116 117 /** 118 * Sets patter for legal trailing comments. 119 * @param legalComment format to set. 120 */ 121 public void setLegalComment(final String legalComment) { 122 this.legalComment = CommonUtils.createPattern(legalComment); 123 } 124 125 /** 126 * Set the format to the specified regular expression. 127 * @param format a {@code String} value 128 * @throws org.apache.commons.beanutils.ConversionException unable to parse format 129 */ 130 public final void setFormat(String format) { 131 this.format = format; 132 regexp = CommonUtils.createPattern(format); 133 } 134 135 @Override 136 public int[] getDefaultTokens() { 137 return CommonUtils.EMPTY_INT_ARRAY; 138 } 139 140 @Override 141 public int[] getAcceptableTokens() { 142 return CommonUtils.EMPTY_INT_ARRAY; 143 } 144 145 @Override 146 public int[] getRequiredTokens() { 147 return CommonUtils.EMPTY_INT_ARRAY; 148 } 149 150 @Override 151 public void visitToken(DetailAST ast) { 152 throw new IllegalStateException("visitToken() shouldn't be called."); 153 } 154 155 @Override 156 public void beginTree(DetailAST rootAST) { 157 final Map<Integer, TextBlock> cppComments = getFileContents() 158 .getCppComments(); 159 final Map<Integer, List<TextBlock>> cComments = getFileContents() 160 .getCComments(); 161 final Set<Integer> lines = Sets.newHashSet(); 162 lines.addAll(cppComments.keySet()); 163 lines.addAll(cComments.keySet()); 164 165 for (Integer lineNo : lines) { 166 final String line = getLines()[lineNo - 1]; 167 final String lineBefore; 168 final TextBlock comment; 169 if (cppComments.containsKey(lineNo)) { 170 comment = cppComments.get(lineNo); 171 lineBefore = line.substring(0, comment.getStartColNo()); 172 } 173 else { 174 final List<TextBlock> commentList = cComments.get(lineNo); 175 comment = commentList.get(commentList.size() - 1); 176 lineBefore = line.substring(0, comment.getStartColNo()); 177 178 // do not check comment which doesn't end line 179 if (comment.getText().length == 1 180 && !line.substring(comment.getEndColNo() + 1).trim().isEmpty()) { 181 continue; 182 } 183 } 184 if (!regexp.matcher(lineBefore).find() 185 && !isLegalComment(comment)) { 186 log(lineNo, MSG_KEY); 187 } 188 } 189 } 190 191 /** 192 * Checks if given comment is legal (single-line and matches to the 193 * pattern). 194 * @param comment comment to check. 195 * @return true if the comment if legal. 196 */ 197 private boolean isLegalComment(final TextBlock comment) { 198 final boolean legal; 199 200 // multi-line comment can not be legal 201 if (legalComment == null || comment.getStartLineNo() != comment.getEndLineNo()) { 202 legal = false; 203 } 204 else { 205 String commentText = comment.getText()[0]; 206 // remove chars which start comment 207 commentText = commentText.substring(2); 208 // if this is a C-style comment we need to remove its end 209 if (commentText.endsWith("*/")) { 210 commentText = commentText.substring(0, commentText.length() - 2); 211 } 212 commentText = commentText.trim(); 213 legal = legalComment.matcher(commentText).find(); 214 } 215 return legal; 216 } 217}