Skip to content

Commit

Permalink
Issue #7183: add JavadocMissingWhitespaceAfterAsteriskCheck
Browse files Browse the repository at this point in the history
  • Loading branch information
0blivious committed Mar 3, 2020
1 parent b653ead commit a59ead9
Show file tree
Hide file tree
Showing 20 changed files with 375 additions and 0 deletions.
1 change: 1 addition & 0 deletions .ci/jsoref-spellchecker/whitelist.words
Expand Up @@ -641,6 +641,7 @@ javadocblocktaglocation
javadoccontentlocation
javadocdetailnodeparser
javadocmethod
javadocmissingwhitespaceafterasterisk
javadocpackage
javadocparagraph
javadocpropertiesgenerator
Expand Down
1 change: 1 addition & 0 deletions config/checkstyle_checks.xml
Expand Up @@ -513,6 +513,7 @@
<module name="JavadocMethod">
<property name="validateThrows" value="true"/>
</module>
<module name="JavadocMissingWhitespaceAfterAsterisk"/>
<module name="JavadocParagraph"/>
<module name="JavadocStyle">
<property name="scope" value="public"/>
Expand Down
Expand Up @@ -636,6 +636,8 @@ private static void fillChecksFromJavadocPackage() {
BASE_PACKAGE + ".checks.javadoc.JavadocContentLocationCheck");
NAME_TO_FULL_MODULE_NAME.put("JavadocMethodCheck",
BASE_PACKAGE + ".checks.javadoc.JavadocMethodCheck");
NAME_TO_FULL_MODULE_NAME.put("JavadocMissingWhitespaceAfterAsteriskCheck",
BASE_PACKAGE + ".checks.javadoc.JavadocMissingWhitespaceAfterAsteriskCheck");
NAME_TO_FULL_MODULE_NAME.put("JavadocPackageCheck",
BASE_PACKAGE + ".checks.javadoc.JavadocPackageCheck");
NAME_TO_FULL_MODULE_NAME.put("JavadocParagraphCheck",
Expand Down
@@ -0,0 +1,131 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2020 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.checks.javadoc;

import com.puppycrawl.tools.checkstyle.StatelessCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.DetailNode;
import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
import com.puppycrawl.tools.checkstyle.utils.TokenUtil;

/**
* <p>
* Checks that at there is least one whitespace after the leading asterisk.
* </p>
* <ul>
* <li>
* Property {@code violateExecutionOnNonTightHtml} - Control when to print violations
* if the Javadoc being examined by this check violates the tight html rules defined at
* <a href="https://checkstyle.org/writingjavadocchecks.html#Tight-HTML_rules">Tight-HTML Rules</a>.
* Default value is {@code false}.
* </li>
* </ul>
* <p>
* To configure the default check:
* </p>
* <pre>
* &lt;module name="JavadocMissingWhitespaceAfterAsterisk"/&gt;
* </pre>
* <p>
* Code Example:
* </p>
* <pre>
* class TestClass {
* &#47;**
* *This is invalid java doc.
* *&#47;
* void invalidJavaDocMethod() {
* }
* &#47;**
* * This is valid java doc.
* *&#47;
* void validJavaDocMethod() {
* }
* &#47;**This is invalid single linejava doc. *&#47;
* void InvalidSingleLineJavaDocMethod() {
* }
* }
* </pre>
*
* @since 8.31
*/
@StatelessCheck
public class JavadocMissingWhitespaceAfterAsteriskCheck extends AbstractJavadocCheck {

/**
* A key is pointing to the warning message text in "messages.properties" file.
*/
public static final String MSG_KEY = "javadoc.missing.whitespace";

@Override
public int[] getDefaultJavadocTokens() {
return new int[] {
JavadocTokenTypes.JAVADOC,
};
}

@Override
public int[] getRequiredJavadocTokens() {
return getAcceptableJavadocTokens();
}

@Override
public void visitJavadocToken(DetailNode javadoc) {
if (isSingleLineJavadoc(getBlockCommentAst())) {
checkWhitespaceAfterAsterisk(JavadocUtil.getFirstChild(javadoc));
}
else {
for (DetailNode node : javadoc.getChildren()) {
if (node.getType() == JavadocTokenTypes.LEADING_ASTERISK) {
final DetailNode nextSibling = JavadocUtil.getNextSibling(node);
if (nextSibling.getType() != JavadocTokenTypes.EOF) {
checkWhitespaceAfterAsterisk(nextSibling);
}
}
}
}
}

/**
* Checks if there is at least one whitespace after leading asterisk.
*
* @param node the node after the leading asterisk.
*/
private void checkWhitespaceAfterAsterisk(DetailNode node) {
final String tagText = node.getText();

if (!Character.isWhitespace(tagText.charAt(0))) {
log(node.getLineNumber(), node.getColumnNumber(), MSG_KEY);
}
}

/**
* Checks if comment is single line comment.
*
* @param blockCommentStart the AST tree in which a block comment starts
* @return true, if comment is single line comment.
*/
private static boolean isSingleLineJavadoc(DetailAST blockCommentStart) {
final DetailAST blockCommentEnd = blockCommentStart.getLastChild();
return TokenUtil.areOnSameLine(blockCommentStart, blockCommentEnd);
}

}
Expand Up @@ -199,6 +199,9 @@
* JavadocBlockTagLocation
* </li>
* <li>
* JavadocMissingWhitespaceAfterAsterisk
* </li>
* <li>
* JavadocParagraph
* </li>
* <li>
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc=Invalid use of the '{'@inheritDoc'}' tag.
javadoc.legacyPackageHtml=Legacy package.html file should be removed.
javadoc.missed.html.close=Javadoc comment at column {0} has parse error. Missed HTML close tag ''{1}''. Sometimes it means that close tag missed for one of previous tags.
javadoc.missing=Missing a Javadoc comment.
javadoc.missing.whitespace=Missing a whitespace after the leading asterisk.
javadoc.noPeriod=First sentence should end with a period.
javadoc.packageInfo=Missing package-info.java file.
javadoc.paragraph.line.before=<p> tag should be preceded with an empty line.
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc=Unerlaubte Verwendung des Tags '{'@inheritDoc'}'.
javadoc.legacyPackageHtml=Die veraltete Datei package.html sollte entfernt werden.
javadoc.missed.html.close=Der Javadoc-Kommentar an Position {0} führt zu einem Parserfehler. Fehlendes schließendes HTML-Tag ''{1}''. Manchmal bedeutet dies, dass das schließende Tag eines vorgehenden Tags fehlt.
javadoc.missing=Es fehlt ein Javadoc-Kommentar.
javadoc.missing.whitespace=Nach dem Sternchen fehlt ein Leerzeichen.
javadoc.noPeriod=Der erste Satz sollte mit einem Punkt enden.
javadoc.packageInfo=Es fehlt eine package-info.java.
javadoc.paragraph.line.before=Einem <p>-Tag im Javadoc sollte eine leere Zeile vorangestellt werden.
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc=Uso no válido del '{'inheritDoc '}' etiqueta.
javadoc.legacyPackageHtml=Archivo package.html legado debe ser eliminado.
javadoc.missed.html.close=Javadoc comentario en la columna {0} tiene parse error. Perdidas HTML cerca etiqueta ''{1}''. A veces esto significa que cerca de la etiqueta se perdió por una de las etiquetas anteriores.
javadoc.missing=Falta el comentario Javadoc.
javadoc.missing.whitespace=Falta un espacio en blanco después del asterisco principal.
javadoc.noPeriod=La primera frase debería finalizar con un punto.
javadoc.packageInfo=Falta el archivo package-info.java.
javadoc.paragraph.line.before=<p> etiqueta debe ir precedida de una línea vacía.
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc=Virheellinen käyttö '{'inheritDoc '}' tag.
javadoc.legacyPackageHtml=Legacy package.html tiedosto tulisi poistaa.
javadoc.missed.html.close=Javadoc kommentti sarakkeessa {0} on Jäsennysvirhe. Missed HTML lähellä tag ''{1}''. Joskus se tarkoittaa, että lähellä tag jäi yhden edellisen tunnisteita.
javadoc.missing=Javadoc-kommentti puuttuu.
javadoc.missing.whitespace=Valkoinen tila puuttuu edessä olevan tähden jälkeen.
javadoc.noPeriod=Ensimmäinen virke pitäisi päättyä aikana.
javadoc.packageInfo=Puuttuu package-info.java tiedosto.
javadoc.paragraph.line.before=<P> tag pitäisi edeltää tyhjä rivi.
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc=Utilisation invalide de la balise '{'@inheritDoc '}'.
javadoc.legacyPackageHtml=L''ancien fichier package.html doit être supprimé.
javadoc.missed.html.close=Le commentaire Javadoc à la colonne {0} ne peut être analysé. La balise HTML fermante ''{1}'' n''a pas été trouvée. Parfois, cela signifie qu''une des balises fermantes précédentes est manquante.
javadoc.missing=Commentaire Javadoc manquant.
javadoc.missing.whitespace=Manque un espace après l'astérisque de tête.
javadoc.noPeriod=La première ligne de la Javadoc doit se terminer avec un point.
javadoc.packageInfo=Le fichier package-info.java est manquant.
javadoc.paragraph.line.before=La balise <p> doit être précédée d''une ligne vide.
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc='{' @inheritDoc '}'タグの使用が無効です。
javadoc.legacyPackageHtml=古い形式のpackage.htmlファイルは削除してください。
javadoc.missed.html.close={0} 桁目の Javadoc コメントでパースエラーが発生しました。HTML タグ ''{1}'' が閉じていません。どこかもっと前のタグが閉じていない可能性もあります。
javadoc.missing=Javadoc コメントがありません。
javadoc.missing.whitespace=先頭のアスタリスクの後に空白がありません。
javadoc.noPeriod=最初の一文はピリオドで終わらなければなりません。
javadoc.packageInfo=package-info.javaファイルがありません。
javadoc.paragraph.line.before=<p> タグの前には空行を入れてください。
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc=Uso inválido da tag '{'inheritDoc '}'.
javadoc.legacyPackageHtml=O arquivo package.html legado deve ser removido.
javadoc.missed.html.close=O comentário de Javadoc na coluna {0} tem erro sintático. Faltou uma etiqueta de fechamento HTML ''{1}''. Às vezes, isso significa que uma etiqueta de fechamento foi esquecida em uma das etiquetas HTML anteriores.
javadoc.missing=Falta o comentário Javadoc.
javadoc.missing.whitespace=Falta um espaço em branco após o asterisco inicial.
javadoc.noPeriod=A primeira frase deve acabar num ponto final.
javadoc.packageInfo=O arquivo package-info.java está faltando.
javadoc.paragraph.line.before=A tag <p> deveria ser precedida por uma linha vazia.
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc='{'@inheritDoc'}' etiketi kullanımı geçersiz.
javadoc.legacyPackageHtml=Eskide kalan package.html dosyaları kaldırılmalı.
javadoc.missed.html.close=Sütununda Javadoc comment {0} hatası ayrıştırmak vardır. Cevapsız HTML yakın etiketi ''{1}'' Bazen yakın etiketi önceki etiketler biri için kaçırmış demektir.
javadoc.missing=Javadoc açıklaması eksik.
javadoc.missing.whitespace=Önde gelen yıldız işaretinden sonra boşluk bırakma.
javadoc.noPeriod=İlk cümle nokta ile bitmeli.
javadoc.packageInfo=package-info.java dosyası eksik.
javadoc.paragraph.line.before=<p> etiketi boş bir çizgi ile gelmelidir.
Expand Down
Expand Up @@ -13,6 +13,7 @@ javadoc.invalidInheritDoc='{'@inheritDoc'}' 标签使用方式错误。
javadoc.legacyPackageHtml=文件 package.html 应被删除。
javadoc.missed.html.close=Javadoc 第 {0} 个字符解析错误。缺少 HTML 闭合标签: ''{1}''。 有时这代表前一标签未闭合。
javadoc.missing=缺少 Javadoc 。
javadoc.missing.whitespace=前导星号后缺少空格。
javadoc.noPeriod=Javadoc 首句应以句号结尾。
javadoc.packageInfo=缺少 package-info.java 文件。
javadoc.paragraph.line.before=<p> 标签前应有空行。
Expand Down
@@ -0,0 +1,65 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2020 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.checks.javadoc;

import static com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMissingWhitespaceAfterAsteriskCheck.MSG_KEY;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import org.junit.jupiter.api.Test;

import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;

public class JavadocMissingWhitespaceAfterAsteriskCheckTest
extends AbstractModuleTestSupport {

@Override
protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/checks/javadoc"
+
"/javadocmissingwhitespaceafterasterisk";
}

@Test
public void testGetAcceptableTokens() {
final JavadocMissingWhitespaceAfterAsteriskCheck checkObj =
new JavadocMissingWhitespaceAfterAsteriskCheck();
final int[] expected = {
JavadocTokenTypes.JAVADOC,
};
assertArrayEquals(expected, checkObj.getAcceptableJavadocTokens(),
"Default acceptable tokens are invalid");
}

@Test
public void testDefault() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(JavadocMissingWhitespaceAfterAsteriskCheck.class);
final String[] expected = {
"16:7: " + getCheckMessage(MSG_KEY),
"22:7: " + getCheckMessage(MSG_KEY),
"38:8: " + getCheckMessage(MSG_KEY),
"41:8: " + getCheckMessage(MSG_KEY),
};
verify(checkConfig, getPath("InputJavadocMissingWhitespaceAfterAsterisk.java"), expected);
}

}
Expand Up @@ -110,6 +110,7 @@ public class XpathRegressionTest extends AbstractModuleTestSupport {
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"AtclauseOrder",
"JavadocBlockTagLocation",
"JavadocMissingWhitespaceAfterAsterisk",
"JavadocParagraph",
"JavadocTagContinuationIndentation",
"MissingDeprecated",
Expand Down
@@ -0,0 +1,46 @@
package com.puppycrawl.tools.checkstyle.checks.javadoc.javadocmissingwhitespaceafterasterisk;
class InputJavadocMissingWhitespaceAfterAsterisk
{
/**
* @see Something
* This is ok.
**/
void foo() {}

/**
* This is ok.
*/
void foo1() {}

/**
*This is not ok.
*/
void foo2() {}

/**
* This is not ok.
*@see Something
*/
void foo3() {}

/**
*
* This is not ok.
*/
void foo4() {}

/** This is ok. */
void bar() {}

/** @see Something */
void bar1() {}

/**@see Something*/
void bar2() {}

/**This is not ok. */
void bar4() {}

/** This is ok. **/
void bar5() {}
}
5 changes: 5 additions & 0 deletions src/xdocs/checks.xml
Expand Up @@ -404,6 +404,11 @@
<td><a href="config_javadoc.html#JavadocMethod">JavadocMethod</a></td>
<td>Checks the Javadoc of a method or constructor.</td>
</tr>
<tr>
<td>
<a href="config_javadoc.html#JavadocMissingWhitespaceAfterAsterisk">JavadocMissingWhitespaceAfterAsterisk</a></td>
<td>Checks that at there is least one whitespace after the leading asterisk.</td>
</tr>
<tr>
<td><a href="config_javadoc.html#JavadocPackage">JavadocPackage</a></td>
<td>Checks that each Java package has a Javadoc file used for commenting.</td>
Expand Down
1 change: 1 addition & 0 deletions src/xdocs/config_filters.xml
Expand Up @@ -957,6 +957,7 @@ public class UserService {
<ul id="SuppressionXpathFilter_JavadocChecks">
<li>AtclauseOrder</li>
<li>JavadocBlockTagLocation</li>
<li>JavadocMissingWhitespaceAfterAsterisk</li>
<li>JavadocParagraph</li>
<li>JavadocTagContinuationIndentation</li>
<li>MissingDeprecated</li>
Expand Down

0 comments on commit a59ead9

Please sign in to comment.