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;
024
025import com.puppycrawl.tools.checkstyle.StatelessCheck;
026import com.puppycrawl.tools.checkstyle.api.DetailNode;
027import com.puppycrawl.tools.checkstyle.api.JavadocCommentsTokenTypes;
028import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
029import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
030
031/**
032 * <div>
033 * Checks the indentation of the continuation lines in block tags. That is whether the continued
034 * description of at clauses should be indented or not. If the text is not properly indented it
035 * throws a violation. A continuation line is when the description starts/spans past the line with
036 * the tag. Default indentation required is at least 4, but this can be changed with the help of
037 * properties below.
038 * </div>
039 * <ul>
040 * <li>
041 * Notes:
042 * This check does not validate the indentation of lines inside {@code pre} tags.
043 * </li>
044 * </ul>
045 *
046 * @since 6.0
047 */
048@StatelessCheck
049public class JavadocTagContinuationIndentationCheck extends AbstractJavadocCheck {
050
051    /**
052     * A key is pointing to the warning message text in "messages.properties" file.
053     */
054    public static final String MSG_KEY = "tag.continuation.indent";
055
056    /** Default tag continuation indentation. */
057    private static final int DEFAULT_INDENTATION = 4;
058
059    /**
060     * Constant for the pre tag name.
061     */
062    private static final String PRE_TAG = "pre";
063
064    /**
065     * Specify how many spaces to use for new indentation level.
066     */
067    private int offset = DEFAULT_INDENTATION;
068
069    /**
070     * Creates a new {@code JavadocTagContinuationIndentationCheck} instance.
071     */
072    public JavadocTagContinuationIndentationCheck() {
073        // no code by default
074    }
075
076    /**
077     * Setter to specify how many spaces to use for new indentation level.
078     *
079     * @param offset custom value.
080     * @since 6.0
081     */
082    public void setOffset(int offset) {
083        this.offset = offset;
084    }
085
086    @Override
087    public int[] getDefaultJavadocTokens() {
088        return new int[] {
089            JavadocCommentsTokenTypes.HTML_ELEMENT,
090            JavadocCommentsTokenTypes.DESCRIPTION,
091        };
092    }
093
094    @Override
095    public int[] getRequiredJavadocTokens() {
096        return getAcceptableJavadocTokens();
097    }
098
099    @Override
100    public void visitJavadocToken(DetailNode ast) {
101        if (isBlockDescription(ast) && !isInlineDescription(ast)) {
102            final List<DetailNode> textNodes = getTargetedTextNodes(ast);
103            for (DetailNode textNode : textNodes) {
104                if (isViolation(textNode)) {
105                    log(textNode.getLineNumber(), MSG_KEY, offset);
106                }
107            }
108        }
109    }
110
111    /**
112     * Returns all targeted text nodes from the given AST node.
113     * This method decides whether to process the node as a description node
114     * or as an HTML element node and delegates to the appropriate helper method.
115     *
116     * @param ast the AST node to process
117     * @return list of targeted text nodes
118     */
119    private static List<DetailNode> getTargetedTextNodes(DetailNode ast) {
120        final List<DetailNode> textNodes;
121        if (ast.getType() == JavadocCommentsTokenTypes.DESCRIPTION) {
122            textNodes = getTargetedTextNodesInsideDescription(ast);
123        }
124        else {
125            textNodes = getTargetedTextNodesInsideHtmlElement(ast);
126        }
127        return textNodes;
128    }
129
130    /**
131     * Returns all targeted text nodes within an HTML element subtree.
132     *
133     * @param ast the HTML element AST node
134     * @return list of targeted text nodes inside the HTML element
135     */
136    private static List<DetailNode> getTargetedTextNodesInsideHtmlElement(DetailNode ast) {
137        final List<DetailNode> textNodes = new ArrayList<>();
138        if (!JavadocUtil.isTag(ast, PRE_TAG) && !isInsidePreTag(ast)) {
139            final DetailNode prevSibling = ast.getPreviousSibling();
140            if (prevSibling != null && isTargetTextNode(prevSibling)) {
141                textNodes.add(prevSibling);
142            }
143            DetailNode node = ast.getFirstChild();
144            while (node != null) {
145                if (node.getType() == JavadocCommentsTokenTypes.HTML_CONTENT) {
146                    // HTML_CONTENT contain text nodes only, so it can be treated as
147                    // DESCRIPTION node
148                    textNodes.addAll(getTargetedTextNodesInsideDescription(node));
149                }
150                else if (subtreeContainsAttributeValue(node)) {
151                    textNodes.addAll(getTargetedTextNodesInsideHtmlElement(node));
152                }
153                else if (isTargetTextNode(node)) {
154                    textNodes.add(node);
155                }
156                node = node.getNextSibling();
157            }
158        }
159        return textNodes;
160    }
161
162    /**
163     * Checks whether the given subtree node represents part of an HTML tag
164     * structure that may contain attribute values.
165     *
166     * @param node the AST node to check
167     * @return true if the subtree may contain attribute values, false otherwise
168     */
169    private static boolean subtreeContainsAttributeValue(DetailNode node) {
170        return node.getType() == JavadocCommentsTokenTypes.HTML_TAG_START
171            || node.getType() == JavadocCommentsTokenTypes.HTML_ATTRIBUTES
172            || node.getType() == JavadocCommentsTokenTypes.HTML_ATTRIBUTE;
173    }
174
175    /**
176     * Returns all targeted text nodes inside a description node.
177     *
178     * @param descriptionNode the DESCRIPTION node to process
179     * @return list of targeted text nodes inside the description node
180     */
181    private static List<DetailNode> getTargetedTextNodesInsideDescription(
182            DetailNode descriptionNode) {
183        final List<DetailNode> textNodes = new ArrayList<>();
184        DetailNode node = descriptionNode.getFirstChild();
185        final DetailNode previousSibling = descriptionNode.getPreviousSibling();
186
187        // special case if the text node is previous sibling of the description node
188        if (isTargetTextNode(previousSibling)) {
189            textNodes.add(previousSibling);
190        }
191
192        // special case for the first child, because leading asterisk
193        // will be previous sibling of the parent (description node) not the node itself
194        if (isLeadingAsterisk(descriptionNode.getPreviousSibling())) {
195            textNodes.add(node);
196        }
197
198        while (node != null) {
199            if (isTargetTextNode(node)) {
200                textNodes.add(node);
201            }
202            node = node.getNextSibling();
203        }
204
205        return textNodes;
206    }
207
208    /**
209     * Determines whether the given node is a targeted node.
210     *
211     * @param node the AST node to check
212     * @return true if the node is a targeted node, false otherwise
213     */
214    private static boolean isTargetTextNode(DetailNode node) {
215        final DetailNode previousSibling = node.getPreviousSibling();
216
217        return previousSibling != null
218            && isTextOrAttributeValueNode(node)
219            && !isBeforePreTag(node)
220            && isLeadingAsterisk(previousSibling);
221    }
222
223    /**
224     * Checks whether the given node is a leading asterisk.
225     *
226     * @param node the AST node to check
227     * @return true if the node is a leading asterisk, false otherwise
228     */
229    private static boolean isLeadingAsterisk(DetailNode node) {
230        return node.getType() == JavadocCommentsTokenTypes.LEADING_ASTERISK
231            || node.getType() == JavadocCommentsTokenTypes.LEADING_ASTERISKS;
232    }
233
234    /**
235     * Checks if a node is located before a {@code pre} tag.
236     *
237     * @param node the node to check
238     * @return true if the node is before a pre tag, false otherwise
239     */
240    private static boolean isBeforePreTag(DetailNode node) {
241        final DetailNode nextSibling = node.getNextSibling();
242        final boolean isBeforePreTag;
243        if (nextSibling != null
244                && nextSibling.getType() == JavadocCommentsTokenTypes.DESCRIPTION) {
245            isBeforePreTag = JavadocUtil.isTag(nextSibling.getFirstChild(), PRE_TAG);
246        }
247        else if (nextSibling != null) {
248            isBeforePreTag = JavadocUtil.isTag(nextSibling, PRE_TAG);
249        }
250        else {
251            isBeforePreTag = false;
252        }
253        return isBeforePreTag;
254    }
255
256    /**
257     * Checks if a node is inside a {@code pre} tag.
258     *
259     * @param node the node to check
260     * @return true if the node is inside a pre tag, false otherwise
261     */
262    private static boolean isInsidePreTag(DetailNode node) {
263        final DetailNode htmlElementParent = node.getParent().getParent();
264        return JavadocUtil.isTag(htmlElementParent, PRE_TAG);
265    }
266
267    /**
268     * Checks whether the given node is either a TEXT node or an ATTRIBUTE_VALUE node.
269     *
270     * @param node the AST node to check
271     * @return true if the node is a TEXT or ATTRIBUTE_VALUE node, false otherwise
272     */
273    private static boolean isTextOrAttributeValueNode(DetailNode node) {
274        return node.getType() == JavadocCommentsTokenTypes.TEXT
275            || node.getType() == JavadocCommentsTokenTypes.ATTRIBUTE_VALUE;
276    }
277
278    /**
279     * Checks if a text node meets the criteria for a violation.
280     * If the text is shorter than {@code offset} characters, then a violation is
281     * detected if the text is not blank or the next node is not a newline.
282     * If the text is longer than {@code offset} characters, then a violation is
283     * detected if any of the first {@code offset} characters are not blank.
284     *
285     * @param textNode the node to check.
286     * @return true if the node has a violation.
287     */
288    private boolean isViolation(DetailNode textNode) {
289        boolean result = false;
290        final String text = textNode.getText();
291        if (text.length() <= offset) {
292            if (CommonUtil.isBlank(text)) {
293                final DetailNode nextNode = textNode.getNextSibling();
294                if (nextNode.getType() != JavadocCommentsTokenTypes.NEWLINE) {
295                    // text is blank but line hasn't ended yet
296                    result = true;
297                }
298            }
299            else {
300                // text is not blank
301                result = true;
302            }
303        }
304        else if (!CommonUtil.isBlank(text.substring(1, offset + 1))) {
305            // first offset number of characters are not blank
306            result = true;
307        }
308        return result;
309    }
310
311    /**
312     * Checks if the given description node is part of a block Javadoc tag.
313     *
314     * @param description the node to check
315     * @return {@code true} if the node is inside a block tag, {@code false} otherwise
316     */
317    private static boolean isBlockDescription(DetailNode description) {
318        boolean isBlock = false;
319        DetailNode currentNode = description;
320        while (currentNode != null) {
321            if (currentNode.getType() == JavadocCommentsTokenTypes.JAVADOC_BLOCK_TAG) {
322                isBlock = true;
323                break;
324            }
325            currentNode = currentNode.getParent();
326        }
327        return isBlock;
328    }
329
330    /**
331     * Checks, if description node is a description of in-line tag.
332     *
333     * @param description DESCRIPTION node.
334     * @return true, if description node is a description of in-line tag.
335     */
336    private static boolean isInlineDescription(DetailNode description) {
337        boolean isInline = false;
338        DetailNode currentNode = description;
339        while (currentNode != null) {
340            if (currentNode.getType() == JavadocCommentsTokenTypes.JAVADOC_INLINE_TAG) {
341                isInline = true;
342                break;
343            }
344            currentNode = currentNode.getParent();
345        }
346        return isInline;
347    }
348
349}