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