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 Apr 2, 2020
1 parent 834b505 commit c32a0f6
Show file tree
Hide file tree
Showing 22 changed files with 511 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .ci/jsoref-spellchecker/whitelist.words
Expand Up @@ -640,6 +640,7 @@ javadocblocktaglocation
javadoccontentlocation
javadocdetailnodeparser
javadocmethod
javadocmissingwhitespaceafterasterisk
javadocpackage
javadocparagraph
javadocpropertiesgenerator
Expand Down Expand Up @@ -759,6 +760,7 @@ libexec
lifecycle
linebreak
linecolumn
linejava
linelength
linkcheck
linkplain
Expand Down
1 change: 0 additions & 1 deletion .ci/pitest.sh
Expand Up @@ -170,7 +170,6 @@ pitest-javadoc)
mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
declare -a ignoredItems=(
"AbstractJavadocCheck.java.html:<td class='covered'><pre><span class='survived'> Arrays.sort(acceptableJavadocTokens);</span></pre></td></tr>"
"AbstractJavadocCheck.java.html:<td class='covered'><pre><span class='survived'> Arrays.sort(defaultJavadocTokens);</span></pre></td></tr>"
"AbstractJavadocCheck.java.html:<td class='covered'><pre><span class='survived'> beginJavadocTree(root);</span></pre></td></tr>"
"AbstractJavadocCheck.java.html:<td class='covered'><pre><span class='survived'> finishJavadocTree(root);</span></pre></td></tr>"
"AbstractJavadocCheck.java.html:<td class='covered'><pre><span class='survived'> javadocTokens.clear();</span></pre></td></tr>"
Expand Down
1 change: 1 addition & 0 deletions config/checkstyle_checks.xml
Expand Up @@ -514,6 +514,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 @@ -639,6 +639,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,141 @@
////////////////////////////////////////////////////////////////////////////////
// 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.DetailNode;
import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;

/**
* <p>
* Checks that there is at least one whitespace after the leading asterisk.
* Although spaces after asterisks are optional in the Javadoc comments, their absence
* makes the documentation difficult to read. It is the de facto standard to put at 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>
* &#47;** This is valid single-line Javadoc. *&#47;
* class TestClass {
* &#47;**
* *This is invalid Javadoc.
* *&#47;
* int invalidJavaDoc;
* &#47;**
* * This is valid Javadoc.
* *&#47;
* void validJavaDocMethod() {
* }
* &#47;**This is invalid single-line Javadoc. *&#47;
* void invalidSingleLineJavaDocMethod() {
* }
* &#47;** This is valid single-line Javadoc. *&#47;
* void validSingleLineJavaDocMethod() {
* }
* }
* </pre>
*
* @since 8.32
*/
@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,
JavadocTokenTypes.LEADING_ASTERISK,
};
}

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

@Override
public void visitJavadocToken(DetailNode detailNode) {
final DetailNode textNode;

if (detailNode.getType() == JavadocTokenTypes.JAVADOC) {
textNode = JavadocUtil.getFirstChild(detailNode);
}
else {
textNode = JavadocUtil.getNextSibling(detailNode);
}

if (textNode != null
&& textNode.getType() != JavadocTokenTypes.EOF
&& !hasWhitespaceAfterAsteriskBeforeText(textNode)) {
log(textNode.getLineNumber(), textNode.getColumnNumber(), MSG_KEY);
}
}

/**
* Checks if there is at least one whitespace after leading asterisks and before text.
* If {@code tagText} contains no characters other than "*", it is considered the
* same as there is whitespace.
*
* @param node the node after the leading asterisks.
* @return true if there is at least one white space after asterisk and before text.
*
*/
private static boolean hasWhitespaceAfterAsteriskBeforeText(DetailNode node) {
boolean hasWhitespaceAfterAsteriskBeforeText = false;
final String tagText = node.getText();

for (int i = 0; i < tagText.length(); i++) {
if (tagText.charAt(i) != '*') {
if (Character.isWhitespace(tagText.charAt(i))) {
hasWhitespaceAfterAsteriskBeforeText = true;
}
break;
}
if (i == tagText.length() - 1) {
hasWhitespaceAfterAsteriskBeforeText = true;
}
}

return hasWhitespaceAfterAsteriskBeforeText;
}

}
Expand Up @@ -118,6 +118,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,98 @@
////////////////////////////////////////////////////////////////////////////////
// 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;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;

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,
JavadocTokenTypes.LEADING_ASTERISK,
};
assertArrayEquals(expected, checkObj.getAcceptableJavadocTokens(),
"Default tokens are invalid");
}

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

@Test
public void testValid() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(JavadocMissingWhitespaceAfterAsteriskCheck.class);
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;

verify(checkConfig,
getPath("InputJavadocMissingWhitespaceAfterAsteriskValid.java"), expected);
}

@Test
public void testInvalid() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(JavadocMissingWhitespaceAfterAsteriskCheck.class);
final String[] expected = {
"5:4: " + getCheckMessage(MSG_KEY),
"11:7: " + getCheckMessage(MSG_KEY),
"16:11: " + getCheckMessage(MSG_KEY),
"23:11: " + getCheckMessage(MSG_KEY),
"27:13: " + getCheckMessage(MSG_KEY),
"33:7: " + getCheckMessage(MSG_KEY),
"38:7: " + getCheckMessage(MSG_KEY),
"43:7: " + getCheckMessage(MSG_KEY),
"48:7: " + getCheckMessage(MSG_KEY),
"50:7: " + getCheckMessage(MSG_KEY),
"54:8: " + getCheckMessage(MSG_KEY),
"57:8: " + getCheckMessage(MSG_KEY),
"60:10: " + getCheckMessage(MSG_KEY),
};
verify(checkConfig,
getPath("InputJavadocMissingWhitespaceAfterAsteriskInvalid.java"), expected);
}

}
Expand Up @@ -84,6 +84,7 @@ public class XpathRegressionTest extends AbstractModuleTestSupport {
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"AtclauseOrder",
"JavadocBlockTagLocation",
"JavadocMissingWhitespaceAfterAsterisk",
"JavadocParagraph",
"JavadocStyle",
"JavadocTagContinuationIndentation",
Expand Down

0 comments on commit c32a0f6

Please sign in to comment.