Debian Codegraph @

src/com/google/javascript/jscomp/DotFormatter.java

raw symbols SCIP
1 /*
2 * Copyright 2007 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
20 import com.google.javascript.jscomp.graph.GraphvizGraph;
21 import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
22 import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
23 import com.google.javascript.jscomp.graph.GraphvizGraph.GraphvizEdge;
24 import com.google.javascript.jscomp.graph.GraphvizGraph.GraphvizNode;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.Token;
27 import com.google.javascript.rhino.jstype.JSType;
28
29 import java.io.IOException;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.List;
33
34 /**
35 * <p>DotFormatter prints out a dot file of the Abstract Syntax Tree.
36 * For a detailed description of the dot format and visualization tool refer
37 * to <a href="http://www.graphviz.org">Graphviz</a>.</p>
38 * <p>Typical usage of this class</p>
39 * <code>System.out.println(new DotFormatter().toDot(<i>node</i>));</code>
40 * <p>This class is <b>not</b> thread safe and should not be used without proper
41 * external synchronization.</p>
42 *
43 */
44 public class DotFormatter {
45 private static final String INDENT = " ";
46 private static final String ARROW = " -> ";
47 private static final String LINE = " -- ";
48
49 // stores the current assignment of node to keys
50 private HashMap<Node, Integer> assignments = new HashMap<Node, Integer>();
51
52 // key count in order to assign a unique key to each node
53 private int keyCount = 0;
54
55 // the builder used to generate the dot diagram
56 private Appendable builder;
57
58 private final ControlFlowGraph<Node> cfg;
59
60 private final boolean printAnnotations;
61
62 /** For Testing Only */
63 private DotFormatter() {
64 this.builder = new StringBuilder();
65 this.cfg = null;
66 this.printAnnotations = false;
67 }
68
69 private DotFormatter(Node n, ControlFlowGraph<Node> cfg,
70 Appendable builder, boolean printAnnotations) throws IOException {
71 this.cfg = cfg;
72 this.builder = builder;
73 this.printAnnotations = printAnnotations;
74
75 formatPreamble();
76 traverseNodes(n);
77 formatConclusion();
78 }
79
80 /**
81 * Converts an AST to dot representation.
82 * @param n the root of the AST described in the dot formatted string
83 * @return the dot representation of the AST
84 */
85 public static String toDot(Node n) throws IOException {
86 return toDot(n, null);
87 }
88
89 /**
90 * Converts an AST to dot representation.
91 * @param n the root of the AST described in the dot formatted string
92 * @param inCFG Control Flow Graph.
93 * @param printAnnotations print annotations.
94 * @return the dot representation of the AST
95 */
96 static String toDot(
97 Node n, ControlFlowGraph<Node> inCFG, boolean printAnnotations)
98 throws IOException {
99 StringBuilder builder = new StringBuilder();
100 new DotFormatter(n, inCFG, builder, printAnnotations);
101 return builder.toString();
102 }
103
104 /**
105 * Converts an AST to dot representation.
106 * @param n the root of the AST described in the dot formatted string
107 * @param inCFG Control Flow Graph.
108 * @return the dot representation of the AST
109 */
110 static String toDot(Node n, ControlFlowGraph<Node> inCFG)
111 throws IOException {
112 StringBuilder builder = new StringBuilder();
113 new DotFormatter(n, inCFG, builder, false);
114 return builder.toString();
115 }
116
117 /**
118 * Converts an AST to dot representation and appends it to the given buffer.
119 * @param n the root of the AST described in the dot formatted string
120 * @param inCFG Control Flow Graph.
121 * @param builder A place to dump the graph.
122 */
123 static void appendDot(Node n, ControlFlowGraph<Node> inCFG,
124 Appendable builder) throws IOException {
125 new DotFormatter(n, inCFG, builder, false);
126 }
127
128 /**
129 * Creates a DotFormatter purely for testing DotFormatter's internal methods.
130 */
131 static DotFormatter newInstanceForTesting() {
132 return new DotFormatter();
133 }
134
135 private void traverseNodes(Node parent) throws IOException {
136 // key
137 int keyParent = key(parent);
138
139 // edges
140 for (Node child = parent.getFirstChild(); child != null;
141 child = child.getNext()) {
142 int keyChild = key(child);
143 builder.append(INDENT);
144 builder.append(formatNodeName(keyParent));
145 builder.append(ARROW);
146 builder.append(formatNodeName(keyChild));
147 builder.append(" [weight=1];\n");
148
149 traverseNodes(child);
150 }
151
152 // Flow Edges
153 if (cfg != null && cfg.hasNode(parent)) {
154 List<DiGraphEdge<Node, Branch>> outEdges =
155 cfg.getOutEdges(parent);
156 String[] edgeList = new String[outEdges.size()];
157 for (int i = 0; i < edgeList.length; i++) {
158 DiGraphEdge<Node, ControlFlowGraph.Branch> edge = outEdges.get(i);
159 DiGraphNode<Node, Branch> succ = edge.getDestination();
160
161 String toNode = null;
162 if (succ == cfg.getImplicitReturn()) {
163 toNode = "RETURN";
164 } else {
165 int keySucc = key(succ.getValue());
166 toNode = formatNodeName(keySucc);
167 }
168
169 edgeList[i] = formatNodeName(keyParent) + ARROW + toNode + " [label=\""
170 + edge.getValue().toString() + "\", " + "fontcolor=\"red\", " +
171 "weight=0.01, color=\"red\"];\n";
172 }
173
174 Arrays.sort(edgeList);
175
176 for (int i = 0; i < edgeList.length; i++) {
177 builder.append(INDENT);
178 builder.append(edgeList[i]);
179 }
180 }
181 }
182
183 int key(Node n) throws IOException {
184 Integer key = assignments.get(n);
185 if (key == null) {
186 key = keyCount++;
187 assignments.put(n, key);
188 builder.append(INDENT);
189 builder.append(formatNodeName(key));
190 builder.append(" [label=\"");
191 builder.append(name(n));
192 JSType type = n.getJSType();
193 if (type != null) {
194 builder.append(" : ");
195 builder.append(type.toString());
196 }
197 if (printAnnotations && cfg != null && cfg.hasNode(n)) {
198 Object annotation = cfg.getNode(n).getAnnotation();
199 if (annotation != null) {
200 builder.append("\\n");
201 builder.append(annotation.toString());
202 }
203 }
204 builder.append("\"");
205 if (n.getJSDocInfo() != null) {
206 builder.append(" color=\"green\"");
207 }
208 builder.append("];\n");
209 }
210 return key;
211 }
212
213 private String name(Node n) {
214 int type = n.getType();
215 switch (type) {
216 case Token.VOID:
217 return "VOID";
218
219 default:
220 return Token.name(type);
221 }
222 }
223
224 private String formatNodeName(Integer key) {
225 return "node" + key;
226 }
227
228 private void formatPreamble() throws IOException {
229 builder.append("digraph AST {\n");
230 builder.append(INDENT);
231 builder.append("node [color=lightblue2, style=filled];\n");
232 }
233
234 private void formatConclusion() throws IOException {
235 builder.append("}\n");
236 }
237
238 /**
239 * Outputs a string in DOT format that presents the graph.
240 *
241 * @param graph Input graph.
242 * @return A string in Dot format that presents the graph.
243 */
244 public static String toDot(GraphvizGraph graph) {
245 StringBuilder builder = new StringBuilder ();
246 builder.append(graph.isDirected() ? "digraph" : "graph");
247 builder.append(INDENT);
248 builder.append(graph.getName());
249 builder.append(" {\n");
250 builder.append(INDENT);
251 builder.append("node [color=lightblue2, style=filled];\n");
252
253 final String edgeSymbol = graph.isDirected() ? ARROW : LINE;
254
255 List<GraphvizNode> nodes = graph.getGraphvizNodes();
256
257 String[] nodeNames = new String[nodes.size()];
258
259 for (int i = 0; i < nodeNames.length; i++) {
260 GraphvizNode gNode = nodes.get(i);
261 nodeNames[i] = gNode.getId() + " [label=\"" + gNode.getLabel() +
262 "\" color=\"" + gNode.getColor() + "\"]";
263 }
264
265 // We sort the nodes so we get a deterministic output every time regardless
266 // of the implementation of the graph data structure.
267 Arrays.sort(nodeNames);
268
269 for (String nodeName : nodeNames) {
270 builder.append(INDENT);
271 builder.append(nodeName);
272 builder.append(";\n");
273 }
274
275 List<GraphvizEdge> edges = graph.getGraphvizEdges();
276
277 String[] edgeNames = new String[edges.size()];
278
279 for (int i = 0; i < edgeNames.length; i++) {
280 GraphvizEdge edge = edges.get(i);
281 edgeNames[i] = edge.getNode1Id() + edgeSymbol + edge.getNode2Id();
282 }
283
284 // Again, we sort the edges as well.
285 Arrays.sort(edgeNames);
286
287 for (String edgeName : edgeNames) {
288 builder.append(INDENT);
289 builder.append(edgeName);
290 builder.append(";\n");
291 }
292
293 builder.append("}\n");
294 return builder.toString();
295 }
296 }