View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle;
21  
22  import java.io.File;
23  import java.io.IOException;
24  import java.nio.charset.Charset;
25  
26  import com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.ParseErrorMessage;
27  import com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.ParseStatus;
28  import com.puppycrawl.tools.checkstyle.api.DetailAST;
29  import com.puppycrawl.tools.checkstyle.api.DetailNode;
30  import com.puppycrawl.tools.checkstyle.api.FileText;
31  import com.puppycrawl.tools.checkstyle.api.JavadocCommentsTokenTypes;
32  import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
33  import com.puppycrawl.tools.checkstyle.utils.ParserUtil;
34  
35  /**
36   * Parses file as javadoc DetailNode tree and prints to system output stream.
37   */
38  public final class DetailNodeTreeStringPrinter {
39  
40      /** OS specific line separator. */
41      private static final String LINE_SEPARATOR = System.getProperty("line.separator");
42  
43      /** Prevent instances. */
44      private DetailNodeTreeStringPrinter() {
45          // no code
46      }
47  
48      /**
49       * Parse a file and print the parse tree.
50       *
51       * @param file the file to print.
52       * @return parse tree as a string
53       * @throws IOException if the file could not be read.
54       */
55      public static String printFileAst(File file) throws IOException {
56          return printTree(parseFile(file), "", "");
57      }
58  
59      /**
60       * Parse block comment DetailAST as Javadoc DetailNode tree.
61       *
62       * @param blockComment DetailAST
63       * @return DetailNode tree
64       * @throws IllegalArgumentException if there is an error parsing the Javadoc.
65       */
66      public static DetailNode parseJavadocAsDetailNode(DetailAST blockComment) {
67          final JavadocDetailNodeParser parser = new JavadocDetailNodeParser();
68          final ParseStatus status = parser.parseJavadocComment(blockComment);
69          if (status.getParseErrorMessage() != null) {
70              throw new IllegalArgumentException(getParseErrorMessage(status.getParseErrorMessage()));
71          }
72          return status.getTree();
73      }
74  
75      /**
76       * Builds violation base on ParseErrorMessage's violation key, its arguments, etc.
77       *
78       * @param parseErrorMessage ParseErrorMessage
79       * @return error violation
80       */
81      private static String getParseErrorMessage(ParseErrorMessage parseErrorMessage) {
82          final LocalizedMessage message = new LocalizedMessage(
83                  "com.puppycrawl.tools.checkstyle.checks.javadoc.messages",
84                  DetailNodeTreeStringPrinter.class,
85                  parseErrorMessage.getMessageKey(),
86                  parseErrorMessage.getMessageArguments());
87          return "[ERROR:" + parseErrorMessage.getLineNumber() + "] " + message.getMessage();
88      }
89  
90      /**
91       * Print AST.
92       *
93       * @param ast the root AST node.
94       * @param rootPrefix prefix for the root node
95       * @param prefix prefix for other nodes
96       * @return string AST.
97       */
98      public static String printTree(DetailNode ast, String rootPrefix, String prefix) {
99          final StringBuilder messageBuilder = new StringBuilder(1024);
100         DetailNode node = ast;
101         while (node != null) {
102             if (node.getType() == JavadocCommentsTokenTypes.JAVADOC_CONTENT) {
103                 messageBuilder.append(rootPrefix);
104             }
105             else {
106                 messageBuilder.append(prefix);
107             }
108             messageBuilder.append(getIndentation(node))
109                     .append(JavadocUtil.getTokenName(node.getType())).append(" -> ")
110                     .append(JavadocUtil.escapeAllControlChars(node.getText())).append(" [")
111                     .append(node.getLineNumber()).append(':').append(node.getColumnNumber() + 1)
112                     .append(']').append(LINE_SEPARATOR)
113                     .append(printTree(node.getFirstChild(), rootPrefix, prefix));
114             node = node.getNextSibling();
115         }
116         return messageBuilder.toString();
117     }
118 
119     /**
120      * Get indentation for a node.
121      *
122      * @param node the DetailNode to get the indentation for.
123      * @return the indentation in String format.
124      */
125     private static String getIndentation(DetailNode node) {
126         final boolean isLastChild = node.getNextSibling() == null;
127         DetailNode currentNode = node;
128         final StringBuilder indentation = new StringBuilder(1024);
129         while (currentNode.getParent() != null) {
130             currentNode = currentNode.getParent();
131             if (currentNode.getParent() == null) {
132                 if (isLastChild) {
133                     // only ASCII symbols must be used due to
134                     // problems with running tests on Windows
135                     indentation.append("`--");
136                 }
137                 else {
138                     indentation.append("|--");
139                 }
140             }
141             else {
142                 if (currentNode.getNextSibling() == null) {
143                     indentation.insert(0, "    ");
144                 }
145                 else {
146                     indentation.insert(0, "|   ");
147                 }
148             }
149         }
150         return indentation.toString();
151     }
152 
153     /**
154      * Parse a file and return the parse tree.
155      *
156      * @param file the file to parse.
157      * @return the root node of the parse tree.
158      * @throws IOException if the file could not be read.
159      */
160     private static DetailNode parseFile(File file) throws IOException {
161         final FileText text = new FileText(file, Charset.defaultCharset().name());
162         final DetailAST comment = ParserUtil.createBlockCommentNode(text.getFullText().toString());
163         return parseJavadocAsDetailNode(comment);
164     }
165 
166 }