001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.javadoc;
021
022import java.util.ArrayList;
023import java.util.List;
024import java.util.Optional;
025import java.util.function.Function;
026import java.util.regex.Pattern;
027import java.util.stream.Stream;
028
029import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
030import com.puppycrawl.tools.checkstyle.api.DetailNode;
031import com.puppycrawl.tools.checkstyle.api.JavadocCommentsTokenTypes;
032import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
033import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
034
035/**
036 * <div>
037 * Checks that
038 * <a href="https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html#firstsentence">
039 * Javadoc summary sentence</a> does not contain phrases that are not recommended to use.
040 * Summaries that contain only the {@code {@inheritDoc}} tag are skipped.
041 * Summaries that contain a non-empty {@code {@return}} are allowed.
042 * Check also violate Javadoc that does not contain first sentence, though with {@code {@return}} a
043 * period is not required as the Javadoc tool adds it.
044 * </div>
045 *
046 * <p>
047 * Note: For defining a summary, both the first sentence and the @summary tag approaches
048 * are supported.
049 * </p>
050 *
051 * @since 6.0
052 */
053@FileStatefulCheck
054public class SummaryJavadocCheck extends AbstractJavadocCheck {
055
056    /**
057     * A key is pointing to the warning message text in "messages.properties"
058     * file.
059     */
060    public static final String MSG_SUMMARY_FIRST_SENTENCE = "summary.first.sentence";
061
062    /**
063     * A key is pointing to the warning message text in "messages.properties"
064     * file.
065     */
066    public static final String MSG_SUMMARY_JAVADOC = "summary.javaDoc";
067
068    /**
069     * A key is pointing to the warning message text in "messages.properties"
070     * file.
071     */
072    public static final String MSG_SUMMARY_JAVADOC_MISSING = "summary.javaDoc.missing";
073
074    /**
075     * A key is pointing to the warning message text in "messages.properties" file.
076     */
077    public static final String MSG_SUMMARY_MISSING_PERIOD = "summary.javaDoc.missing.period";
078
079    /**
080     * This regexp is used to convert multiline javadoc to single-line without stars.
081     */
082    private static final Pattern JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN =
083            Pattern.compile("\n[ \\t]+(\\*)|^[ \\t]+(\\*)");
084
085    /**
086     * This regexp is used to remove html tags, whitespace, and asterisks from a string.
087     */
088    private static final Pattern HTML_ELEMENTS =
089            Pattern.compile("<[^>]*>");
090
091    /** Default period literal. */
092    private static final String DEFAULT_PERIOD = ".";
093
094    /**
095     * Specify the regexp for forbidden summary fragments.
096     */
097    private Pattern forbiddenSummaryFragments = CommonUtil.createPattern("^$");
098
099    /**
100     * Specify the period symbol. Used to check the first sentence ends with a period. Periods that
101     * are not followed by a whitespace character are ignored (eg. the period in v1.0). Because some
102     * periods include whitespace built into the character, if this is set to a non-default value
103     * any period will end the sentence, whether it is followed by whitespace or not.
104     */
105    private String period = DEFAULT_PERIOD;
106
107    /**
108     * Whether to validate untagged summary text in Javadoc.
109     */
110    private boolean shouldValidateUntaggedSummary = true;
111
112    /**
113     * Creates a new {@code SummaryJavadocCheck} instance.
114     */
115    public SummaryJavadocCheck() {
116        // no code by default
117    }
118
119    /**
120     * Setter to specify the regexp for forbidden summary fragments.
121     *
122     * @param pattern a pattern.
123     * @since 6.0
124     */
125    public void setForbiddenSummaryFragments(Pattern pattern) {
126        forbiddenSummaryFragments = pattern;
127    }
128
129    /**
130     * Setter to specify the period symbol. Used to check the first sentence ends with a period.
131     * Periods that are not followed by a whitespace character are ignored (eg. the period in v1.0).
132     * Because some periods include whitespace built into the character, if this is set to a
133     * non-default value any period will end the sentence, whether it is followed by whitespace or
134     * not.
135     *
136     * @param period period's value.
137     * @since 6.2
138     */
139    public void setPeriod(String period) {
140        this.period = period;
141    }
142
143    @Override
144    public int[] getDefaultJavadocTokens() {
145        return new int[] {
146            JavadocCommentsTokenTypes.JAVADOC_CONTENT,
147            JavadocCommentsTokenTypes.SUMMARY_INLINE_TAG,
148            JavadocCommentsTokenTypes.RETURN_INLINE_TAG,
149        };
150    }
151
152    @Override
153    public int[] getRequiredJavadocTokens() {
154        return getAcceptableJavadocTokens();
155    }
156
157    @Override
158    public void visitJavadocToken(DetailNode ast) {
159        if (isSummaryTag(ast) && isDefinedFirst(ast.getParent())) {
160            shouldValidateUntaggedSummary = false;
161            validateSummaryTag(ast);
162        }
163        else if (isInlineReturnTag(ast)) {
164            shouldValidateUntaggedSummary = false;
165            validateInlineReturnTag(ast);
166        }
167    }
168
169    @Override
170    public void leaveJavadocToken(DetailNode ast) {
171        if (ast.getType() == JavadocCommentsTokenTypes.JAVADOC_CONTENT) {
172            if (shouldValidateUntaggedSummary && !startsWithInheritDoc(ast)) {
173                validateUntaggedSummary(ast);
174            }
175            shouldValidateUntaggedSummary = true;
176        }
177    }
178
179    /**
180     * Checks the javadoc text for {@code period} at end and forbidden fragments.
181     *
182     * @param ast the javadoc text node
183     */
184    private void validateUntaggedSummary(DetailNode ast) {
185        final String summaryDoc = getSummarySentence(ast);
186        if (summaryDoc.isEmpty()) {
187            log(ast, MSG_SUMMARY_JAVADOC_MISSING);
188        }
189        else if (!period.isEmpty()) {
190            if (summaryDoc.contains(period)) {
191                final Optional<String> firstSentence = getFirstSentence(ast, period);
192
193                if (firstSentence.isPresent()) {
194                    if (containsForbiddenFragment(firstSentence.get())) {
195                        log(ast, MSG_SUMMARY_JAVADOC);
196                    }
197                }
198                else {
199                    log(ast, MSG_SUMMARY_FIRST_SENTENCE);
200                }
201            }
202            else {
203                log(ast, MSG_SUMMARY_FIRST_SENTENCE);
204            }
205        }
206    }
207
208    /**
209     * Whether the {@code {@summary}} tag is defined first in the javadoc.
210     *
211     * @param inlineTagNode node of type {@link JavadocCommentsTokenTypes#JAVADOC_INLINE_TAG}
212     * @return {@code true} if the {@code {@summary}} tag is defined first in the javadoc
213     */
214    private static boolean isDefinedFirst(DetailNode inlineTagNode) {
215        boolean isDefinedFirst = true;
216        DetailNode currentAst = inlineTagNode.getPreviousSibling();
217        while (currentAst != null && isDefinedFirst) {
218            switch (currentAst.getType()) {
219                case JavadocCommentsTokenTypes.TEXT ->
220                    isDefinedFirst = currentAst.getText().isBlank();
221                case JavadocCommentsTokenTypes.HTML_ELEMENT ->
222                    isDefinedFirst = isHtmlTagWithoutText(currentAst);
223                case JavadocCommentsTokenTypes.LEADING_ASTERISK,
224                     JavadocCommentsTokenTypes.NEWLINE -> {
225                    // Ignore formatting tokens
226                }
227                default -> isDefinedFirst = false;
228            }
229            currentAst = currentAst.getPreviousSibling();
230        }
231        return isDefinedFirst;
232    }
233
234    /**
235     * Whether some text is present inside the HTML element or tag.
236     *
237     * @param node DetailNode of type {@link JavadocCommentsTokenTypes#HTML_ELEMENT}
238     * @return {@code true} if some text is present inside the HTML element
239     */
240    public static boolean isHtmlTagWithoutText(DetailNode node) {
241        boolean isEmpty = true;
242        final DetailNode htmlContentToken =
243             JavadocUtil.findFirstToken(node, JavadocCommentsTokenTypes.HTML_CONTENT);
244
245        if (htmlContentToken != null) {
246            final DetailNode child = htmlContentToken.getFirstChild();
247            isEmpty = child.getType() == JavadocCommentsTokenTypes.HTML_ELEMENT
248                        && isHtmlTagWithoutText(child);
249        }
250        return isEmpty;
251    }
252
253    /**
254     * Checks if the given node is an inline summary tag.
255     *
256     * @param javadocInlineTag node
257     * @return {@code true} if inline tag is of
258     *       type {@link JavadocCommentsTokenTypes#SUMMARY_INLINE_TAG}
259     */
260    private static boolean isSummaryTag(DetailNode javadocInlineTag) {
261        return javadocInlineTag.getType() == JavadocCommentsTokenTypes.SUMMARY_INLINE_TAG;
262    }
263
264    /**
265     * Checks if the given node is an inline return node.
266     *
267     * @param javadocInlineTag node
268     * @return {@code true} if inline tag is of
269     *       type {@link JavadocCommentsTokenTypes#RETURN_INLINE_TAG}
270     */
271    private static boolean isInlineReturnTag(DetailNode javadocInlineTag) {
272        return javadocInlineTag.getType() == JavadocCommentsTokenTypes.RETURN_INLINE_TAG;
273    }
274
275    /**
276     * Checks the inline summary (if present) for {@code period} at end and forbidden fragments.
277     *
278     * @param inlineSummaryTag node of type {@link JavadocCommentsTokenTypes#SUMMARY_INLINE_TAG}
279     */
280    private void validateSummaryTag(DetailNode inlineSummaryTag) {
281        final DetailNode descriptionNode = JavadocUtil.findFirstToken(
282                inlineSummaryTag, JavadocCommentsTokenTypes.DESCRIPTION);
283        final String inlineSummary = getContentOfInlineCustomTag(descriptionNode);
284        final String summaryVisible = getVisibleContent(inlineSummary);
285        if (summaryVisible.isEmpty()) {
286            log(inlineSummaryTag, MSG_SUMMARY_JAVADOC_MISSING);
287        }
288        else if (!period.isEmpty()) {
289            final boolean isPeriodNotAtEnd =
290                    summaryVisible.lastIndexOf(period) != summaryVisible.length() - 1;
291            if (isPeriodNotAtEnd) {
292                log(inlineSummaryTag, MSG_SUMMARY_MISSING_PERIOD);
293            }
294            else if (containsForbiddenFragment(inlineSummary)) {
295                log(inlineSummaryTag, MSG_SUMMARY_JAVADOC);
296            }
297        }
298    }
299
300    /**
301     * Checks the inline return for forbidden fragments.
302     *
303     * @param inlineReturnTag node of type {@link JavadocCommentsTokenTypes#RETURN_INLINE_TAG}
304     */
305    private void validateInlineReturnTag(DetailNode inlineReturnTag) {
306        final DetailNode descriptionNode = JavadocUtil.findFirstToken(
307                inlineReturnTag, JavadocCommentsTokenTypes.DESCRIPTION);
308        final String inlineReturn = getContentOfInlineCustomTag(descriptionNode);
309        final String returnVisible = getVisibleContent(inlineReturn);
310        if (returnVisible.isEmpty()) {
311            log(inlineReturnTag, MSG_SUMMARY_JAVADOC_MISSING);
312        }
313        else if (containsForbiddenFragment(inlineReturn)) {
314            log(inlineReturnTag, MSG_SUMMARY_JAVADOC);
315        }
316    }
317
318    /**
319     * Gets the content of inline custom tag.
320     *
321     * @param descriptionNode node of type {@link JavadocCommentsTokenTypes#DESCRIPTION}
322     * @return String consisting of the content of inline custom tag.
323     */
324    public static String getContentOfInlineCustomTag(DetailNode descriptionNode) {
325        final StringBuilder customTagContent = new StringBuilder(256);
326        DetailNode curNode = descriptionNode;
327        while (curNode != null) {
328            if (curNode.getFirstChild() == null
329                && curNode.getType() != JavadocCommentsTokenTypes.LEADING_ASTERISK) {
330                customTagContent.append(curNode.getText());
331            }
332
333            DetailNode toVisit = curNode.getFirstChild();
334            while (curNode != descriptionNode && toVisit == null) {
335                toVisit = curNode.getNextSibling();
336                curNode = curNode.getParent();
337            }
338
339            curNode = toVisit;
340        }
341        return customTagContent.toString();
342    }
343
344    /**
345     * Gets the string that is visible to user in javadoc.
346     *
347     * @param summary entire content of summary javadoc.
348     * @return string that is visible to user in javadoc.
349     */
350    private static String getVisibleContent(String summary) {
351        final String visibleSummary = HTML_ELEMENTS.matcher(summary).replaceAll("");
352        return visibleSummary.trim();
353    }
354
355    /**
356     * Tests if first sentence contains forbidden summary fragment.
357     *
358     * @param firstSentence string with first sentence.
359     * @return {@code true} if first sentence contains forbidden summary fragment.
360     */
361    private boolean containsForbiddenFragment(String firstSentence) {
362        final String javadocText = JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN
363                .matcher(firstSentence).replaceAll(" ");
364        return forbiddenSummaryFragments.matcher(trimExcessWhitespaces(javadocText)).find();
365    }
366
367    /**
368     * Trims the given {@code text} of duplicate whitespaces.
369     *
370     * @param text the text to transform.
371     * @return the finalized form of the text.
372     */
373    private static String trimExcessWhitespaces(String text) {
374        final StringBuilder result = new StringBuilder(256);
375        boolean previousWhitespace = true;
376
377        for (int index = 0; index < text.length(); index++) {
378            final char letter = text.charAt(index);
379            final char print;
380            if (Character.isWhitespace(letter)) {
381                if (previousWhitespace) {
382                    continue;
383                }
384
385                previousWhitespace = true;
386                print = ' ';
387            }
388            else {
389                previousWhitespace = false;
390                print = letter;
391            }
392
393            result.append(print);
394        }
395
396        return result.toString();
397    }
398
399    /**
400     * Checks if the node starts with an {&#64;inheritDoc}.
401     *
402     * @param root the root node to examine.
403     * @return {@code true} if the javadoc starts with an {&#64;inheritDoc}.
404     */
405    private static boolean startsWithInheritDoc(DetailNode root) {
406        boolean found = false;
407        DetailNode node = root.getFirstChild();
408
409        while (node != null) {
410            if (node.getType() == JavadocCommentsTokenTypes.JAVADOC_INLINE_TAG
411                    && node.getFirstChild().getType()
412                            == JavadocCommentsTokenTypes.INHERIT_DOC_INLINE_TAG) {
413                found = true;
414            }
415            if ((node.getType() == JavadocCommentsTokenTypes.TEXT
416                    || node.getType() == JavadocCommentsTokenTypes.HTML_ELEMENT)
417                    && !CommonUtil.isBlank(node.getText())) {
418                break;
419            }
420            node = node.getNextSibling();
421        }
422
423        return found;
424    }
425
426    /**
427     * Finds and returns summary sentence.
428     *
429     * @param ast javadoc root node.
430     * @return violation string.
431     */
432    private static String getSummarySentence(DetailNode ast) {
433        final StringBuilder result = new StringBuilder(256);
434        DetailNode node = ast.getFirstChild();
435        while (node != null) {
436            if (node.getType() == JavadocCommentsTokenTypes.TEXT) {
437                result.append(node.getText());
438            }
439            else {
440                final String summary = result.toString();
441                if (CommonUtil.isBlank(summary)
442                        && node.getType() == JavadocCommentsTokenTypes.HTML_ELEMENT) {
443                    final DetailNode htmlContentToken = JavadocUtil.findFirstToken(
444                            node, JavadocCommentsTokenTypes.HTML_CONTENT);
445                    result.append(getStringInsideHtmlTag(summary, htmlContentToken));
446                }
447            }
448            node = node.getNextSibling();
449        }
450        return result.toString().trim();
451    }
452
453    /**
454     * Get concatenated string within text of html tags.
455     *
456     * @param result javadoc string
457     * @param detailNode htmlContent node
458     * @return java doc tag content appended in result
459     */
460    private static String getStringInsideHtmlTag(String result, DetailNode detailNode) {
461        final StringBuilder contents = new StringBuilder(result);
462        if (detailNode != null) {
463            DetailNode tempNode = detailNode.getFirstChild();
464            while (tempNode != null) {
465                if (tempNode.getType() == JavadocCommentsTokenTypes.TEXT) {
466                    contents.append(tempNode.getText());
467                }
468                else {
469                    final DetailNode htmlContentToken = JavadocUtil.findFirstToken(
470                            tempNode, JavadocCommentsTokenTypes.HTML_CONTENT);
471                    contents.append(getStringInsideHtmlTag("", htmlContentToken));
472                }
473                tempNode = tempNode.getNextSibling();
474            }
475        }
476        return contents.toString();
477    }
478
479    /**
480     * Finds the first sentence.
481     *
482     * @param ast The Javadoc root node.
483     * @param period The configured period symbol.
484     * @return An Optional containing the first sentence
485     *     up to and excluding the period, or an empty
486     *     Optional if no ending was found.
487     */
488    private static Optional<String> getFirstSentence(DetailNode ast, String period) {
489        final List<String> sentenceParts = new ArrayList<>();
490        Optional<String> result = Optional.empty();
491        for (String text : (Iterable<String>) streamTextParts(ast)::iterator) {
492            final Optional<String> sentenceEnding = findSentenceEnding(text, period);
493
494            if (sentenceEnding.isPresent()) {
495                sentenceParts.add(sentenceEnding.get());
496                result = Optional.of(String.join("", sentenceParts));
497                break;
498            }
499            sentenceParts.add(text);
500        }
501        return result;
502    }
503
504    /**
505     * Streams through all the text under the given node.
506     *
507     * @param node The Javadoc node to examine.
508     * @return All the text in all nodes that have no child nodes.
509     */
510    private static Stream<String> streamTextParts(DetailNode node) {
511        final Stream<String> result;
512        if (node.getFirstChild() == null) {
513            result = Stream.of(node.getText());
514        }
515        else {
516            final List<Stream<String>> childStreams = new ArrayList<>();
517            DetailNode child = node.getFirstChild();
518            while (child != null) {
519                childStreams.add(streamTextParts(child));
520                child = child.getNextSibling();
521            }
522            result = childStreams.stream().flatMap(Function.identity());
523        }
524        return result;
525    }
526
527    /**
528     * Finds the end of a sentence. The end of sentence detection here could be replaced in the
529     * future by Java's built-in BreakIterator class.
530     *
531     * @param text The string to search.
532     * @param period The period character to find.
533     * @return An Optional containing the string up to and excluding the period,
534     *     or empty Optional if no ending was found.
535     */
536    private static Optional<String> findSentenceEnding(String text, String period) {
537        int periodIndex = text.indexOf(period);
538        Optional<String> result = Optional.empty();
539        while (periodIndex >= 0) {
540            final int afterPeriodIndex = periodIndex + period.length();
541
542            // Handle western period separately as it is only the end of a sentence if followed
543            // by whitespace. Other period characters often include whitespace in the character.
544            if (!DEFAULT_PERIOD.equals(period)
545                || afterPeriodIndex >= text.length()
546                || Character.isWhitespace(text.charAt(afterPeriodIndex))) {
547                final String resultStr = text.substring(0, periodIndex);
548                result = Optional.of(resultStr);
549                break;
550            }
551            periodIndex = text.indexOf(period, afterPeriodIndex);
552        }
553        return result;
554    }
555
556}