Debian Codegraph @

src/com/google/javascript/rhino/Node.java

raw symbols SCIP
1 /*
2 *
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is Rhino code, released
17 * May 6, 1999.
18 *
19 * The Initial Developer of the Original Code is
20 * Netscape Communications Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 1997-1999
22 * the Initial Developer. All Rights Reserved.
23 *
24 * Contributor(s):
25 * Norris Boyd
26 * Roger Lawrence
27 * Mike McCabe
28 *
29 * Alternatively, the contents of this file may be used under the terms of
30 * the GNU General Public License Version 2 or later (the "GPL"), in which
31 * case the provisions of the GPL are applicable instead of those above. If
32 * you wish to allow use of your version of this file only under the terms of
33 * the GPL and not to allow others to use your version of this file under the
34 * MPL, indicate your decision by deleting the provisions above and replacing
35 * them with the notice and other provisions required by the GPL. If you do
36 * not delete the provisions above, a recipient may use your version of this
37 * file under either the MPL or the GPL.
38 *
39 * ***** END LICENSE BLOCK ***** */
40
41 package com.google.javascript.rhino;
42
43 import com.google.common.annotations.VisibleForTesting;
44 import com.google.common.base.Objects;
45 import com.google.common.base.Preconditions;
46 import com.google.javascript.rhino.jstype.JSType;
47 import com.google.javascript.rhino.jstype.SimpleSourceFile;
48 import com.google.javascript.rhino.jstype.StaticSourceFile;
49
50 import java.io.IOException;
51 import java.io.Serializable;
52 import java.util.Arrays;
53 import java.util.Collections;
54 import java.util.Iterator;
55 import java.util.NoSuchElementException;
56 import java.util.Set;
57
58 /**
59 * This class implements the root of the intermediate representation.
60 *
61 */
62
63 public class Node implements Cloneable, Serializable {
64
65 private static final long serialVersionUID = 1L;
66
67 public static final int
68 JSDOC_INFO_PROP = 29, // contains a TokenStream.JSDocInfo object
69 VAR_ARGS_NAME = 30, // the name node is a variable length
70 // argument placeholder.
71 INCRDECR_PROP = 32, // pre or post type of increment/decrement
72 QUOTED_PROP = 36, // set to indicate a quoted object lit key
73 OPT_ARG_NAME = 37, // The name node is an optional argument.
74 SYNTHETIC_BLOCK_PROP = 38, // A synthetic block. Used to make
75 // processing simpler, and does not
76 // represent a real block in the source.
77 EMPTY_BLOCK = 39, // Used to indicate BLOCK that replaced
78 // EMPTY nodes.
79 ORIGINALNAME_PROP = 40, // The original name of the node, before
80 // renaming.
81 SIDE_EFFECT_FLAGS = 42, // Function or constructor call side effect
82 // flags
83 // Coding convention props
84 IS_CONSTANT_NAME = 43, // The variable or property is constant.
85 IS_NAMESPACE = 46, // The variable creates a namespace.
86 IS_DISPATCHER = 47, // The function is a dispatcher function,
87 // probably generated from Java code, and
88 // should be resolved to the proper
89 // overload if possible.
90 DIRECTIVES = 48, // The ES5 directives on this node.
91 DIRECT_EVAL = 49, // ES5 distinguishes between direct and
92 // indirect calls to eval.
93 FREE_CALL = 50, // A CALL without an explicit "this" value.
94 STATIC_SOURCE_FILE = 51, // A StaticSourceFile indicating the file
95 // where this node lives.
96 LENGTH = 52, // The length of the code represented by
97 // this node.
98 INPUT_ID = 53, // The id of the input associated with this
99 // node.
100 SLASH_V = 54, // Whether a STRING node contains a \v
101 // vertical tab escape. This is a total hack.
102 // See comments in IRFactory about this.
103 INFERRED_FUNCTION = 55, // Marks a function whose parameter types
104 // have been inferred.
105 LAST_PROP = 55;
106
107 public static final int // flags for INCRDECR_PROP
108 DECR_FLAG = 0x1,
109 POST_FLAG = 0x2;
110
111 private static final String propToString(int propType) {
112 switch (propType) {
113 case VAR_ARGS_NAME: return "var_args_name";
114
115 case JSDOC_INFO_PROP: return "jsdoc_info";
116
117 case INCRDECR_PROP: return "incrdecr";
118 case QUOTED_PROP: return "quoted";
119 case OPT_ARG_NAME: return "opt_arg";
120
121 case SYNTHETIC_BLOCK_PROP: return "synthetic";
122 case EMPTY_BLOCK: return "empty_block";
123 case ORIGINALNAME_PROP: return "originalname";
124 case SIDE_EFFECT_FLAGS: return "side_effect_flags";
125
126 case IS_CONSTANT_NAME: return "is_constant_name";
127 case IS_NAMESPACE: return "is_namespace";
128 case IS_DISPATCHER: return "is_dispatcher";
129 case DIRECTIVES: return "directives";
130 case DIRECT_EVAL: return "direct_eval";
131 case FREE_CALL: return "free_call";
132 case STATIC_SOURCE_FILE: return "source_file";
133 case INPUT_ID: return "input_id";
134 case LENGTH: return "length";
135 case SLASH_V: return "slash_v";
136 case INFERRED_FUNCTION: return "inferred";
137 default:
138 throw new IllegalStateException("unexpect prop id " + propType);
139 }
140 }
141
142 private static class NumberNode extends Node {
143
144 private static final long serialVersionUID = 1L;
145
146 NumberNode(double number) {
147 super(Token.NUMBER);
148 this.number = number;
149 }
150
151 public NumberNode(double number, int lineno, int charno) {
152 super(Token.NUMBER, lineno, charno);
153 this.number = number;
154 }
155
156 @Override
157 public double getDouble() {
158 return this.number;
159 }
160
161 @Override
162 public void setDouble(double d) {
163 this.number = d;
164 }
165
166 @Override
167 boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) {
168 boolean equivalent = super.isEquivalentTo(node, compareJsType, recurse);
169 if (equivalent) {
170 double thisValue = getDouble();
171 double thatValue = ((NumberNode) node).getDouble();
172 if (thisValue == thatValue) {
173 // detect the difference between 0.0 and -0.0.
174 return (thisValue != 0.0) || (1/thisValue == 1/thatValue);
175 }
176 }
177 return false;
178 }
179
180 private double number;
181 }
182
183 private static class StringNode extends Node {
184
185 private static final long serialVersionUID = 1L;
186
187 StringNode(int type, String str) {
188 super(type);
189 if (null == str) {
190 throw new IllegalArgumentException("StringNode: str is null");
191 }
192 this.str = str;
193 }
194
195 StringNode(int type, String str, int lineno, int charno) {
196 super(type, lineno, charno);
197 if (null == str) {
198 throw new IllegalArgumentException("StringNode: str is null");
199 }
200 this.str = str;
201 }
202
203 /**
204 * returns the string content.
205 * @return non null.
206 */
207 @Override
208 public String getString() {
209 return this.str;
210 }
211
212 /**
213 * sets the string content.
214 * @param str the new value. Non null.
215 */
216 @Override
217 public void setString(String str) {
218 if (null == str) {
219 throw new IllegalArgumentException("StringNode: str is null");
220 }
221 this.str = str;
222 }
223
224 @Override
225 boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) {
226 return (super.isEquivalentTo(node, compareJsType, recurse)
227 && this.str.equals(((StringNode) node).str));
228 }
229
230 /**
231 * If the property is not defined, this was not a quoted key. The
232 * QUOTED_PROP int property is only assigned to STRING tokens used as
233 * object lit keys.
234 * @return true if this was a quoted string key in an object literal.
235 */
236 @Override
237 public boolean isQuotedString() {
238 return getBooleanProp(QUOTED_PROP);
239 }
240
241 /**
242 * This should only be called for STRING nodes created in object lits.
243 */
244 @Override
245 public void setQuotedString() {
246 putBooleanProp(QUOTED_PROP, true);
247 }
248
249 private String str;
250 }
251
252 // PropListItems must be immutable so that they can be shared.
253 private interface PropListItem {
254 int getType();
255 PropListItem getNext();
256 PropListItem chain(PropListItem next);
257 Object getObjectValue();
258 int getIntValue();
259 }
260
261 private static abstract class AbstractPropListItem
262 implements PropListItem, Serializable {
263 private static final long serialVersionUID = 1L;
264
265 private final PropListItem next;
266 private final int propType;
267
268 AbstractPropListItem(int propType, PropListItem next) {
269 this.propType = propType;
270 this.next = next;
271 }
272
273 @Override
274 public int getType() {
275 return propType;
276 }
277
278 @Override
279 public PropListItem getNext() {
280 return next;
281 }
282
283 @Override
284 public abstract PropListItem chain(PropListItem next);
285 }
286
287 // A base class for Object storing props
288 private static class ObjectPropListItem
289 extends AbstractPropListItem {
290 private static final long serialVersionUID = 1L;
291
292 private final Object objectValue;
293
294 ObjectPropListItem(int propType, Object objectValue, PropListItem next) {
295 super(propType, next);
296 this.objectValue = objectValue;
297 }
298
299 @Override
300 public int getIntValue() {
301 throw new UnsupportedOperationException();
302 }
303
304 @Override
305 public Object getObjectValue() {
306 return objectValue;
307 }
308
309 @Override
310 public String toString() {
311 return objectValue == null ? "null" : objectValue.toString();
312 }
313
314 @Override
315 public PropListItem chain(PropListItem next) {
316 return new ObjectPropListItem(getType(), objectValue, next);
317 }
318 }
319
320 // A base class for int storing props
321 private static class IntPropListItem extends AbstractPropListItem {
322 private static final long serialVersionUID = 1L;
323
324 final int intValue;
325
326 IntPropListItem(int propType, int intValue, PropListItem next) {
327 super(propType, next);
328 this.intValue = intValue;
329 }
330
331 @Override
332 public int getIntValue() {
333 return intValue;
334 }
335
336 @Override
337 public Object getObjectValue() {
338 throw new UnsupportedOperationException();
339 }
340
341 @Override
342 public String toString() {
343 return String.valueOf(intValue);
344 }
345
346 @Override
347 public PropListItem chain(PropListItem next) {
348 return new IntPropListItem(getType(), intValue, next);
349 }
350 }
351
352 public Node(int nodeType) {
353 type = nodeType;
354 parent = null;
355 sourcePosition = -1;
356 }
357
358 public Node(int nodeType, Node child) {
359 Preconditions.checkArgument(child.parent == null,
360 "new child has existing parent");
361 Preconditions.checkArgument(child.next == null,
362 "new child has existing sibling");
363
364 type = nodeType;
365 parent = null;
366 first = last = child;
367 child.next = null;
368 child.parent = this;
369 sourcePosition = -1;
370 }
371
372 public Node(int nodeType, Node left, Node right) {
373 Preconditions.checkArgument(left.parent == null,
374 "first new child has existing parent");
375 Preconditions.checkArgument(left.next == null,
376 "first new child has existing sibling");
377 Preconditions.checkArgument(right.parent == null,
378 "second new child has existing parent");
379 Preconditions.checkArgument(right.next == null,
380 "second new child has existing sibling");
381 type = nodeType;
382 parent = null;
383 first = left;
384 last = right;
385 left.next = right;
386 left.parent = this;
387 right.next = null;
388 right.parent = this;
389 sourcePosition = -1;
390 }
391
392 public Node(int nodeType, Node left, Node mid, Node right) {
393 Preconditions.checkArgument(left.parent == null);
394 Preconditions.checkArgument(left.next == null);
395 Preconditions.checkArgument(mid.parent == null);
396 Preconditions.checkArgument(mid.next == null);
397 Preconditions.checkArgument(right.parent == null);
398 Preconditions.checkArgument(right.next == null);
399 type = nodeType;
400 parent = null;
401 first = left;
402 last = right;
403 left.next = mid;
404 left.parent = this;
405 mid.next = right;
406 mid.parent = this;
407 right.next = null;
408 right.parent = this;
409 sourcePosition = -1;
410 }
411
412 public Node(int nodeType, Node left, Node mid, Node mid2, Node right) {
413 Preconditions.checkArgument(left.parent == null);
414 Preconditions.checkArgument(left.next == null);
415 Preconditions.checkArgument(mid.parent == null);
416 Preconditions.checkArgument(mid.next == null);
417 Preconditions.checkArgument(mid2.parent == null);
418 Preconditions.checkArgument(mid2.next == null);
419 Preconditions.checkArgument(right.parent == null);
420 Preconditions.checkArgument(right.next == null);
421 type = nodeType;
422 parent = null;
423 first = left;
424 last = right;
425 left.next = mid;
426 left.parent = this;
427 mid.next = mid2;
428 mid.parent = this;
429 mid2.next = right;
430 mid2.parent = this;
431 right.next = null;
432 right.parent = this;
433 sourcePosition = -1;
434 }
435
436 public Node(int nodeType, int lineno, int charno) {
437 type = nodeType;
438 parent = null;
439 sourcePosition = mergeLineCharNo(lineno, charno);
440 }
441
442 public Node(int nodeType, Node child, int lineno, int charno) {
443 this(nodeType, child);
444 sourcePosition = mergeLineCharNo(lineno, charno);
445 }
446
447 public Node(int nodeType, Node left, Node right, int lineno, int charno) {
448 this(nodeType, left, right);
449 sourcePosition = mergeLineCharNo(lineno, charno);
450 }
451
452 public Node(int nodeType, Node left, Node mid, Node right,
453 int lineno, int charno) {
454 this(nodeType, left, mid, right);
455 sourcePosition = mergeLineCharNo(lineno, charno);
456 }
457
458 public Node(int nodeType, Node left, Node mid, Node mid2, Node right,
459 int lineno, int charno) {
460 this(nodeType, left, mid, mid2, right);
461 sourcePosition = mergeLineCharNo(lineno, charno);
462 }
463
464 public Node(int nodeType, Node[] children, int lineno, int charno) {
465 this(nodeType, children);
466 sourcePosition = mergeLineCharNo(lineno, charno);
467 }
468
469 public Node(int nodeType, Node[] children) {
470 this.type = nodeType;
471 parent = null;
472 if (children.length != 0) {
473 this.first = children[0];
474 this.last = children[children.length - 1];
475
476 for (int i = 1; i < children.length; i++) {
477 if (null != children[i - 1].next) {
478 // fail early on loops. implies same node in array twice
479 throw new IllegalArgumentException("duplicate child");
480 }
481 children[i - 1].next = children[i];
482 Preconditions.checkArgument(children[i - 1].parent == null);
483 children[i - 1].parent = this;
484 }
485 Preconditions.checkArgument(children[children.length - 1].parent == null);
486 children[children.length - 1].parent = this;
487
488 if (null != this.last.next) {
489 // fail early on loops. implies same node in array twice
490 throw new IllegalArgumentException("duplicate child");
491 }
492 }
493 }
494
495 public static Node newNumber(double number) {
496 return new NumberNode(number);
497 }
498
499 public static Node newNumber(double number, int lineno, int charno) {
500 return new NumberNode(number, lineno, charno);
501 }
502
503 public static Node newString(String str) {
504 return new StringNode(Token.STRING, str);
505 }
506
507 public static Node newString(int type, String str) {
508 return new StringNode(type, str);
509 }
510
511 public static Node newString(String str, int lineno, int charno) {
512 return new StringNode(Token.STRING, str, lineno, charno);
513 }
514
515 public static Node newString(int type, String str, int lineno, int charno) {
516 return new StringNode(type, str, lineno, charno);
517 }
518
519 public int getType() {
520 return type;
521 }
522
523 public void setType(int type) {
524 this.type = type;
525 }
526
527 public boolean hasChildren() {
528 return first != null;
529 }
530
531 public Node getFirstChild() {
532 return first;
533 }
534
535 public Node getLastChild() {
536 return last;
537 }
538
539 public Node getNext() {
540 return next;
541 }
542
543 public Node getChildBefore(Node child) {
544 if (child == first) {
545 return null;
546 }
547 Node n = first;
548 while (n.next != child) {
549 n = n.next;
550 if (n == null) {
551 throw new RuntimeException("node is not a child");
552 }
553 }
554 return n;
555 }
556
557 public Node getChildAtIndex(int i) {
558 Node n = first;
559 while (i > 0) {
560 n = n.next;
561 i--;
562 }
563 return n;
564 }
565
566 public int getIndexOfChild(Node child) {
567 Node n = first;
568 int i = 0;
569 while (n != null) {
570 if (child == n) {
571 return i;
572 }
573
574 n = n.next;
575 i++;
576 }
577 return -1;
578 }
579
580 public Node getLastSibling() {
581 Node n = this;
582 while (n.next != null) {
583 n = n.next;
584 }
585 return n;
586 }
587
588 public void addChildToFront(Node child) {
589 Preconditions.checkArgument(child.parent == null);
590 Preconditions.checkArgument(child.next == null);
591 child.parent = this;
592 child.next = first;
593 first = child;
594 if (last == null) {
595 last = child;
596 }
597 }
598
599 public void addChildToBack(Node child) {
600 Preconditions.checkArgument(child.parent == null);
601 Preconditions.checkArgument(child.next == null);
602 child.parent = this;
603 child.next = null;
604 if (last == null) {
605 first = last = child;
606 return;
607 }
608 last.next = child;
609 last = child;
610 }
611
612 public void addChildrenToFront(Node children) {
613 for (Node child = children; child != null; child = child.next) {
614 Preconditions.checkArgument(child.parent == null);
615 child.parent = this;
616 }
617 Node lastSib = children.getLastSibling();
618 lastSib.next = first;
619 first = children;
620 if (last == null) {
621 last = lastSib;
622 }
623 }
624
625 public void addChildrenToBack(Node children) {
626 addChildrenAfter(children, getLastChild());
627 }
628
629 /**
630 * Add 'child' before 'node'.
631 */
632 public void addChildBefore(Node newChild, Node node) {
633 Preconditions.checkArgument(node != null && node.parent == this,
634 "The existing child node of the parent should not be null.");
635 Preconditions.checkArgument(newChild.next == null,
636 "The new child node has siblings.");
637 Preconditions.checkArgument(newChild.parent == null,
638 "The new child node already has a parent.");
639 if (first == node) {
640 newChild.parent = this;
641 newChild.next = first;
642 first = newChild;
643 return;
644 }
645 Node prev = getChildBefore(node);
646 addChildAfter(newChild, prev);
647 }
648
649 /**
650 * Add 'child' after 'node'.
651 */
652 public void addChildAfter(Node newChild, Node node) {
653 Preconditions.checkArgument(newChild.next == null,
654 "The new child node has siblings.");
655 addChildrenAfter(newChild, node);
656 }
657
658 /**
659 * Add all children after 'node'.
660 */
661 public void addChildrenAfter(Node children, Node node) {
662 Preconditions.checkArgument(node == null || node.parent == this);
663 for (Node child = children; child != null; child = child.next) {
664 Preconditions.checkArgument(child.parent == null);
665 child.parent = this;
666 }
667
668 Node lastSibling = children.getLastSibling();
669 if (node != null) {
670 Node oldNext = node.next;
671 node.next = children;
672 lastSibling.next = oldNext;
673 if (node == last) {
674 last = lastSibling;
675 }
676 } else {
677 // Append to the beginning.
678 if (first != null) {
679 lastSibling.next = first;
680 } else {
681 last = lastSibling;
682 }
683 first = children;
684 }
685 }
686
687 /**
688 * Detach a child from its parent and siblings.
689 */
690 public void removeChild(Node child) {
691 Node prev = getChildBefore(child);
692 if (prev == null)
693 first = first.next;
694 else
695 prev.next = child.next;
696 if (child == last) last = prev;
697 child.next = null;
698 child.parent = null;
699 }
700
701 /**
702 * Detaches child from Node and replaces it with newChild.
703 */
704 public void replaceChild(Node child, Node newChild) {
705 Preconditions.checkArgument(newChild.next == null,
706 "The new child node has siblings.");
707 Preconditions.checkArgument(newChild.parent == null,
708 "The new child node already has a parent.");
709
710 // Copy over important information.
711 newChild.copyInformationFrom(child);
712
713 newChild.next = child.next;
714 newChild.parent = this;
715 if (child == first) {
716 first = newChild;
717 } else {
718 Node prev = getChildBefore(child);
719 prev.next = newChild;
720 }
721 if (child == last)
722 last = newChild;
723 child.next = null;
724 child.parent = null;
725 }
726
727 public void replaceChildAfter(Node prevChild, Node newChild) {
728 Preconditions.checkArgument(prevChild.parent == this,
729 "prev is not a child of this node.");
730
731 Preconditions.checkArgument(newChild.next == null,
732 "The new child node has siblings.");
733 Preconditions.checkArgument(newChild.parent == null,
734 "The new child node already has a parent.");
735
736 // Copy over important information.
737 newChild.copyInformationFrom(prevChild);
738
739 Node child = prevChild.next;
740 newChild.next = child.next;
741 newChild.parent = this;
742 prevChild.next = newChild;
743 if (child == last)
744 last = newChild;
745 child.next = null;
746 child.parent = null;
747 }
748
749 @VisibleForTesting
750 PropListItem lookupProperty(int propType) {
751 PropListItem x = propListHead;
752 while (x != null && propType != x.getType()) {
753 x = x.getNext();
754 }
755 return x;
756 }
757
758 /**
759 * Clone the properties from the provided node without copying
760 * the property object. The receiving node may not have any
761 * existing properties.
762 * @param other The node to clone properties from.
763 * @return this node.
764 */
765 public Node clonePropsFrom(Node other) {
766 Preconditions.checkState(this.propListHead == null,
767 "Node has existing properties.");
768 this.propListHead = other.propListHead;
769 return this;
770 }
771
772 public void removeProp(int propType) {
773 PropListItem result = removeProp(propListHead, propType);
774 if (result != propListHead) {
775 propListHead = result;
776 }
777 }
778
779 /**
780 * @param item The item to inspect
781 * @param propType The property to look for
782 * @return The replacement list if the property was removed, or
783 * 'item' otherwise.
784 */
785 private PropListItem removeProp(PropListItem item, int propType) {
786 if (item == null) {
787 return null;
788 } else if (item.getType() == propType) {
789 return item.getNext();
790 } else {
791 PropListItem result = removeProp(item.getNext(), propType);
792 if (result != item.getNext()) {
793 return item.chain(result);
794 } else {
795 return item;
796 }
797 }
798 }
799
800 public Object getProp(int propType) {
801 PropListItem item = lookupProperty(propType);
802 if (item == null) {
803 return null;
804 }
805 return item.getObjectValue();
806 }
807
808 public boolean getBooleanProp(int propType) {
809 return getIntProp(propType) != 0;
810 }
811
812 /**
813 * Returns the integer value for the property, or 0 if the property
814 * is not defined.
815 */
816 public int getIntProp(int propType) {
817 PropListItem item = lookupProperty(propType);
818 if (item == null) {
819 return 0;
820 }
821 return item.getIntValue();
822 }
823
824 public int getExistingIntProp(int propType) {
825 PropListItem item = lookupProperty(propType);
826 if (item == null) {
827 throw new IllegalStateException("missing prop: " + propType);
828 }
829 return item.getIntValue();
830 }
831
832 public void putProp(int propType, Object value) {
833 removeProp(propType);
834 if (value != null) {
835 propListHead = createProp(propType, value, propListHead);
836 }
837 }
838
839 public void putBooleanProp(int propType, boolean value) {
840 putIntProp(propType, value ? 1 : 0);
841 }
842
843 public void putIntProp(int propType, int value) {
844 removeProp(propType);
845 if (value != 0) {
846 propListHead = createProp(propType, value, propListHead);
847 }
848 }
849
850 PropListItem createProp(int propType, Object value, PropListItem next) {
851 return new ObjectPropListItem(propType, value, next);
852 }
853
854 PropListItem createProp(int propType, int value, PropListItem next) {
855 return new IntPropListItem(propType, value, next);
856 }
857
858 // Gets all the property types, in sorted order.
859 private int[] getSortedPropTypes() {
860 int count = 0;
861 for (PropListItem x = propListHead; x != null; x = x.getNext()) {
862 count++;
863 }
864
865 int[] keys = new int[count];
866 for (PropListItem x = propListHead; x != null; x = x.getNext()) {
867 count--;
868 keys[count] = x.getType();
869 }
870
871 Arrays.sort(keys);
872 return keys;
873 }
874
875 /** Can only be called when <tt>getType() == TokenStream.NUMBER</tt> */
876 public double getDouble() throws UnsupportedOperationException {
877 if (this.getType() == Token.NUMBER) {
878 throw new IllegalStateException(
879 "Number node not created with Node.newNumber");
880 } else {
881 throw new UnsupportedOperationException(this + " is not a number node");
882 }
883 }
884
885 /**
886 * Can only be called when <tt>getType() == Token.NUMBER</tt>
887 * @param value value to set.
888 */
889 public void setDouble(double value) throws UnsupportedOperationException {
890 if (this.getType() == Token.NUMBER) {
891 throw new IllegalStateException(
892 "Number node not created with Node.newNumber");
893 } else {
894 throw new UnsupportedOperationException(this + " is not a string node");
895 }
896 }
897
898 /** Can only be called when node has String context. */
899 public String getString() throws UnsupportedOperationException {
900 if (this.getType() == Token.STRING) {
901 throw new IllegalStateException(
902 "String node not created with Node.newString");
903 } else {
904 throw new UnsupportedOperationException(this + " is not a string node");
905 }
906 }
907
908 /**
909 * Can only be called for a Token.STRING or Token.NAME.
910 * @param value the value to set.
911 */
912 public void setString(String value) throws UnsupportedOperationException {
913 if (this.getType() == Token.STRING || this.getType() == Token.NAME) {
914 throw new IllegalStateException(
915 "String node not created with Node.newString");
916 } else {
917 throw new UnsupportedOperationException(this + " is not a string node");
918 }
919 }
920
921 @Override
922 public String toString() {
923 return toString(true, true, true);
924 }
925
926 public String toString(
927 boolean printSource,
928 boolean printAnnotations,
929 boolean printType) {
930 StringBuilder sb = new StringBuilder();
931 toString(sb, printSource, printAnnotations, printType);
932 return sb.toString();
933 }
934
935 private void toString(
936 StringBuilder sb,
937 boolean printSource,
938 boolean printAnnotations,
939 boolean printType) {
940 sb.append(Token.name(type));
941 if (this instanceof StringNode) {
942 sb.append(' ');
943 sb.append(getString());
944 } else if (type == Token.FUNCTION) {
945 sb.append(' ');
946 // In the case of JsDoc trees, the first child is often not a string
947 // which causes exceptions to be thrown when calling toString or
948 // toStringTree.
949 if (first == null || first.getType() != Token.NAME) {
950 sb.append("<invalid>");
951 } else {
952 sb.append(first.getString());
953 }
954 } else if (type == Token.NUMBER) {
955 sb.append(' ');
956 sb.append(getDouble());
957 }
958 if (printSource) {
959 int lineno = getLineno();
960 if (lineno != -1) {
961 sb.append(' ');
962 sb.append(lineno);
963 }
964 }
965
966 if (printAnnotations) {
967 int[] keys = getSortedPropTypes();
968 for (int i = 0; i < keys.length; i++) {
969 int type = keys[i];
970 PropListItem x = lookupProperty(type);
971 sb.append(" [");
972 sb.append(propToString(type));
973 sb.append(": ");
974 String value;
975 switch (type) {
976 default:
977 value = x.toString();
978 break;
979 }
980 sb.append(value);
981 sb.append(']');
982 }
983 }
984
985 if (printType) {
986 if (jsType != null) {
987 String jsTypeString = jsType.toString();
988 if (jsTypeString != null) {
989 sb.append(" : ");
990 sb.append(jsTypeString);
991 }
992 }
993 }
994 }
995
996
997 public String toStringTree() {
998 return toStringTreeImpl();
999 }
1000
1001 private String toStringTreeImpl() {
1002 try {
1003 StringBuilder s = new StringBuilder();
1004 appendStringTree(s);
1005 return s.toString();
1006 } catch (IOException e) {
1007 throw new RuntimeException("Should not happen\n" + e);
1008 }
1009 }
1010
1011 public void appendStringTree(Appendable appendable) throws IOException {
1012 toStringTreeHelper(this, 0, appendable);
1013 }
1014
1015 private static void toStringTreeHelper(Node n, int level, Appendable sb)
1016 throws IOException {
1017 for (int i = 0; i != level; ++i) {
1018 sb.append(" ");
1019 }
1020 sb.append(n.toString());
1021 sb.append('\n');
1022 for (Node cursor = n.getFirstChild();
1023 cursor != null;
1024 cursor = cursor.getNext()) {
1025 toStringTreeHelper(cursor, level + 1, sb);
1026 }
1027 }
1028
1029 int type; // type of the node; Token.NAME for example
1030 Node next; // next sibling
1031 private Node first; // first element of a linked list of children
1032 private Node last; // last element of a linked list of children
1033
1034 /**
1035 * Linked list of properties. Since vast majority of nodes would have
1036 * no more then 2 properties, linked list saves memory and provides
1037 * fast lookup. If this does not holds, propListHead can be replaced
1038 * by UintMap.
1039 */
1040 private PropListItem propListHead;
1041
1042 /**
1043 * COLUMN_BITS represents how many of the lower-order bits of
1044 * sourcePosition are reserved for storing the column number.
1045 * Bits above these store the line number.
1046 * This gives us decent position information for everything except
1047 * files already passed through a minimizer, where lines might
1048 * be longer than 4096 characters.
1049 */
1050 public static final int COLUMN_BITS = 12;
1051
1052 /**
1053 * MAX_COLUMN_NUMBER represents the maximum column number that can
1054 * be represented. JSCompiler's modifications to Rhino cause all
1055 * tokens located beyond the maximum column to MAX_COLUMN_NUMBER.
1056 */
1057 public static final int MAX_COLUMN_NUMBER = (1 << COLUMN_BITS) - 1;
1058
1059 /**
1060 * COLUMN_MASK stores a value where bits storing the column number
1061 * are set, and bits storing the line are not set. It's handy for
1062 * separating column number from line number.
1063 */
1064 public static final int COLUMN_MASK = MAX_COLUMN_NUMBER;
1065
1066 /**
1067 * Source position of this node. The position is encoded with the
1068 * column number in the low 12 bits of the integer, and the line
1069 * number in the rest. Create some handy constants so we can change this
1070 * size if we want.
1071 */
1072 private int sourcePosition;
1073
1074 private JSType jsType;
1075
1076 private Node parent;
1077
1078 //==========================================================================
1079 // Source position management
1080
1081 public void setStaticSourceFile(StaticSourceFile file) {
1082 this.putProp(STATIC_SOURCE_FILE, file);
1083 }
1084
1085 /** Sets the source file to a non-extern file of the given name. */
1086 public void setSourceFileForTesting(String name) {
1087 this.putProp(STATIC_SOURCE_FILE, new SimpleSourceFile(name, false));
1088 }
1089
1090 public String getSourceFileName() {
1091 StaticSourceFile file = getStaticSourceFile();
1092 return file == null ? null : file.getName();
1093 }
1094
1095 /** Returns the source file associated with this input. May be null */
1096 public StaticSourceFile getStaticSourceFile() {
1097 return ((StaticSourceFile) this.getProp(STATIC_SOURCE_FILE));
1098 }
1099
1100 /**
1101 * @param inputId
1102 */
1103 public void setInputId(InputId inputId) {
1104 this.putProp(INPUT_ID, inputId);
1105 }
1106
1107 /**
1108 * @return The Id of the CompilerInput associated with this Node.
1109 */
1110 public InputId getInputId() {
1111 return ((InputId) this.getProp(INPUT_ID));
1112 }
1113
1114 public boolean isFromExterns() {
1115 StaticSourceFile file = getStaticSourceFile();
1116 return file == null ? false : file.isExtern();
1117 }
1118
1119 public int getLength() {
1120 return getIntProp(LENGTH);
1121 }
1122
1123 public void setLength(int length) {
1124 putIntProp(LENGTH, length);
1125 }
1126
1127 public int getLineno() {
1128 return extractLineno(sourcePosition);
1129 }
1130
1131 public int getCharno() {
1132 return extractCharno(sourcePosition);
1133 }
1134
1135 public int getSourceOffset() {
1136 StaticSourceFile file = getStaticSourceFile();
1137 if (file == null) {
1138 return -1;
1139 }
1140 int lineno = getLineno();
1141 if (lineno == -1) {
1142 return -1;
1143 }
1144 return file.getLineOffset(lineno) + getCharno();
1145 }
1146
1147 public int getSourcePosition() {
1148 return sourcePosition;
1149 }
1150
1151 public void setLineno(int lineno) {
1152 int charno = getCharno();
1153 if (charno == -1) {
1154 charno = 0;
1155 }
1156 sourcePosition = mergeLineCharNo(lineno, charno);
1157 }
1158
1159 public void setCharno(int charno) {
1160 sourcePosition = mergeLineCharNo(getLineno(), charno);
1161 }
1162
1163 public void setSourceEncodedPosition(int sourcePosition) {
1164 this.sourcePosition = sourcePosition;
1165 }
1166
1167 public void setSourceEncodedPositionForTree(int sourcePosition) {
1168 this.sourcePosition = sourcePosition;
1169
1170 for (Node child = getFirstChild();
1171 child != null; child = child.getNext()) {
1172 child.setSourceEncodedPositionForTree(sourcePosition);
1173 }
1174 }
1175
1176 /**
1177 * Merges the line number and character number in one integer. The Character
1178 * number takes the first 12 bits and the line number takes the rest. If
1179 * the character number is greater than <code>2<sup>12</sup>-1</code> it is
1180 * adjusted to <code>2<sup>12</sup>-1</code>.
1181 */
1182 protected static int mergeLineCharNo(int lineno, int charno) {
1183 if (lineno < 0 || charno < 0) {
1184 return -1;
1185 } else if ((charno & ~COLUMN_MASK) != 0) {
1186 return lineno << COLUMN_BITS | COLUMN_MASK;
1187 } else {
1188 return lineno << COLUMN_BITS | (charno & COLUMN_MASK);
1189 }
1190 }
1191
1192 /**
1193 * Extracts the line number and character number from a merged line char
1194 * number (see {@link #mergeLineCharNo(int, int)}).
1195 */
1196 protected static int extractLineno(int lineCharNo) {
1197 if (lineCharNo == -1) {
1198 return -1;
1199 } else {
1200 return lineCharNo >>> COLUMN_BITS;
1201 }
1202 }
1203
1204 /**
1205 * Extracts the character number and character number from a merged line
1206 * char number (see {@link #mergeLineCharNo(int, int)}).
1207 */
1208 protected static int extractCharno(int lineCharNo) {
1209 if (lineCharNo == -1) {
1210 return -1;
1211 } else {
1212 return lineCharNo & COLUMN_MASK;
1213 }
1214 }
1215
1216 //==========================================================================
1217 // Iteration
1218
1219 /**
1220 * <p>Return an iterable object that iterates over this node's children.
1221 * The iterator does not support the optional operation
1222 * {@link Iterator#remove()}.</p>
1223 *
1224 * <p>To iterate over a node's siblings, one can write</p>
1225 * <pre>Node n = ...;
1226 * for (Node child : n.children()) { ...</pre>
1227 */
1228 public Iterable<Node> children() {
1229 if (first == null) {
1230 return Collections.emptySet();
1231 } else {
1232 return new SiblingNodeIterable(first);
1233 }
1234 }
1235
1236 /**
1237 * <p>Return an iterable object that iterates over this node's siblings.
1238 * The iterator does not support the optional operation
1239 * {@link Iterator#remove()}.</p>
1240 *
1241 * <p>To iterate over a node's siblings, one can write</p>
1242 * <pre>Node n = ...;
1243 * for (Node sibling : n.siblings()) { ...</pre>
1244 */
1245 public Iterable<Node> siblings() {
1246 return new SiblingNodeIterable(this);
1247 }
1248
1249 /**
1250 * @see Node#siblings()
1251 */
1252 private static final class SiblingNodeIterable
1253 implements Iterable<Node>, Iterator<Node> {
1254 private final Node start;
1255 private Node current;
1256 private boolean used;
1257
1258 SiblingNodeIterable(Node start) {
1259 this.start = start;
1260 this.current = start;
1261 this.used = false;
1262 }
1263
1264 @Override
1265 public Iterator<Node> iterator() {
1266 if (!used) {
1267 used = true;
1268 return this;
1269 } else {
1270 // We have already used the current object as an iterator;
1271 // we must create a new SiblingNodeIterable based on this
1272 // iterable's start node.
1273 //
1274 // Since the primary use case for Node.children is in for
1275 // loops, this branch is extremely unlikely.
1276 return (new SiblingNodeIterable(start)).iterator();
1277 }
1278 }
1279
1280 @Override
1281 public boolean hasNext() {
1282 return current != null;
1283 }
1284
1285 @Override
1286 public Node next() {
1287 if (current == null) {
1288 throw new NoSuchElementException();
1289 }
1290 try {
1291 return current;
1292 } finally {
1293 current = current.getNext();
1294 }
1295 }
1296
1297 @Override
1298 public void remove() {
1299 throw new UnsupportedOperationException();
1300 }
1301 }
1302
1303 // ==========================================================================
1304 // Accessors
1305
1306 PropListItem getPropListHeadForTesting() {
1307 return propListHead;
1308 }
1309
1310 public Node getParent() {
1311 return parent;
1312 }
1313
1314 /**
1315 * Gets the ancestor node relative to this.
1316 *
1317 * @param level 0 = this, 1 = the parent, etc.
1318 */
1319 public Node getAncestor(int level) {
1320 Preconditions.checkArgument(level >= 0);
1321 Node node = this;
1322 while (node != null && level-- > 0) {
1323 node = node.getParent();
1324 }
1325 return node;
1326 }
1327
1328 /**
1329 * Iterates all of the node's ancestors excluding itself.
1330 */
1331 public AncestorIterable getAncestors() {
1332 return new AncestorIterable(this.getParent());
1333 }
1334
1335 /**
1336 * Iterator to go up the ancestor tree.
1337 */
1338 public static class AncestorIterable implements Iterable<Node> {
1339 private Node cur;
1340
1341 /**
1342 * @param cur The node to start.
1343 */
1344 AncestorIterable(Node cur) {
1345 this.cur = cur;
1346 }
1347
1348 @Override
1349 public Iterator<Node> iterator() {
1350 return new Iterator<Node>() {
1351 @Override
1352 public boolean hasNext() {
1353 return cur != null;
1354 }
1355
1356 @Override
1357 public Node next() {
1358 if (!hasNext()) throw new NoSuchElementException();
1359 Node n = cur;
1360 cur = cur.getParent();
1361 return n;
1362 }
1363
1364 @Override
1365 public void remove() {
1366 throw new UnsupportedOperationException();
1367 }
1368 };
1369 }
1370 }
1371
1372 /**
1373 * Check for one child more efficiently than by iterating over all the
1374 * children as is done with Node.getChildCount().
1375 *
1376 * @return Whether the node has exactly one child.
1377 */
1378 public boolean hasOneChild() {
1379 return first != null && first == last;
1380 }
1381
1382 /**
1383 * Check for more than one child more efficiently than by iterating over all
1384 * the children as is done with Node.getChildCount().
1385 *
1386 * @return Whether the node more than one child.
1387 */
1388 public boolean hasMoreThanOneChild() {
1389 return first != null && first != last;
1390 }
1391
1392 public int getChildCount() {
1393 int c = 0;
1394 for (Node n = first; n != null; n = n.next)
1395 c++;
1396
1397 return c;
1398 }
1399
1400 // Intended for testing and verification only.
1401 public boolean hasChild(Node child) {
1402 for (Node n = first; n != null; n = n.getNext()) {
1403 if (child == n) {
1404 return true;
1405 }
1406 }
1407 return false;
1408 }
1409
1410 /**
1411 * Checks if the subtree under this node is the same as another subtree.
1412 * Returns null if it's equal, or a message describing the differences.
1413 */
1414 public String checkTreeEquals(Node node2) {
1415 NodeMismatch diff = checkTreeEqualsImpl(node2);
1416 if (diff != null) {
1417 return "Node tree inequality:" +
1418 "\nTree1:\n" + toStringTree() +
1419 "\n\nTree2:\n" + node2.toStringTree() +
1420 "\n\nSubtree1: " + diff.nodeA.toStringTree() +
1421 "\n\nSubtree2: " + diff.nodeB.toStringTree();
1422 }
1423 return null;
1424 }
1425
1426 /**
1427 * Compare this node to node2 recursively and return the first pair of nodes
1428 * that differs doing a preorder depth-first traversal. Package private for
1429 * testing. Returns null if the nodes are equivalent.
1430 */
1431 NodeMismatch checkTreeEqualsImpl(Node node2) {
1432 if (!isEquivalentTo(node2, false, false)) {
1433 return new NodeMismatch(this, node2);
1434 }
1435
1436 NodeMismatch res = null;
1437 Node n, n2;
1438 for (n = first, n2 = node2.first;
1439 res == null && n != null;
1440 n = n.next, n2 = n2.next) {
1441 if (node2 == null) {
1442 throw new IllegalStateException();
1443 }
1444 res = n.checkTreeEqualsImpl(n2);
1445 if (res != null) {
1446 return res;
1447 }
1448 }
1449 return res;
1450 }
1451
1452 /**
1453 * Compare this node to node2 recursively and return the first pair of nodes
1454 * that differs doing a preorder depth-first traversal. Package private for
1455 * testing. Returns null if the nodes are equivalent.
1456 */
1457 NodeMismatch checkTreeTypeAwareEqualsImpl(Node node2) {
1458 // Do a non-recursive equivalents check.
1459 if (!isEquivalentTo(node2, true, false)) {
1460 return new NodeMismatch(this, node2);
1461 }
1462
1463 NodeMismatch res = null;
1464 Node n, n2;
1465 for (n = first, n2 = node2.first;
1466 res == null && n != null;
1467 n = n.next, n2 = n2.next) {
1468 res = n.checkTreeTypeAwareEqualsImpl(n2);
1469 if (res != null) {
1470 return res;
1471 }
1472 }
1473 return res;
1474 }
1475
1476 /** Returns true if this node is equivalent semantically to another */
1477 public boolean isEquivalentTo(Node node) {
1478 return isEquivalentTo(node, false, true);
1479 }
1480
1481 /**
1482 * Returns true if this node is equivalent semantically to another and
1483 * the types are equivalent.
1484 */
1485 public boolean isEquivalentToTyped(Node node) {
1486 return isEquivalentTo(node, true, true);
1487 }
1488
1489 /**
1490 * @param compareJsType Whether to compare the JSTypes of the nodes.
1491 * @param recurse Whether to compare the children of the current node, if
1492 * not only the the count of the children are compared.
1493 * @return Whether this node is equivalent semantically to the provided node.
1494 */
1495 boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) {
1496 if (type != node.getType()
1497 || getChildCount() != node.getChildCount()
1498 || this.getClass() != node.getClass()) {
1499 return false;
1500 }
1501
1502 if (compareJsType && !JSType.isEquivalent(jsType, node.getJSType())) {
1503 return false;
1504 }
1505
1506 if (type == Token.INC || type == Token.DEC) {
1507 int post1 = this.getIntProp(INCRDECR_PROP);
1508 int post2 = node.getIntProp(INCRDECR_PROP);
1509 if (post1 != post2) {
1510 return false;
1511 }
1512 } else if (type == Token.STRING || type == Token.STRING_KEY) {
1513 if (type == Token.STRING_KEY) {
1514 int quoted1 = this.getIntProp(QUOTED_PROP);
1515 int quoted2 = node.getIntProp(QUOTED_PROP);
1516 if (quoted1 != quoted2) {
1517 return false;
1518 }
1519 }
1520
1521 int slashV1 = this.getIntProp(SLASH_V);
1522 int slashV2 = node.getIntProp(SLASH_V);
1523 if (slashV1 != slashV2) {
1524 return false;
1525 }
1526 } else if (type == Token.CALL) {
1527 if (this.getBooleanProp(FREE_CALL) != node.getBooleanProp(FREE_CALL)) {
1528 return false;
1529 }
1530 }
1531
1532 if (recurse) {
1533 Node n, n2;
1534 for (n = first, n2 = node.first;
1535 n != null;
1536 n = n.next, n2 = n2.next) {
1537 if (!n.isEquivalentTo(n2, compareJsType, true)) {
1538 return false;
1539 }
1540 }
1541 }
1542
1543 return true;
1544 }
1545
1546 /**
1547 * This function takes a set of GETPROP nodes and produces a string that is
1548 * each property separated by dots. If the node ultimately under the left
1549 * sub-tree is not a simple name, this is not a valid qualified name.
1550 *
1551 * @return a null if this is not a qualified name, or a dot-separated string
1552 * of the name and properties.
1553 */
1554 public String getQualifiedName() {
1555 if (type == Token.NAME) {
1556 String name = getString();
1557 return name.isEmpty() ? null : name;
1558 } else if (type == Token.GETPROP) {
1559 String left = getFirstChild().getQualifiedName();
1560 if (left == null) {
1561 return null;
1562 }
1563 return left + "." + getLastChild().getString();
1564 } else if (type == Token.THIS) {
1565 return "this";
1566 } else {
1567 return null;
1568 }
1569 }
1570
1571 /**
1572 * Returns whether a node corresponds to a simple or a qualified name, such as
1573 * <code>x</code> or <code>a.b.c</code> or <code>this.a</code>.
1574 */
1575 public boolean isQualifiedName() {
1576 switch (getType()) {
1577 case Token.NAME:
1578 return getString().isEmpty() ? false : true;
1579 case Token.THIS:
1580 return true;
1581 case Token.GETPROP:
1582 return getFirstChild().isQualifiedName();
1583 default:
1584 return false;
1585 }
1586 }
1587
1588 /**
1589 * Returns whether a node corresponds to a simple or a qualified name without
1590 * a "this" reference, such as <code>a.b.c</code>, but not <code>this.a</code>
1591 * .
1592 */
1593 public boolean isUnscopedQualifiedName() {
1594 switch (getType()) {
1595 case Token.NAME:
1596 return getString().isEmpty() ? false : true;
1597 case Token.GETPROP:
1598 return getFirstChild().isUnscopedQualifiedName();
1599 default:
1600 return false;
1601 }
1602 }
1603
1604 // ==========================================================================
1605 // Mutators
1606
1607 /**
1608 * Removes this node from its parent. Equivalent to:
1609 * node.getParent().removeChild();
1610 */
1611 public Node detachFromParent() {
1612 Preconditions.checkState(parent != null);
1613 parent.removeChild(this);
1614 return this;
1615 }
1616
1617 /**
1618 * Removes the first child of Node. Equivalent to:
1619 * node.removeChild(node.getFirstChild());
1620 *
1621 * @return The removed Node.
1622 */
1623 public Node removeFirstChild() {
1624 Node child = first;
1625 if (child != null) {
1626 removeChild(child);
1627 }
1628 return child;
1629 }
1630
1631 /**
1632 * @return A Node that is the head of the list of children.
1633 */
1634 public Node removeChildren() {
1635 Node children = first;
1636 for (Node child = first; child != null; child = child.getNext()) {
1637 child.parent = null;
1638 }
1639 first = null;
1640 last = null;
1641 return children;
1642 }
1643
1644 /**
1645 * Removes all children from this node and isolates the children from each
1646 * other.
1647 */
1648 public void detachChildren() {
1649 for (Node child = first; child != null;) {
1650 Node nextChild = child.getNext();
1651 child.parent = null;
1652 child.next = null;
1653 child = nextChild;
1654 }
1655 first = null;
1656 last = null;
1657 }
1658
1659 public Node removeChildAfter(Node prev) {
1660 Preconditions.checkArgument(prev.parent == this,
1661 "prev is not a child of this node.");
1662 Preconditions.checkArgument(prev.next != null,
1663 "no next sibling.");
1664
1665 Node child = prev.next;
1666 prev.next = child.next;
1667 if (child == last) last = prev;
1668 child.next = null;
1669 child.parent = null;
1670 return child;
1671 }
1672
1673 /**
1674 * @return A detached clone of the Node, specifically excluding its children.
1675 */
1676 public Node cloneNode() {
1677 Node result;
1678 try {
1679 result = (Node) super.clone();
1680 // PropListItem lists are immutable and can be shared so there is no
1681 // need to clone them here.
1682 result.next = null;
1683 result.first = null;
1684 result.last = null;
1685 result.parent = null;
1686 } catch (CloneNotSupportedException e) {
1687 throw new RuntimeException(e.getMessage());
1688 }
1689 return result;
1690 }
1691
1692 /**
1693 * @return A detached clone of the Node and all its children.
1694 */
1695 public Node cloneTree() {
1696 Node result = cloneNode();
1697 for (Node n2 = getFirstChild(); n2 != null; n2 = n2.getNext()) {
1698 Node n2clone = n2.cloneTree();
1699 n2clone.parent = result;
1700 if (result.last != null) {
1701 result.last.next = n2clone;
1702 }
1703 if (result.first == null) {
1704 result.first = n2clone;
1705 }
1706 result.last = n2clone;
1707 }
1708 return result;
1709 }
1710
1711 /**
1712 * Copies source file and name information from the other
1713 * node given to the current node. Used for maintaining
1714 * debug information across node append and remove operations.
1715 * @return this
1716 */
1717 // TODO(nicksantos): The semantics of this method are ill-defined. Delete it.
1718 public Node copyInformationFrom(Node other) {
1719 if (getProp(ORIGINALNAME_PROP) == null) {
1720 putProp(ORIGINALNAME_PROP, other.getProp(ORIGINALNAME_PROP));
1721 }
1722
1723 if (getProp(STATIC_SOURCE_FILE) == null) {
1724 putProp(STATIC_SOURCE_FILE, other.getProp(STATIC_SOURCE_FILE));
1725 sourcePosition = other.sourcePosition;
1726 }
1727
1728 return this;
1729 }
1730
1731 /**
1732 * Copies source file and name information from the other node to the
1733 * entire tree rooted at this node.
1734 * @return this
1735 */
1736 // TODO(nicksantos): The semantics of this method are ill-defined. Delete it.
1737 public Node copyInformationFromForTree(Node other) {
1738 copyInformationFrom(other);
1739 for (Node child = getFirstChild();
1740 child != null; child = child.getNext()) {
1741 child.copyInformationFromForTree(other);
1742 }
1743
1744 return this;
1745 }
1746
1747 /**
1748 * Overwrite all the source information in this node with
1749 * that of {@code other}.
1750 */
1751 public Node useSourceInfoFrom(Node other) {
1752 putProp(ORIGINALNAME_PROP, other.getProp(ORIGINALNAME_PROP));
1753 putProp(STATIC_SOURCE_FILE, other.getProp(STATIC_SOURCE_FILE));
1754 sourcePosition = other.sourcePosition;
1755 return this;
1756 }
1757
1758 public Node srcref(Node other) {
1759 return useSourceInfoFrom(other);
1760 }
1761
1762 /**
1763 * Overwrite all the source information in this node and its subtree with
1764 * that of {@code other}.
1765 */
1766 public Node useSourceInfoFromForTree(Node other) {
1767 useSourceInfoFrom(other);
1768 for (Node child = getFirstChild();
1769 child != null; child = child.getNext()) {
1770 child.useSourceInfoFromForTree(other);
1771 }
1772
1773 return this;
1774 }
1775
1776 public Node srcrefTree(Node other) {
1777 return useSourceInfoFromForTree(other);
1778 }
1779
1780 /**
1781 * Overwrite all the source information in this node with
1782 * that of {@code other} iff the source info is missing.
1783 */
1784 public Node useSourceInfoIfMissingFrom(Node other) {
1785 if (getProp(ORIGINALNAME_PROP) == null) {
1786 putProp(ORIGINALNAME_PROP, other.getProp(ORIGINALNAME_PROP));
1787 }
1788
1789 if (getProp(STATIC_SOURCE_FILE) == null) {
1790 putProp(STATIC_SOURCE_FILE, other.getProp(STATIC_SOURCE_FILE));
1791 sourcePosition = other.sourcePosition;
1792 }
1793
1794 return this;
1795 }
1796
1797 /**
1798 * Overwrite all the source information in this node and its subtree with
1799 * that of {@code other} iff the source info is missing.
1800 */
1801 public Node useSourceInfoIfMissingFromForTree(Node other) {
1802 useSourceInfoIfMissingFrom(other);
1803 for (Node child = getFirstChild();
1804 child != null; child = child.getNext()) {
1805 child.useSourceInfoIfMissingFromForTree(other);
1806 }
1807
1808 return this;
1809 }
1810
1811 //==========================================================================
1812 // Custom annotations
1813
1814 public JSType getJSType() {
1815 return jsType;
1816 }
1817
1818 public void setJSType(JSType jsType) {
1819 this.jsType = jsType;
1820 }
1821
1822 public FileLevelJsDocBuilder getJsDocBuilderForNode() {
1823 return new FileLevelJsDocBuilder();
1824 }
1825
1826 /**
1827 * An inner class that provides back-door access to the license
1828 * property of the JSDocInfo property for this node. This is only
1829 * meant to be used for top-level script nodes where the
1830 * {@link com.google.javascript.jscomp.parsing.JsDocInfoParser} needs to
1831 * be able to append directly to the top-level node, not just the
1832 * current node.
1833 */
1834 public class FileLevelJsDocBuilder {
1835 public void append(String fileLevelComment) {
1836 JSDocInfo jsDocInfo = getJSDocInfo();
1837 if (jsDocInfo == null) {
1838 // TODO(user): Is there a way to determine whether to
1839 // parse the JsDoc documentation from here?
1840 jsDocInfo = new JSDocInfo(false);
1841 }
1842 String license = jsDocInfo.getLicense();
1843 if (license == null) {
1844 license = "";
1845 }
1846 jsDocInfo.setLicense(license + fileLevelComment);
1847 setJSDocInfo(jsDocInfo);
1848 }
1849 }
1850
1851 /**
1852 * Get the {@link JSDocInfo} attached to this node.
1853 * @return the information or {@code null} if no JSDoc is attached to this
1854 * node
1855 */
1856 public JSDocInfo getJSDocInfo() {
1857 return (JSDocInfo) getProp(JSDOC_INFO_PROP);
1858 }
1859
1860 /**
1861 * Sets the {@link JSDocInfo} attached to this node.
1862 */
1863 public Node setJSDocInfo(JSDocInfo info) {
1864 putProp(JSDOC_INFO_PROP, info);
1865 return this;
1866 }
1867
1868 /**
1869 * Sets whether this node is a variable length argument node. This
1870 * method is meaningful only on {@link Token#NAME} nodes
1871 * used to define a {@link Token#FUNCTION}'s argument list.
1872 */
1873 public void setVarArgs(boolean varArgs) {
1874 putBooleanProp(VAR_ARGS_NAME, varArgs);
1875 }
1876
1877 /**
1878 * Returns whether this node is a variable length argument node. This
1879 * method's return value is meaningful only on {@link Token#NAME} nodes
1880 * used to define a {@link Token#FUNCTION}'s argument list.
1881 */
1882 public boolean isVarArgs() {
1883 return getBooleanProp(VAR_ARGS_NAME);
1884 }
1885
1886 /**
1887 * Sets whether this node is an optional argument node. This
1888 * method is meaningful only on {@link Token#NAME} nodes
1889 * used to define a {@link Token#FUNCTION}'s argument list.
1890 */
1891 public void setOptionalArg(boolean optionalArg) {
1892 putBooleanProp(OPT_ARG_NAME, optionalArg);
1893 }
1894
1895 /**
1896 * Returns whether this node is an optional argument node. This
1897 * method's return value is meaningful only on {@link Token#NAME} nodes
1898 * used to define a {@link Token#FUNCTION}'s argument list.
1899 */
1900 public boolean isOptionalArg() {
1901 return getBooleanProp(OPT_ARG_NAME);
1902 }
1903
1904 /**
1905 * Sets whether this is a synthetic block that should not be considered
1906 * a real source block.
1907 */
1908 public void setIsSyntheticBlock(boolean val) {
1909 putBooleanProp(SYNTHETIC_BLOCK_PROP, val);
1910 }
1911
1912 /**
1913 * Returns whether this is a synthetic block that should not be considered
1914 * a real source block.
1915 */
1916 public boolean isSyntheticBlock() {
1917 return getBooleanProp(SYNTHETIC_BLOCK_PROP);
1918 }
1919
1920 /**
1921 * Sets the ES5 directives on this node.
1922 */
1923 public void setDirectives(Set<String> val) {
1924 putProp(DIRECTIVES, val);
1925 }
1926
1927 /**
1928 * Returns the set of ES5 directives for this node.
1929 */
1930 @SuppressWarnings("unchecked")
1931 public Set<String> getDirectives() {
1932 return (Set<String>) getProp(DIRECTIVES);
1933 }
1934
1935 /**
1936 * Adds a warning to be suppressed. This is indistinguishable
1937 * from having a {@code @suppress} tag in the code.
1938 */
1939 public void addSuppression(String warning) {
1940 if (getJSDocInfo() == null) {
1941 setJSDocInfo(new JSDocInfo(false));
1942 }
1943 getJSDocInfo().addSuppression(warning);
1944 }
1945
1946 /**
1947 * Sets whether this is a synthetic block that should not be considered
1948 * a real source block.
1949 */
1950 public void setWasEmptyNode(boolean val) {
1951 putBooleanProp(EMPTY_BLOCK, val);
1952 }
1953
1954 /**
1955 * Returns whether this is a synthetic block that should not be considered
1956 * a real source block.
1957 */
1958 public boolean wasEmptyNode() {
1959 return getBooleanProp(EMPTY_BLOCK);
1960 }
1961
1962 // There are four values of interest:
1963 // global state changes
1964 // this state changes
1965 // arguments state changes
1966 // whether the call throws an exception
1967 // locality of the result
1968 // We want a value of 0 to mean "global state changes and
1969 // unknown locality of result".
1970
1971 final public static int FLAG_GLOBAL_STATE_UNMODIFIED = 1;
1972 final public static int FLAG_THIS_UNMODIFIED = 2;
1973 final public static int FLAG_ARGUMENTS_UNMODIFIED = 4;
1974 final public static int FLAG_NO_THROWS = 8;
1975 final public static int FLAG_LOCAL_RESULTS = 16;
1976
1977 final public static int SIDE_EFFECTS_FLAGS_MASK = 31;
1978
1979 final public static int SIDE_EFFECTS_ALL = 0;
1980 final public static int NO_SIDE_EFFECTS =
1981 FLAG_GLOBAL_STATE_UNMODIFIED
1982 | FLAG_THIS_UNMODIFIED
1983 | FLAG_ARGUMENTS_UNMODIFIED
1984 | FLAG_NO_THROWS;
1985
1986 /**
1987 * Marks this function or constructor call's side effect flags.
1988 * This property is only meaningful for {@link Token#CALL} and
1989 * {@link Token#NEW} nodes.
1990 */
1991 public void setSideEffectFlags(int flags) {
1992 Preconditions.checkArgument(
1993 getType() == Token.CALL || getType() == Token.NEW,
1994 "setIsNoSideEffectsCall only supports CALL and NEW nodes, got " +
1995 Token.name(getType()));
1996
1997 putIntProp(SIDE_EFFECT_FLAGS, flags);
1998 }
1999
2000 public void setSideEffectFlags(SideEffectFlags flags) {
2001 setSideEffectFlags(flags.valueOf());
2002 }
2003
2004 /**
2005 * Returns the side effects flags for this node.
2006 */
2007 public int getSideEffectFlags() {
2008 return getIntProp(SIDE_EFFECT_FLAGS);
2009 }
2010
2011 /**
2012 * A helper class for getting and setting the side-effect flags.
2013 * @author [email protected] (John Lenz)
2014 */
2015 public static class SideEffectFlags {
2016 private int value = Node.SIDE_EFFECTS_ALL;
2017
2018 public SideEffectFlags() {
2019 }
2020
2021 public SideEffectFlags(int value) {
2022 this.value = value;
2023 }
2024
2025 public int valueOf() {
2026 return value;
2027 }
2028
2029 /** All side-effect occur and the returned results are non-local. */
2030 public void setAllFlags() {
2031 value = Node.SIDE_EFFECTS_ALL;
2032 }
2033
2034 /** No side-effects occur and the returned results are local. */
2035 public void clearAllFlags() {
2036 value = Node.NO_SIDE_EFFECTS | Node.FLAG_LOCAL_RESULTS;
2037 }
2038
2039 public boolean areAllFlagsSet() {
2040 return value == Node.SIDE_EFFECTS_ALL;
2041 }
2042
2043 /**
2044 * Preserve the return result flag, but clear the others:
2045 * no global state change, no throws, no this change, no arguments change
2046 */
2047 public void clearSideEffectFlags() {
2048 value |= Node.NO_SIDE_EFFECTS;
2049 }
2050
2051 public void setMutatesGlobalState() {
2052 // Modify global means everything must be assumed to be modified.
2053 removeFlag(Node.FLAG_GLOBAL_STATE_UNMODIFIED);
2054 removeFlag(Node.FLAG_ARGUMENTS_UNMODIFIED);
2055 removeFlag(Node.FLAG_THIS_UNMODIFIED);
2056 }
2057
2058 public void setThrows() {
2059 removeFlag(Node.FLAG_NO_THROWS);
2060 }
2061
2062 public void setMutatesThis() {
2063 removeFlag(Node.FLAG_THIS_UNMODIFIED);
2064 }
2065
2066 public void setMutatesArguments() {
2067 removeFlag(Node.FLAG_ARGUMENTS_UNMODIFIED);
2068 }
2069
2070 public void setReturnsTainted() {
2071 removeFlag(Node.FLAG_LOCAL_RESULTS);
2072 }
2073
2074 private void removeFlag(int flag) {
2075 value &= ~flag;
2076 }
2077 }
2078
2079 /**
2080 * @return Whether the only side-effect is "modifies this"
2081 */
2082 public boolean isOnlyModifiesThisCall() {
2083 return areBitFlagsSet(
2084 getSideEffectFlags() & Node.NO_SIDE_EFFECTS,
2085 Node.FLAG_GLOBAL_STATE_UNMODIFIED
2086 | Node.FLAG_ARGUMENTS_UNMODIFIED
2087 | Node.FLAG_NO_THROWS);
2088 }
2089
2090 /**
2091 * Returns true if this node is a function or constructor call that
2092 * has no side effects.
2093 */
2094 public boolean isNoSideEffectsCall() {
2095 return areBitFlagsSet(getSideEffectFlags(), NO_SIDE_EFFECTS);
2096 }
2097
2098 /**
2099 * Returns true if this node is a function or constructor call that
2100 * returns a primitive or a local object (an object that has no other
2101 * references).
2102 */
2103 public boolean isLocalResultCall() {
2104 return areBitFlagsSet(getSideEffectFlags(), FLAG_LOCAL_RESULTS);
2105 }
2106
2107 /**
2108 * returns true if all the flags are set in value.
2109 */
2110 private boolean areBitFlagsSet(int value, int flags) {
2111 return (value & flags) == flags;
2112 }
2113
2114 /**
2115 * This should only be called for STRING nodes children of OBJECTLIT.
2116 */
2117 public boolean isQuotedString() {
2118 return false;
2119 }
2120
2121 /**
2122 * This should only be called for STRING nodes children of OBJECTLIT.
2123 */
2124 public void setQuotedString() {
2125 throw new IllegalStateException("not a StringNode");
2126 }
2127
2128 static class NodeMismatch {
2129 final Node nodeA;
2130 final Node nodeB;
2131
2132 NodeMismatch(Node nodeA, Node nodeB) {
2133 this.nodeA = nodeA;
2134 this.nodeB = nodeB;
2135 }
2136
2137 @Override
2138 public boolean equals(Object object) {
2139 if (object instanceof NodeMismatch) {
2140 NodeMismatch that = (NodeMismatch) object;
2141 return that.nodeA.equals(this.nodeA) && that.nodeB.equals(this.nodeB);
2142 }
2143 return false;
2144 }
2145
2146 @Override
2147 public int hashCode() {
2148 return Objects.hashCode(nodeA, nodeB);
2149 }
2150 }
2151
2152
2153 /*** AST type check methods ***/
2154
2155 public boolean isAdd() {
2156 return this.getType() == Token.ADD;
2157 }
2158
2159 public boolean isAnd() {
2160 return this.getType() == Token.AND;
2161 }
2162
2163 public boolean isArrayLit() {
2164 return this.getType() == Token.ARRAYLIT;
2165 }
2166
2167 public boolean isAssign() {
2168 return this.getType() == Token.ASSIGN;
2169 }
2170
2171 public boolean isAssignAdd() {
2172 return this.getType() == Token.ASSIGN_ADD;
2173 }
2174
2175 public boolean isBlock() {
2176 return this.getType() == Token.BLOCK;
2177 }
2178
2179 public boolean isBreak() {
2180 return this.getType() == Token.BREAK;
2181 }
2182
2183 public boolean isCall() {
2184 return this.getType() == Token.CALL;
2185 }
2186
2187 public boolean isCase() {
2188 return this.getType() == Token.CASE;
2189 }
2190
2191 public boolean isCast() {
2192 return this.getType() == Token.CAST;
2193 }
2194
2195 public boolean isCatch() {
2196 return this.getType() == Token.CATCH;
2197 }
2198
2199 public boolean isComma() {
2200 return this.getType() == Token.COMMA;
2201 }
2202
2203 public boolean isContinue() {
2204 return this.getType() == Token.CONTINUE;
2205 }
2206
2207 public boolean isDebugger() {
2208 return this.getType() == Token.DEBUGGER;
2209 }
2210
2211 public boolean isDec() {
2212 return this.getType() == Token.DEC;
2213 }
2214
2215 public boolean isDefaultCase() {
2216 return this.getType() == Token.DEFAULT_CASE;
2217 }
2218
2219 public boolean isDelProp() {
2220 return this.getType() == Token.DELPROP;
2221 }
2222
2223 public boolean isDo() {
2224 return this.getType() == Token.DO;
2225 }
2226
2227 public boolean isEmpty() {
2228 return this.getType() == Token.EMPTY;
2229 }
2230
2231 public boolean isExprResult() {
2232 return this.getType() == Token.EXPR_RESULT;
2233 }
2234
2235 public boolean isFalse() {
2236 return this.getType() == Token.FALSE;
2237 }
2238
2239 public boolean isFor() {
2240 return this.getType() == Token.FOR;
2241 }
2242
2243 public boolean isFunction() {
2244 return this.getType() == Token.FUNCTION;
2245 }
2246
2247 public boolean isGetterDef() {
2248 return this.getType() == Token.GETTER_DEF;
2249 }
2250
2251 public boolean isGetElem() {
2252 return this.getType() == Token.GETELEM;
2253 }
2254
2255 public boolean isGetProp() {
2256 return this.getType() == Token.GETPROP;
2257 }
2258
2259 public boolean isHook() {
2260 return this.getType() == Token.HOOK;
2261 }
2262
2263 public boolean isIf() {
2264 return this.getType() == Token.IF;
2265 }
2266
2267 public boolean isIn() {
2268 return this.getType() == Token.IN;
2269 }
2270
2271 public boolean isInc() {
2272 return this.getType() == Token.INC;
2273 }
2274
2275 public boolean isInstanceOf() {
2276 return this.getType() == Token.INSTANCEOF;
2277 }
2278
2279 public boolean isLabel() {
2280 return this.getType() == Token.LABEL;
2281 }
2282
2283 public boolean isLabelName() {
2284 return this.getType() == Token.LABEL_NAME;
2285 }
2286
2287 public boolean isName() {
2288 return this.getType() == Token.NAME;
2289 }
2290
2291 public boolean isNE() {
2292 return this.getType() == Token.NE;
2293 }
2294
2295 public boolean isNew() {
2296 return this.getType() == Token.NEW;
2297 }
2298
2299 public boolean isNot() {
2300 return this.getType() == Token.NOT;
2301 }
2302
2303 public boolean isNull() {
2304 return this.getType() == Token.NULL;
2305 }
2306
2307 public boolean isNumber() {
2308 return this.getType() == Token.NUMBER;
2309 }
2310
2311 public boolean isObjectLit() {
2312 return this.getType() == Token.OBJECTLIT;
2313 }
2314
2315 public boolean isOr() {
2316 return this.getType() == Token.OR;
2317 }
2318
2319 public boolean isParamList() {
2320 return this.getType() == Token.PARAM_LIST;
2321 }
2322
2323 public boolean isRegExp() {
2324 return this.getType() == Token.REGEXP;
2325 }
2326
2327 public boolean isReturn() {
2328 return this.getType() == Token.RETURN;
2329 }
2330
2331 public boolean isScript() {
2332 return this.getType() == Token.SCRIPT;
2333 }
2334
2335 public boolean isSetterDef() {
2336 return this.getType() == Token.SETTER_DEF;
2337 }
2338
2339 public boolean isString() {
2340 return this.getType() == Token.STRING;
2341 }
2342
2343 public boolean isStringKey() {
2344 return this.getType() == Token.STRING_KEY;
2345 }
2346
2347 public boolean isSwitch() {
2348 return this.getType() == Token.SWITCH;
2349 }
2350
2351 public boolean isThis() {
2352 return this.getType() == Token.THIS;
2353 }
2354
2355 public boolean isThrow() {
2356 return this.getType() == Token.THROW;
2357 }
2358
2359 public boolean isTrue() {
2360 return this.getType() == Token.TRUE;
2361 }
2362
2363 public boolean isTry() {
2364 return this.getType() == Token.TRY;
2365 }
2366
2367 public boolean isTypeOf() {
2368 return this.getType() == Token.TYPEOF;
2369 }
2370
2371 public boolean isVar() {
2372 return this.getType() == Token.VAR;
2373 }
2374
2375 public boolean isVoid() {
2376 return this.getType() == Token.VOID;
2377 }
2378
2379 public boolean isWhile() {
2380 return this.getType() == Token.WHILE;
2381 }
2382
2383 public boolean isWith() {
2384 return this.getType() == Token.WITH;
2385 }
2386 }