001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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;
021
022import java.io.File;
023import java.io.IOException;
024import java.nio.charset.StandardCharsets;
025
026import com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.ParseErrorMessage;
027import com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.ParseStatus;
028import com.puppycrawl.tools.checkstyle.api.DetailAST;
029import com.puppycrawl.tools.checkstyle.api.DetailNode;
030import com.puppycrawl.tools.checkstyle.api.FileText;
031import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
032import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
033import com.puppycrawl.tools.checkstyle.utils.ParserUtil;
034
035/**
036 * Parses file as javadoc DetailNode tree and prints to system output stream.
037 */
038public final class DetailNodeTreeStringPrinter {
039
040    /** OS specific line separator. */
041    private static final String LINE_SEPARATOR = System.getProperty("line.separator");
042
043    /** Prevent instances. */
044    private DetailNodeTreeStringPrinter() {
045        // no code
046    }
047
048    /**
049     * Parse a file and print the parse tree.
050     *
051     * @param file the file to print.
052     * @return parse tree as a string
053     * @throws IOException if the file could not be read.
054     */
055    public static String printFileAst(File file) throws IOException {
056        return printTree(parseFile(file), "", "");
057    }
058
059    /**
060     * Parse block comment DetailAST as Javadoc DetailNode tree.
061     *
062     * @param blockComment DetailAST
063     * @return DetailNode tree
064     * @throws IllegalArgumentException if there is an error parsing the Javadoc.
065     */
066    public static DetailNode parseJavadocAsDetailNode(DetailAST blockComment) {
067        final JavadocDetailNodeParser parser = new JavadocDetailNodeParser();
068        final ParseStatus status = parser.parseJavadocAsDetailNode(blockComment);
069        if (status.getParseErrorMessage() != null) {
070            throw new IllegalArgumentException(getParseErrorMessage(status.getParseErrorMessage()));
071        }
072        return status.getTree();
073    }
074
075    /**
076     * Parse javadoc comment to DetailNode tree.
077     *
078     * @param javadocComment javadoc comment content
079     * @return tree
080     */
081    private static DetailNode parseJavadocAsDetailNode(String javadocComment) {
082        final DetailAST blockComment = ParserUtil.createBlockCommentNode(javadocComment);
083        return parseJavadocAsDetailNode(blockComment);
084    }
085
086    /**
087     * Builds violation base on ParseErrorMessage's violation key, its arguments, etc.
088     *
089     * @param parseErrorMessage ParseErrorMessage
090     * @return error violation
091     */
092    private static String getParseErrorMessage(ParseErrorMessage parseErrorMessage) {
093        final LocalizedMessage message = new LocalizedMessage(
094                "com.puppycrawl.tools.checkstyle.checks.javadoc.messages",
095                DetailNodeTreeStringPrinter.class,
096                parseErrorMessage.getMessageKey(),
097                parseErrorMessage.getMessageArguments());
098        return "[ERROR:" + parseErrorMessage.getLineNumber() + "] " + message.getMessage();
099    }
100
101    /**
102     * Print AST.
103     *
104     * @param ast the root AST node.
105     * @param rootPrefix prefix for the root node
106     * @param prefix prefix for other nodes
107     * @return string AST.
108     */
109    public static String printTree(DetailNode ast, String rootPrefix, String prefix) {
110        final StringBuilder messageBuilder = new StringBuilder(1024);
111        DetailNode node = ast;
112        while (node != null) {
113            if (node.getType() == JavadocTokenTypes.JAVADOC) {
114                messageBuilder.append(rootPrefix);
115            }
116            else {
117                messageBuilder.append(prefix);
118            }
119            messageBuilder.append(getIndentation(node))
120                    .append(JavadocUtil.getTokenName(node.getType())).append(" -> ")
121                    .append(JavadocUtil.escapeAllControlChars(node.getText())).append(" [")
122                    .append(node.getLineNumber()).append(':').append(node.getColumnNumber())
123                    .append(']').append(LINE_SEPARATOR)
124                    .append(printTree(JavadocUtil.getFirstChild(node), rootPrefix, prefix));
125            node = JavadocUtil.getNextSibling(node);
126        }
127        return messageBuilder.toString();
128    }
129
130    /**
131     * Get indentation for a node.
132     *
133     * @param node the DetailNode to get the indentation for.
134     * @return the indentation in String format.
135     */
136    private static String getIndentation(DetailNode node) {
137        final boolean isLastChild = JavadocUtil.getNextSibling(node) == null;
138        DetailNode currentNode = node;
139        final StringBuilder indentation = new StringBuilder(1024);
140        while (currentNode.getParent() != null) {
141            currentNode = currentNode.getParent();
142            if (currentNode.getParent() == null) {
143                if (isLastChild) {
144                    // only ASCII symbols must be used due to
145                    // problems with running tests on Windows
146                    indentation.append("`--");
147                }
148                else {
149                    indentation.append("|--");
150                }
151            }
152            else {
153                if (JavadocUtil.getNextSibling(currentNode) == null) {
154                    indentation.insert(0, "    ");
155                }
156                else {
157                    indentation.insert(0, "|   ");
158                }
159            }
160        }
161        return indentation.toString();
162    }
163
164    /**
165     * Parse a file and return the parse tree.
166     *
167     * @param file the file to parse.
168     * @return the root node of the parse tree.
169     * @throws IOException if the file could not be read.
170     */
171    private static DetailNode parseFile(File file) throws IOException {
172        final FileText text = new FileText(file.getAbsoluteFile(),
173            System.getProperty("file.encoding", StandardCharsets.UTF_8.name()));
174        return parseJavadocAsDetailNode(text.getFullText().toString());
175    }
176
177}