View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 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  
25  import com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.ParseErrorMessage;
26  import com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.ParseStatus;
27  import com.puppycrawl.tools.checkstyle.api.DetailAST;
28  import com.puppycrawl.tools.checkstyle.api.DetailNode;
29  import com.puppycrawl.tools.checkstyle.api.FileText;
30  import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
31  import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
32  import com.puppycrawl.tools.checkstyle.utils.ParserUtil;
33  
34  /**
35   * Parses file as javadoc DetailNode tree and prints to system output stream.
36   */
37  public final class DetailNodeTreeStringPrinter {
38  
39      /** OS specific line separator. */
40      private static final String LINE_SEPARATOR = System.getProperty("line.separator");
41  
42      /** Prevent instances. */
43      private DetailNodeTreeStringPrinter() {
44          // no code
45      }
46  
47      /**
48       * Parse a file and print the parse tree.
49       *
50       * @param file the file to print.
51       * @return parse tree as a string
52       * @throws IOException if the file could not be read.
53       */
54      public static String printFileAst(File file) throws IOException {
55          return printTree(parseFile(file), "", "");
56      }
57  
58      /**
59       * Parse block comment DetailAST as Javadoc DetailNode tree.
60       *
61       * @param blockComment DetailAST
62       * @return DetailNode tree
63       * @throws IllegalArgumentException if there is an error parsing the Javadoc.
64       */
65      public static DetailNode parseJavadocAsDetailNode(DetailAST blockComment) {
66          final JavadocDetailNodeParser parser = new JavadocDetailNodeParser();
67          final ParseStatus status = parser.parseJavadocAsDetailNode(blockComment);
68          if (status.getParseErrorMessage() != null) {
69              throw new IllegalArgumentException(getParseErrorMessage(status.getParseErrorMessage()));
70          }
71          return status.getTree();
72      }
73  
74      /**
75       * Parse javadoc comment to DetailNode tree.
76       *
77       * @param javadocComment javadoc comment content
78       * @return tree
79       */
80      private static DetailNode parseJavadocAsDetailNode(String javadocComment) {
81          final DetailAST blockComment = ParserUtil.createBlockCommentNode(javadocComment);
82          return parseJavadocAsDetailNode(blockComment);
83      }
84  
85      /**
86       * Builds violation base on ParseErrorMessage's violation key, its arguments, etc.
87       *
88       * @param parseErrorMessage ParseErrorMessage
89       * @return error violation
90       */
91      private static String getParseErrorMessage(ParseErrorMessage parseErrorMessage) {
92          final LocalizedMessage message = new LocalizedMessage(
93                  "com.puppycrawl.tools.checkstyle.checks.javadoc.messages",
94                  DetailNodeTreeStringPrinter.class,
95                  parseErrorMessage.getMessageKey(),
96                  parseErrorMessage.getMessageArguments());
97          return "[ERROR:" + parseErrorMessage.getLineNumber() + "] " + message.getMessage();
98      }
99  
100     /**
101      * Print AST.
102      *
103      * @param ast the root AST node.
104      * @param rootPrefix prefix for the root node
105      * @param prefix prefix for other nodes
106      * @return string AST.
107      */
108     public static String printTree(DetailNode ast, String rootPrefix, String prefix) {
109         final StringBuilder messageBuilder = new StringBuilder(1024);
110         DetailNode node = ast;
111         while (node != null) {
112             if (node.getType() == JavadocTokenTypes.JAVADOC) {
113                 messageBuilder.append(rootPrefix);
114             }
115             else {
116                 messageBuilder.append(prefix);
117             }
118             messageBuilder.append(getIndentation(node))
119                     .append(JavadocUtil.getTokenName(node.getType())).append(" -> ")
120                     .append(JavadocUtil.escapeAllControlChars(node.getText())).append(" [")
121                     .append(node.getLineNumber()).append(':').append(node.getColumnNumber())
122                     .append(']').append(LINE_SEPARATOR)
123                     .append(printTree(JavadocUtil.getFirstChild(node), rootPrefix, prefix));
124             node = JavadocUtil.getNextSibling(node);
125         }
126         return messageBuilder.toString();
127     }
128 
129     /**
130      * Get indentation for a node.
131      *
132      * @param node the DetailNode to get the indentation for.
133      * @return the indentation in String format.
134      */
135     private static String getIndentation(DetailNode node) {
136         final boolean isLastChild = JavadocUtil.getNextSibling(node) == null;
137         DetailNode currentNode = node;
138         final StringBuilder indentation = new StringBuilder(1024);
139         while (currentNode.getParent() != null) {
140             currentNode = currentNode.getParent();
141             if (currentNode.getParent() == null) {
142                 if (isLastChild) {
143                     // only ASCII symbols must be used due to
144                     // problems with running tests on Windows
145                     indentation.append("`--");
146                 }
147                 else {
148                     indentation.append("|--");
149                 }
150             }
151             else {
152                 if (JavadocUtil.getNextSibling(currentNode) == null) {
153                     indentation.insert(0, "    ");
154                 }
155                 else {
156                     indentation.insert(0, "|   ");
157                 }
158             }
159         }
160         return indentation.toString();
161     }
162 
163     /**
164      * Parse a file and return the parse tree.
165      *
166      * @param file the file to parse.
167      * @return the root node of the parse tree.
168      * @throws IOException if the file could not be read.
169      */
170     private static DetailNode parseFile(File file) throws IOException {
171         final FileText text = new FileText(file, System.getProperty("file.encoding"));
172         return parseJavadocAsDetailNode(text.getFullText().toString());
173     }
174 
175 }