Debian Codegraph @

rhino/src/org/mozilla/javascript/ast/AstNode.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.ast;
8
9 import org.mozilla.javascript.Kit;
10 import org.mozilla.javascript.Node;
11 import org.mozilla.javascript.Token;
12
13 import java.io.Serializable;
14 import java.util.Comparator;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18
19 /**
20 * Base class for AST node types. The goal of the AST is to represent the
21 * physical source code, to make it useful for code-processing tools such
22 * as IDEs or pretty-printers. The parser must not rewrite the parse tree
23 * when producing this representation. <p>
24 *
25 * The {@code AstNode} hierarchy sits atop the older {@link Node} class,
26 * which was designed for code generation. The {@code Node} class is a
27 * flexible, weakly-typed class suitable for creating and rewriting code
28 * trees, but using it requires you to remember the exact ordering of the
29 * child nodes, which are kept in a linked list. The {@code AstNode}
30 * hierarchy is a strongly-typed facade with named accessors for children
31 * and common properties, but under the hood it's still using a linked list
32 * of child nodes. It isn't a very good idea to use the child list directly
33 * unless you know exactly what you're doing.</p>
34 *
35 * Note that {@code AstNode} records additional information, including
36 * the node's position, length, and parent node. Also, some {@code AstNode}
37 * subclasses record some of their child nodes in instance members, since
38 * they are not needed for code generation. In a nutshell, only the code
39 * generator should be mixing and matching {@code AstNode} and {@code Node}
40 * objects.<p>
41 *
42 * All offset fields in all subclasses of AstNode are relative to their
43 * parent. For things like paren, bracket and keyword positions, the
44 * position is relative to the current node. The node start position is
45 * relative to the parent node. <p>
46 *
47 * During the actual parsing, node positions are absolute; adding the node to
48 * its parent fixes up the offsets to be relative. By the time you see the AST
49 * (e.g. using the {@code Visitor} interface), the offsets are relative. <p>
50 *
51 * {@code AstNode} objects have property lists accessible via the
52 * {@link #getProp} and {@link #putProp} methods. The property lists are
53 * integer-keyed with arbitrary {@code Object} values. For the most part the
54 * parser generating the AST avoids using properties, preferring fields for
55 * elements that are always set. Property lists are intended for user-defined
56 * annotations to the tree. The Rhino code generator acts as a client and
57 * uses node properties extensively. You are welcome to use the property-list
58 * API for anything your client needs.<p>
59 *
60 * This hierarchy does not have separate branches for expressions and
61 * statements, as the distinction in JavaScript is not as clear-cut as in
62 * Java or C++. <p>
63 */
64 public abstract class AstNode extends Node implements Comparable<AstNode> {
65
66 protected int position = -1;
67 protected int length = 1;
68 protected AstNode parent;
69
70 private static Map<Integer,String> operatorNames =
71 new HashMap<Integer,String>();
72
73 static {
74 operatorNames.put(Token.IN, "in");
75 operatorNames.put(Token.TYPEOF, "typeof");
76 operatorNames.put(Token.INSTANCEOF, "instanceof");
77 operatorNames.put(Token.DELPROP, "delete");
78 operatorNames.put(Token.COMMA, ",");
79 operatorNames.put(Token.COLON, ":");
80 operatorNames.put(Token.OR, "||");
81 operatorNames.put(Token.AND, "&&");
82 operatorNames.put(Token.INC, "++");
83 operatorNames.put(Token.DEC, "--");
84 operatorNames.put(Token.BITOR, "|");
85 operatorNames.put(Token.BITXOR, "^");
86 operatorNames.put(Token.BITAND, "&");
87 operatorNames.put(Token.EQ, "==");
88 operatorNames.put(Token.NE, "!=");
89 operatorNames.put(Token.LT, "<");
90 operatorNames.put(Token.GT, ">");
91 operatorNames.put(Token.LE, "<=");
92 operatorNames.put(Token.GE, ">=");
93 operatorNames.put(Token.LSH, "<<");
94 operatorNames.put(Token.RSH, ">>");
95 operatorNames.put(Token.URSH, ">>>");
96 operatorNames.put(Token.ADD, "+");
97 operatorNames.put(Token.SUB, "-");
98 operatorNames.put(Token.MUL, "*");
99 operatorNames.put(Token.DIV, "/");
100 operatorNames.put(Token.MOD, "%");
101 operatorNames.put(Token.NOT, "!");
102 operatorNames.put(Token.BITNOT, "~");
103 operatorNames.put(Token.POS, "+");
104 operatorNames.put(Token.NEG, "-");
105 operatorNames.put(Token.SHEQ, "===");
106 operatorNames.put(Token.SHNE, "!==");
107 operatorNames.put(Token.ASSIGN, "=");
108 operatorNames.put(Token.ASSIGN_BITOR, "|=");
109 operatorNames.put(Token.ASSIGN_BITAND, "&=");
110 operatorNames.put(Token.ASSIGN_LSH, "<<=");
111 operatorNames.put(Token.ASSIGN_RSH, ">>=");
112 operatorNames.put(Token.ASSIGN_URSH, ">>>=");
113 operatorNames.put(Token.ASSIGN_ADD, "+=");
114 operatorNames.put(Token.ASSIGN_SUB, "-=");
115 operatorNames.put(Token.ASSIGN_MUL, "*=");
116 operatorNames.put(Token.ASSIGN_DIV, "/=");
117 operatorNames.put(Token.ASSIGN_MOD, "%=");
118 operatorNames.put(Token.ASSIGN_BITXOR, "^=");
119 operatorNames.put(Token.VOID, "void");
120 }
121
122 public static class PositionComparator implements Comparator<AstNode>, Serializable {
123 private static final long serialVersionUID = 1L;
124
125 /**
126 * Sorts nodes by (relative) start position. The start positions are
127 * relative to their parent, so this comparator is only meaningful for
128 * comparing siblings.
129 */
130 public int compare(AstNode n1, AstNode n2) {
131 return n1.position - n2.position;
132 }
133 }
134
135 public AstNode() {
136 super(Token.ERROR);
137 }
138
139 /**
140 * Constructs a new AstNode
141 * @param pos the start position
142 */
143 public AstNode(int pos) {
144 this();
145 position = pos;
146 }
147
148 /**
149 * Constructs a new AstNode
150 * @param pos the start position
151 * @param len the number of characters spanned by the node in the source
152 * text
153 */
154 public AstNode(int pos, int len) {
155 this();
156 position = pos;
157 length = len;
158 }
159
160 /**
161 * Returns relative position in parent
162 */
163 public int getPosition() {
164 return position;
165 }
166
167 /**
168 * Sets relative position in parent
169 */
170 public void setPosition(int position) {
171 this.position = position;
172 }
173
174 /**
175 * Returns the absolute document position of the node.
176 * Computes it by adding the node's relative position
177 * to the relative positions of all its parents.
178 */
179 public int getAbsolutePosition() {
180 int pos = position;
181 AstNode parent = this.parent;
182 while (parent != null) {
183 pos += parent.getPosition();
184 parent = parent.getParent();
185 }
186 return pos;
187 }
188
189 /**
190 * Returns node length
191 */
192 public int getLength() {
193 return length;
194 }
195
196 /**
197 * Sets node length
198 */
199 public void setLength(int length) {
200 this.length = length;
201 }
202
203 /**
204 * Sets the node start and end positions.
205 * Computes the length as ({@code end} - {@code position}).
206 */
207 public void setBounds(int position, int end) {
208 setPosition(position);
209 setLength(end - position);
210 }
211
212 /**
213 * Make this node's position relative to a parent.
214 * Typically only used by the parser when constructing the node.
215 * @param parentPosition the absolute parent position; the
216 * current node position is assumed to be absolute and is
217 * decremented by parentPosition.
218 */
219 public void setRelative(int parentPosition) {
220 this.position -= parentPosition;
221 }
222
223 /**
224 * Returns the node parent, or {@code null} if it has none
225 */
226 public AstNode getParent() {
227 return parent;
228 }
229
230 /**
231 * Sets the node parent. This method automatically adjusts the
232 * current node's start position to be relative to the new parent.
233 * @param parent the new parent. Can be {@code null}.
234 */
235 public void setParent(AstNode parent) {
236 if (parent == this.parent) {
237 return;
238 }
239
240 // Convert position back to absolute.
241 if (this.parent != null) {
242 setRelative(-this.parent.getPosition());
243 }
244
245 this.parent = parent;
246 if (parent != null) {
247 setRelative(parent.getPosition());
248 }
249 }
250
251 /**
252 * Adds a child or function to the end of the block.
253 * Sets the parent of the child to this node, and fixes up
254 * the start position of the child to be relative to this node.
255 * Sets the length of this node to include the new child.
256 * @param kid the child
257 * @throws IllegalArgumentException if kid is {@code null}
258 */
259 public void addChild(AstNode kid) {
260 assertNotNull(kid);
261 int end = kid.getPosition() + kid.getLength();
262 setLength(end - this.getPosition());
263 addChildToBack(kid);
264 kid.setParent(this);
265 }
266
267 /**
268 * Returns the root of the tree containing this node.
269 * @return the {@link AstRoot} at the root of this node's parent
270 * chain, or {@code null} if the topmost parent is not an {@code AstRoot}.
271 */
272 public AstRoot getAstRoot() {
273 AstNode parent = this; // this node could be the AstRoot
274 while (parent != null && !(parent instanceof AstRoot)) {
275 parent = parent.getParent();
276 }
277 return (AstRoot)parent;
278 }
279
280 /**
281 * Emits source code for this node. Callee is responsible for calling this
282 * function recursively on children, incrementing indent as appropriate.<p>
283 *
284 * Note: if the parser was in error-recovery mode, some AST nodes may have
285 * {@code null} children that are expected to be non-{@code null}
286 * when no errors are present. In this situation, the behavior of the
287 * {@code toSource} method is undefined: {@code toSource}
288 * implementations may assume that the AST node is error-free, since it is
289 * intended to be invoked only at runtime after a successful parse.<p>
290 *
291 * @param depth the current recursion depth, typically beginning at 0
292 * when called on the root node.
293 */
294 public abstract String toSource(int depth);
295
296 /**
297 * Prints the source indented to depth 0.
298 */
299 public String toSource() {
300 return this.toSource(0);
301 }
302
303 /**
304 * Constructs an indentation string.
305 * @param indent the number of indentation steps
306 */
307 public String makeIndent(int indent) {
308 StringBuilder sb = new StringBuilder();
309 for (int i = 0; i < indent; i++) {
310 sb.append(" ");
311 }
312 return sb.toString();
313 }
314
315 /**
316 * Returns a short, descriptive name for the node, such as
317 * "ArrayComprehension".
318 */
319 public String shortName() {
320 String classname = getClass().getName();
321 int last = classname.lastIndexOf(".");
322 return classname.substring(last + 1);
323 }
324
325 /**
326 * Returns the string name for this operator.
327 * @param op the token type, e.g. {@link Token#ADD} or {@link Token#TYPEOF}
328 * @return the source operator string, such as "+" or "typeof"
329 */
330 public static String operatorToString(int op) {
331 String result = operatorNames.get(op);
332 if (result == null)
333 throw new IllegalArgumentException("Invalid operator: " + op);
334 return result;
335 }
336
337 /**
338 * Visits this node and its children in an arbitrary order. <p>
339 *
340 * It's up to each node subclass to decide the order for processing
341 * its children. The subclass also decides (and should document)
342 * which child nodes are not passed to the {@code NodeVisitor}.
343 * For instance, nodes representing keywords like {@code each} or
344 * {@code in} may not be passed to the visitor object. The visitor
345 * can simply query the current node for these children if desired.<p>
346 *
347 * Generally speaking, the order will be deterministic; the order is
348 * whatever order is decided by each child node. Normally child nodes
349 * will try to visit their children in lexical order, but there may
350 * be exceptions to this rule.<p>
351 *
352 * @param visitor the object to call with this node and its children
353 */
354 public abstract void visit(NodeVisitor visitor);
355
356 // subclasses with potential side effects should override this
357 @Override
358 public boolean hasSideEffects()
359 {
360 switch (getType()) {
361 case Token.ASSIGN:
362 case Token.ASSIGN_ADD:
363 case Token.ASSIGN_BITAND:
364 case Token.ASSIGN_BITOR:
365 case Token.ASSIGN_BITXOR:
366 case Token.ASSIGN_DIV:
367 case Token.ASSIGN_LSH:
368 case Token.ASSIGN_MOD:
369 case Token.ASSIGN_MUL:
370 case Token.ASSIGN_RSH:
371 case Token.ASSIGN_SUB:
372 case Token.ASSIGN_URSH:
373 case Token.BLOCK:
374 case Token.BREAK:
375 case Token.CALL:
376 case Token.CATCH:
377 case Token.CATCH_SCOPE:
378 case Token.CONST:
379 case Token.CONTINUE:
380 case Token.DEC:
381 case Token.DELPROP:
382 case Token.DEL_REF:
383 case Token.DO:
384 case Token.ELSE:
385 case Token.ENTERWITH:
386 case Token.ERROR: // Avoid cascaded error messages
387 case Token.EXPORT:
388 case Token.EXPR_RESULT:
389 case Token.FINALLY:
390 case Token.FUNCTION:
391 case Token.FOR:
392 case Token.GOTO:
393 case Token.IF:
394 case Token.IFEQ:
395 case Token.IFNE:
396 case Token.IMPORT:
397 case Token.INC:
398 case Token.JSR:
399 case Token.LABEL:
400 case Token.LEAVEWITH:
401 case Token.LET:
402 case Token.LETEXPR:
403 case Token.LOCAL_BLOCK:
404 case Token.LOOP:
405 case Token.NEW:
406 case Token.REF_CALL:
407 case Token.RETHROW:
408 case Token.RETURN:
409 case Token.RETURN_RESULT:
410 case Token.SEMI:
411 case Token.SETELEM:
412 case Token.SETELEM_OP:
413 case Token.SETNAME:
414 case Token.SETPROP:
415 case Token.SETPROP_OP:
416 case Token.SETVAR:
417 case Token.SET_REF:
418 case Token.SET_REF_OP:
419 case Token.SWITCH:
420 case Token.TARGET:
421 case Token.THROW:
422 case Token.TRY:
423 case Token.VAR:
424 case Token.WHILE:
425 case Token.WITH:
426 case Token.WITHEXPR:
427 case Token.YIELD:
428 return true;
429
430 default:
431 return false;
432 }
433 }
434
435 /**
436 * Bounces an IllegalArgumentException up if arg is {@code null}.
437 * @param arg any method argument
438 * @throws IllegalArgumentException if the argument is {@code null}
439 */
440 protected void assertNotNull(Object arg) {
441 if (arg == null)
442 throw new IllegalArgumentException("arg cannot be null");
443 }
444
445 /**
446 * Prints a comma-separated item list into a {@link StringBuilder}.
447 * @param items a list to print
448 * @param sb a {@link StringBuilder} into which to print
449 */
450 protected <T extends AstNode> void printList(List<T> items,
451 StringBuilder sb) {
452 int max = items.size();
453 int count = 0;
454 for (AstNode item : items) {
455 sb.append(item.toSource(0));
456 if (count++ < max-1) {
457 sb.append(", ");
458 } else if (item instanceof EmptyExpression) {
459 sb.append(",");
460 }
461 }
462 }
463
464 /**
465 * @see Kit#codeBug
466 */
467 public static RuntimeException codeBug()
468 throws RuntimeException
469 {
470 throw Kit.codeBug();
471 }
472
473 // TODO(stevey): think of a way to have polymorphic toString
474 // methods while keeping the ability to use Node.toString for
475 // dumping the IR with Token.printTrees. Most likely: change
476 // Node.toString to be Node.dumpTree and change callers to use that.
477 // For now, need original toString, to compare output to old Rhino's.
478
479 // @Override
480 // public String toString() {
481 // return this.getClass().getName() + ": " +
482 // Token.typeToName(getType());
483 // }
484
485 /**
486 * Returns the innermost enclosing function, or {@code null} if not in a
487 * function. Begins the search with this node's parent.
488 * @return the {@link FunctionNode} enclosing this node, else {@code null}
489 */
490 public FunctionNode getEnclosingFunction() {
491 AstNode parent = this.getParent();
492 while (parent != null && !(parent instanceof FunctionNode)) {
493 parent = parent.getParent();
494 }
495 return (FunctionNode)parent;
496 }
497
498 /**
499 * Returns the innermost enclosing {@link Scope} node, or {@code null}
500 * if we're not nested in a scope. Begins the search with this node's parent.
501 * Note that this is not the same as the defining scope for a {@link Name}.
502 *
503 * @return the {@link Scope} enclosing this node, else {@code null}
504 */
505 public Scope getEnclosingScope() {
506 AstNode parent = this.getParent();
507 while (parent != null && !(parent instanceof Scope)) {
508 parent = parent.getParent();
509 }
510 return (Scope)parent;
511 }
512
513 /**
514 * Permits AST nodes to be sorted based on start position and length.
515 * This makes it easy to sort Comment and Error nodes into a set of
516 * other AST nodes: just put them all into a {@link java.util.SortedSet},
517 * for instance.
518 * @param other another node
519 * @return -1 if this node's start position is less than {@code other}'s
520 * start position. If tied, -1 if this node's length is less than
521 * {@code other}'s length. If the lengths are equal, sorts abitrarily
522 * on hashcode unless the nodes are the same per {@link #equals}.
523 */
524 public int compareTo(AstNode other) {
525 if (this.equals(other)) return 0;
526 int abs1 = this.getAbsolutePosition();
527 int abs2 = other.getAbsolutePosition();
528 if (abs1 < abs2) return -1;
529 if (abs2 < abs1) return 1;
530 int len1 = this.getLength();
531 int len2 = other.getLength();
532 if (len1 < len2) return -1;
533 if (len2 < len1) return 1;
534 return this.hashCode() - other.hashCode();
535 }
536
537 /**
538 * Returns the depth of this node. The root is depth 0, its
539 * children are depth 1, and so on.
540 * @return the node depth in the tree
541 */
542 public int depth() {
543 return parent == null ? 0 : 1 + parent.depth();
544 }
545
546 protected static class DebugPrintVisitor implements NodeVisitor {
547 private StringBuilder buffer;
548 private static final int DEBUG_INDENT = 2;
549 public DebugPrintVisitor(StringBuilder buf) {
550 buffer = buf;
551 }
552 @Override
553 public String toString() {
554 return buffer.toString();
555 }
556 private String makeIndent(int depth) {
557 StringBuilder sb = new StringBuilder(DEBUG_INDENT * depth);
558 for (int i = 0; i < (DEBUG_INDENT * depth); i++) {
559 sb.append(" ");
560 }
561 return sb.toString();
562 }
563 public boolean visit(AstNode node) {
564 int tt = node.getType();
565 String name = Token.typeToName(tt);
566 buffer.append(node.getAbsolutePosition()).append("\t");
567 buffer.append(makeIndent(node.depth()));
568 buffer.append(name).append(" ");
569 buffer.append(node.getPosition()).append(" ");
570 buffer.append(node.getLength());
571 if (tt == Token.NAME) {
572 buffer.append(" ").append(((Name)node).getIdentifier());
573 }
574 buffer.append("\n");
575 return true; // process kids
576 }
577 }
578
579 /**
580 * Return the line number recorded for this node.
581 * If no line number was recorded, searches the parent chain.
582 * @return the nearest line number, or -1 if none was found
583 */
584 @Override
585 public int getLineno() {
586 if (lineno != -1)
587 return lineno;
588 if (parent != null)
589 return parent.getLineno();
590 return -1;
591 }
592
593 /**
594 * Returns a debugging representation of the parse tree
595 * starting at this node.
596 * @return a very verbose indented printout of the tree.
597 * The format of each line is: abs-pos name position length [identifier]
598 */
599 public String debugPrint() {
600 DebugPrintVisitor dpv = new DebugPrintVisitor(new StringBuilder(1000));
601 visit(dpv);
602 return dpv.toString();
603 }
604 }