aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/ir/debug/ASTWriter.java
blob: 3c66aa12d0ed291e29b29ba1ed478c1cd5bcb5ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.ir.debug;

import java.lang.reflect.Field;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.TernaryNode;
import jdk.nashorn.internal.ir.annotations.Ignore;
import jdk.nashorn.internal.ir.annotations.ParentNode;
import jdk.nashorn.internal.ir.annotations.Reference;
import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.runtime.Context;

/**
 * AST-as-text visualizer. Sometimes you want tree form and not source
 * code. This works for both lowered and unlowered IR
 *
 * see the flags --print-ast and --print-ast-lower
 */

public final class ASTWriter {
    /** Root node from which to start the traversal */
    private final Node root;

    private static final int TABWIDTH = 4;

    /**
     * Constructor
     * @param root root of the AST to visualize
     */
    public ASTWriter(final Node root) {
        this.root = root;
    }

    /**
     * Use the ASTWriter by instantiating it and retrieving its String
     * representation
     *
     * @return the string representation of the AST
     */
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        printAST(sb, null, "root", root, 0);
        return sb.toString();
    }

    @SuppressWarnings("unchecked")
    private void printAST(final StringBuilder sb, final Field field, final String name, final Node node, final int indent) {
        ASTWriter.indent(sb, indent);
        if (node == null) {
            sb.append("[Object ");
            sb.append(name);
            sb.append(" null]\n");
            return;
        }

        final boolean isReference = field != null && field.getAnnotation(Reference.class) != null;

        Class<?> clazz = node.getClass();
        String   type  = clazz.getName();

        type = type.substring(type.lastIndexOf('.') + 1, type.length());
//        type += "@" + Debug.id(node) + "#" + node.getSymbol();

        final List<Field> children = new LinkedList<>();

        if (!isReference) {
            enqueueChildren(node, clazz, children);
        }

        String status = "";

        if (node.shouldDiscard()) {
            status += " Discard";
        }

        if (node.isTerminal()) {
            status += " Terminal";
        }

        if (node.hasGoto()) {
            status += " Goto ";
        }

        if (node.getSymbol() != null) {
            status += node.getSymbol();
        }

        status = status.trim();
        if (!"".equals(status)) {
            status = " [" + status + "]";
        }

        if (node.getSymbol() != null) {
            String tname = node.getType().toString();
            if (tname.indexOf('.') != -1) {
                tname = tname.substring(tname.lastIndexOf('.') + 1, tname.length());
            }
            status += " (" + tname + ")";
        }

        if (children.isEmpty()) {
            sb.append("[").
                append(type).
                append(' ').
                append(name).
                append(" = '").
                append(node).
                append("'").
                append(status).
                append("] ").
                append('\n');
        } else {
            sb.append("[").
                append(type).
                append(' ').
                append(name).
                append(' ').
                append(Token.toString(node.getToken())).
                append(status).
                append("]").
                append('\n');

            for (final Field child : children) {
                if (child.getAnnotation(ParentNode.class) != null) {
                    continue;
                } else if (child.getAnnotation(Ignore.class) != null) {
                    continue;
                }

                Object value;
                try {
                    value = child.get(node);
                } catch (final IllegalArgumentException | IllegalAccessException e) {
                    Context.printStackTrace(e);
                    return;
                }

                if (value instanceof Node) {
                    printAST(sb, child, child.getName(), (Node)value, indent + 1);
                } else if (value instanceof Collection) {
                    int pos = 0;
                    ASTWriter.indent(sb, indent + 1);
                    sb.append("[Collection ").
                        append(child.getName()).
                        append("[0..").
                        append(((Collection<Node>)value).size()).
                        append("]]").
                        append('\n');

                    for (final Node member : (Collection<Node>)value) {
                        printAST(sb, child, child.getName() + "[" + pos++ + "]", member, indent + 2);
                    }
                }
            }
        }
    }

    private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
        final Deque<Class<?>> stack = new ArrayDeque<>();

        /**
         * Here is some ugliness that can be overcome by proper ChildNode annotations
         * with proper orders. Right now we basically sort all classes up to Node
         * with super class first, as this often is the natural order, e.g. base
         * before index for an IndexNode.
         *
         * Also there are special cases as this is not true for UnaryNodes(lhs) and
         * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
         *
         * TODO - generalize traversal with an order built on annotations and this
         * will go away.
         */
        Class<?> clazz = nodeClass;
        do {
            stack.push(clazz);
            clazz = clazz.getSuperclass();
        } while (clazz != null);

        if (node instanceof TernaryNode) {
            // HACK juggle "third"
            stack.push(stack.removeLast());
        }
        // HACK change operator order for BinaryNodes to get lhs first.
        final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

        while (iter.hasNext()) {
            final Class<?> c = iter.next();
            for (final Field f : c.getDeclaredFields()) {
                try {
                    f.setAccessible(true);
                    final Object child = f.get(node);
                    if (child == null) {
                        continue;
                    }

                    if (child instanceof Node) {
                        children.add(f);
                    } else if (child instanceof Collection) {
                        if (!((Collection<?>)child).isEmpty()) {
                            children.add(f);
                        }
                    }
                } catch (final IllegalArgumentException | IllegalAccessException e) {
                    return;
                }
            }
        }
    }

    private static void indent(final StringBuilder sb, final int indent) {
        for (int i = 0; i < indent; i++) {
            for (int j = 0; j < TABWIDTH; j++) {
                sb.append(' ');
            }
        }
    }
}