Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Predicate;
21 import com.google.common.base.Predicates;
22 import com.google.common.collect.ImmutableSet;
23 import com.google.common.collect.Maps;
24 import com.google.javascript.rhino.IR;
25 import com.google.javascript.rhino.InputId;
26 import com.google.javascript.rhino.JSDocInfo;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.Token;
29 import com.google.javascript.rhino.TokenStream;
30 import com.google.javascript.rhino.jstype.FunctionType;
31 import com.google.javascript.rhino.jstype.JSType;
32 import com.google.javascript.rhino.jstype.StaticSourceFile;
33 import com.google.javascript.rhino.jstype.TernaryValue;
34
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.HashSet;
39 import java.util.Map;
40 import java.util.Set;
41
42 import javax.annotation.Nullable;
43
44 /**
45 * NodeUtil contains generally useful AST utilities.
46 *
47 */
48 public final class NodeUtil {
49
50 static final long MAX_POSITIVE_INTEGER_NUMBER = (long) Math.pow(2, 53);
51
52 static final String JSC_PROPERTY_NAME_FN = "JSCompiler_renameProperty";
53
54 static final char LARGEST_BASIC_LATIN = 0x7f;
55
56 /** the set of builtin constructors that don't have side effects. */
57 private static final Set<String> CONSTRUCTORS_WITHOUT_SIDE_EFFECTS =
58 new HashSet<String>(Arrays.asList(
59 "Array",
60 "Date",
61 "Error",
62 "Object",
63 "RegExp",
64 "XMLHttpRequest"));
65
66 // Utility class; do not instantiate.
67 private NodeUtil() {}
68
69 /**
70 * Gets the boolean value of a node that represents a expression. This method
71 * effectively emulates the <code>Boolean()</code> JavaScript cast function.
72 * Note: unlike getBooleanValue this function does not return UNKNOWN
73 * for expressions with side-effects.
74 */
75 static TernaryValue getImpureBooleanValue(Node n) {
76 switch (n.getType()) {
77 case Token.ASSIGN:
78 case Token.COMMA:
79 // For ASSIGN and COMMA the value is the value of the RHS.
80 return getImpureBooleanValue(n.getLastChild());
81 case Token.NOT:
82 TernaryValue value = getImpureBooleanValue(n.getLastChild());
83 return value.not();
84 case Token.AND: {
85 TernaryValue lhs = getImpureBooleanValue(n.getFirstChild());
86 TernaryValue rhs = getImpureBooleanValue(n.getLastChild());
87 return lhs.and(rhs);
88 }
89 case Token.OR: {
90 TernaryValue lhs = getImpureBooleanValue(n.getFirstChild());
91 TernaryValue rhs = getImpureBooleanValue(n.getLastChild());
92 return lhs.or(rhs);
93 }
94 case Token.HOOK: {
95 TernaryValue trueValue = getImpureBooleanValue(
96 n.getFirstChild().getNext());
97 TernaryValue falseValue = getImpureBooleanValue(n.getLastChild());
98 if (trueValue.equals(falseValue)) {
99 return trueValue;
100 } else {
101 return TernaryValue.UNKNOWN;
102 }
103 }
104 case Token.ARRAYLIT:
105 case Token.OBJECTLIT:
106 // ignoring side-effects
107 return TernaryValue.TRUE;
108
109 case Token.VOID:
110 return TernaryValue.FALSE;
111
112 default:
113 return getPureBooleanValue(n);
114 }
115 }
116
117 /**
118 * Gets the boolean value of a node that represents a literal. This method
119 * effectively emulates the <code>Boolean()</code> JavaScript cast function
120 * except it return UNKNOWN for known values with side-effects, use
121 * getImpureBooleanValue if you don't care about side-effects.
122 */
123 static TernaryValue getPureBooleanValue(Node n) {
124 switch (n.getType()) {
125 case Token.STRING:
126 return TernaryValue.forBoolean(n.getString().length() > 0);
127
128 case Token.NUMBER:
129 return TernaryValue.forBoolean(n.getDouble() != 0);
130
131 case Token.NOT:
132 return getPureBooleanValue(n.getLastChild()).not();
133
134 case Token.NULL:
135 case Token.FALSE:
136 return TernaryValue.FALSE;
137
138 case Token.VOID:
139 if (!mayHaveSideEffects(n.getFirstChild())) {
140 return TernaryValue.FALSE;
141 }
142 break;
143
144 case Token.NAME:
145 String name = n.getString();
146 if ("undefined".equals(name)
147 || "NaN".equals(name)) {
148 // We assume here that programs don't change the value of the keyword
149 // undefined to something other than the value undefined.
150 return TernaryValue.FALSE;
151 } else if ("Infinity".equals(name)) {
152 return TernaryValue.TRUE;
153 }
154 break;
155
156 case Token.TRUE:
157 case Token.REGEXP:
158 return TernaryValue.TRUE;
159
160 case Token.ARRAYLIT:
161 case Token.OBJECTLIT:
162 if (!mayHaveSideEffects(n)) {
163 return TernaryValue.TRUE;
164 }
165 break;
166 }
167
168 return TernaryValue.UNKNOWN;
169 }
170
171 /**
172 * Gets the value of a node as a String, or null if it cannot be converted.
173 * When it returns a non-null String, this method effectively emulates the
174 * <code>String()</code> JavaScript cast function.
175 */
176 static String getStringValue(Node n) {
177 // TODO(user): regex literals as well.
178 switch (n.getType()) {
179 case Token.STRING:
180 case Token.STRING_KEY:
181 return n.getString();
182
183 case Token.NAME:
184 String name = n.getString();
185 if ("undefined".equals(name)
186 || "Infinity".equals(name)
187 || "NaN".equals(name)) {
188 return name;
189 }
190 break;
191
192 case Token.NUMBER:
193 return getStringValue(n.getDouble());
194
195 case Token.FALSE:
196 return "false";
197
198 case Token.TRUE:
199 return "true";
200
201 case Token.NULL:
202 return "null";
203
204 case Token.VOID:
205 return "undefined";
206
207 case Token.NOT:
208 TernaryValue child = getPureBooleanValue(n.getFirstChild());
209 if (child != TernaryValue.UNKNOWN) {
210 return child.toBoolean(true) ? "false" : "true"; // reversed.
211 }
212 break;
213
214 case Token.ARRAYLIT:
215 return arrayToString(n);
216
217 case Token.OBJECTLIT:
218 return "[object Object]";
219 }
220 return null;
221 }
222
223 static String getStringValue(double value) {
224 long longValue = (long) value;
225
226 // Return "1" instead of "1.0"
227 if (longValue == value) {
228 return Long.toString(longValue);
229 } else {
230 return Double.toString(value);
231 }
232 }
233
234 /**
235 * When converting arrays to string using Array.prototype.toString or
236 * Array.prototype.join, the rules for conversion to String are different
237 * than converting each element individually. Specifically, "null" and
238 * "undefined" are converted to an empty string.
239 * @param n A node that is a member of an Array.
240 * @return The string representation.
241 */
242 static String getArrayElementStringValue(Node n) {
243 return (NodeUtil.isNullOrUndefined(n) || n.isEmpty())
244 ? "" : getStringValue(n);
245 }
246
247 static String arrayToString(Node literal) {
248 Node first = literal.getFirstChild();
249 StringBuilder result = new StringBuilder();
250 for (Node n = first; n != null; n = n.getNext()) {
251 String childValue = getArrayElementStringValue(n);
252 if (childValue == null) {
253 return null;
254 }
255 if (n != first) {
256 result.append(',');
257 }
258 result.append(childValue);
259 }
260 return result.toString();
261 }
262
263 /**
264 * Gets the value of a node as a Number, or null if it cannot be converted.
265 * When it returns a non-null Double, this method effectively emulates the
266 * <code>Number()</code> JavaScript cast function.
267 */
268 static Double getNumberValue(Node n) {
269 switch (n.getType()) {
270 case Token.TRUE:
271 return 1.0;
272
273 case Token.FALSE:
274 case Token.NULL:
275 return 0.0;
276
277 case Token.NUMBER:
278 return n.getDouble();
279
280 case Token.VOID:
281 if (mayHaveSideEffects(n.getFirstChild())) {
282 return null;
283 } else {
284 return Double.NaN;
285 }
286
287 case Token.NAME:
288 // Check for known constants
289 String name = n.getString();
290 if (name.equals("undefined")) {
291 return Double.NaN;
292 }
293 if (name.equals("NaN")) {
294 return Double.NaN;
295 }
296 if (name.equals("Infinity")) {
297 return Double.POSITIVE_INFINITY;
298 }
299 return null;
300
301 case Token.NEG:
302 if (n.getChildCount() == 1 && n.getFirstChild().isName()
303 && n.getFirstChild().getString().equals("Infinity")) {
304 return Double.NEGATIVE_INFINITY;
305 }
306 return null;
307
308 case Token.NOT:
309 TernaryValue child = getPureBooleanValue(n.getFirstChild());
310 if (child != TernaryValue.UNKNOWN) {
311 return child.toBoolean(true) ? 0.0 : 1.0; // reversed.
312 }
313 break;
314
315 case Token.STRING:
316 return getStringNumberValue(n.getString());
317
318 case Token.ARRAYLIT:
319 case Token.OBJECTLIT:
320 String value = getStringValue(n);
321 return value != null ? getStringNumberValue(value) : null;
322 }
323
324 return null;
325 }
326
327 static Double getStringNumberValue(String rawJsString) {
328 if (rawJsString.contains("\u000b")) {
329 // vertical tab is not always whitespace
330 return null;
331 }
332
333 String s = trimJsWhiteSpace(rawJsString);
334 // return ScriptRuntime.toNumber(s);
335 if (s.length() == 0) {
336 return 0.0;
337 }
338
339 if (s.length() > 2
340 && s.charAt(0) == '0'
341 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
342 // Attempt to convert hex numbers.
343 try {
344 return Double.valueOf(Integer.parseInt(s.substring(2), 16));
345 } catch (NumberFormatException e) {
346 return Double.NaN;
347 }
348 }
349
350 if (s.length() > 3
351 && (s.charAt(0) == '-' || s.charAt(0) == '+')
352 && s.charAt(1) == '0'
353 && (s.charAt(2) == 'x' || s.charAt(2) == 'X')) {
354 // hex numbers with explicit signs vary between browsers.
355 return null;
356 }
357
358 // Firefox and IE treat the "Infinity" differently. Firefox is case
359 // insensitive, but IE treats "infinity" as NaN. So leave it alone.
360 if (s.equals("infinity")
361 || s.equals("-infinity")
362 || s.equals("+infinity")) {
363 return null;
364 }
365
366 try {
367 return Double.parseDouble(s);
368 } catch (NumberFormatException e) {
369 return Double.NaN;
370 }
371 }
372
373 static String trimJsWhiteSpace(String s) {
374 int start = 0;
375 int end = s.length();
376 while (end > 0
377 && isStrWhiteSpaceChar(s.charAt(end - 1)) == TernaryValue.TRUE) {
378 end--;
379 }
380 while (start < end
381 && isStrWhiteSpaceChar(s.charAt(start)) == TernaryValue.TRUE) {
382 start++;
383 }
384 return s.substring(start, end);
385 }
386
387 /**
388 * Copied from Rhino's ScriptRuntime
389 */
390 public static TernaryValue isStrWhiteSpaceChar(int c) {
391 switch (c) {
392 case '\u000B': // <VT>
393 return TernaryValue.UNKNOWN; // IE says "no", ECMAScript says "yes"
394 case ' ': // <SP>
395 case '\n': // <LF>
396 case '\r': // <CR>
397 case '\t': // <TAB>
398 case '\u00A0': // <NBSP>
399 case '\u000C': // <FF>
400 case '\u2028': // <LS>
401 case '\u2029': // <PS>
402 case '\uFEFF': // <BOM>
403 return TernaryValue.TRUE;
404 default:
405 return (Character.getType(c) == Character.SPACE_SEPARATOR)
406 ? TernaryValue.TRUE : TernaryValue.FALSE;
407 }
408 }
409
410 /**
411 * Gets the function's name. This method recognizes five forms:
412 * <ul>
413 * <li>{@code function name() ...}</li>
414 * <li>{@code var name = function() ...}</li>
415 * <li>{@code qualified.name = function() ...}</li>
416 * <li>{@code var name2 = function name1() ...}</li>
417 * <li>{@code qualified.name2 = function name1() ...}</li>
418 * </ul>
419 * In two last cases with named function expressions, the second name is
420 * returned (the variable of qualified name).
421 *
422 * @param n a node whose type is {@link Token#FUNCTION}
423 * @return the function's name, or {@code null} if it has no name
424 */
425 static String getFunctionName(Node n) {
426 Preconditions.checkState(n.isFunction());
427 Node parent = n.getParent();
428 switch (parent.getType()) {
429 case Token.NAME:
430 // var name = function() ...
431 // var name2 = function name1() ...
432 return parent.getQualifiedName();
433
434 case Token.ASSIGN:
435 // qualified.name = function() ...
436 // qualified.name2 = function name1() ...
437 return parent.getFirstChild().getQualifiedName();
438
439 default:
440 // function name() ...
441 String name = n.getFirstChild().getQualifiedName();
442 return name;
443 }
444 }
445
446 /**
447 * Gets the function's name. This method recognizes the forms:
448 * <ul>
449 * <li>{@code &#123;'name': function() ...&#125;}</li>
450 * <li>{@code &#123;name: function() ...&#125;}</li>
451 * <li>{@code function name() ...}</li>
452 * <li>{@code var name = function() ...}</li>
453 * <li>{@code qualified.name = function() ...}</li>
454 * <li>{@code var name2 = function name1() ...}</li>
455 * <li>{@code qualified.name2 = function name1() ...}</li>
456 * </ul>
457 *
458 * @param n a node whose type is {@link Token#FUNCTION}
459 * @return the function's name, or {@code null} if it has no name
460 */
461 public static String getNearestFunctionName(Node n) {
462 if (!n.isFunction()) {
463 return null;
464 }
465
466 String name = getFunctionName(n);
467 if (name != null) {
468 return name;
469 }
470
471 // Check for the form { 'x' : function() { } }
472 Node parent = n.getParent();
473 switch (parent.getType()) {
474 case Token.SETTER_DEF:
475 case Token.GETTER_DEF:
476 case Token.STRING_KEY:
477 // Return the name of the literal's key.
478 return parent.getString();
479 case Token.NUMBER:
480 return getStringValue(parent);
481 }
482
483 return null;
484 }
485
486
487 /**
488 * Returns true if this is an immutable value.
489 */
490 static boolean isImmutableValue(Node n) {
491 switch (n.getType()) {
492 case Token.STRING:
493 case Token.NUMBER:
494 case Token.NULL:
495 case Token.TRUE:
496 case Token.FALSE:
497 return true;
498 case Token.CAST:
499 case Token.NOT:
500 return isImmutableValue(n.getFirstChild());
501 case Token.VOID:
502 case Token.NEG:
503 return isImmutableValue(n.getFirstChild());
504 case Token.NAME:
505 String name = n.getString();
506 // We assume here that programs don't change the value of the keyword
507 // undefined to something other than the value undefined.
508 return "undefined".equals(name)
509 || "Infinity".equals(name)
510 || "NaN".equals(name);
511 }
512
513 return false;
514 }
515
516 /**
517 * Returns true if the operator on this node is symmetric
518 */
519 static boolean isSymmetricOperation(Node n) {
520 switch (n.getType()) {
521 case Token.EQ: // equal
522 case Token.NE: // not equal
523 case Token.SHEQ: // exactly equal
524 case Token.SHNE: // exactly not equal
525 case Token.MUL: // multiply, unlike add it only works on numbers
526 // or results NaN if any of the operators is not a number
527 return true;
528 }
529 return false;
530 }
531
532 /**
533 * Returns true if the operator on this node is relational.
534 * the returned set does not include the equalities.
535 */
536 static boolean isRelationalOperation(Node n) {
537 switch (n.getType()) {
538 case Token.GT: // equal
539 case Token.GE: // not equal
540 case Token.LT: // exactly equal
541 case Token.LE: // exactly not equal
542 return true;
543 }
544 return false;
545 }
546
547 /**
548 * Returns the inverse of an operator if it is invertible.
549 * ex. '>' ==> '<'
550 */
551 static int getInverseOperator(int type) {
552 switch (type) {
553 case Token.GT:
554 return Token.LT;
555 case Token.LT:
556 return Token.GT;
557 case Token.GE:
558 return Token.LE;
559 case Token.LE:
560 return Token.GE;
561 }
562 return Token.ERROR;
563 }
564
565 /**
566 * Returns true if this is a literal value. We define a literal value
567 * as any node that evaluates to the same thing regardless of when or
568 * where it is evaluated. So /xyz/ and [3, 5] are literals, but
569 * the name a is not.
570 *
571 * Function literals do not meet this definition, because they
572 * lexically capture variables. For example, if you have
573 * <code>
574 * function() { return a; }
575 * </code>
576 * If it is evaluated in a different scope, then it
577 * captures a different variable. Even if the function did not read
578 * any captured variables directly, it would still fail this definition,
579 * because it affects the lifecycle of variables in the enclosing scope.
580 *
581 * However, a function literal with respect to a particular scope is
582 * a literal.
583 *
584 * @param includeFunctions If true, all function expressions will be
585 * treated as literals.
586 */
587 static boolean isLiteralValue(Node n, boolean includeFunctions) {
588 switch (n.getType()) {
589 case Token.CAST:
590 return isLiteralValue(n.getFirstChild(), includeFunctions);
591
592 case Token.ARRAYLIT:
593 for (Node child = n.getFirstChild(); child != null;
594 child = child.getNext()) {
595 if ((!child.isEmpty()) && !isLiteralValue(child, includeFunctions)) {
596 return false;
597 }
598 }
599 return true;
600
601 case Token.REGEXP:
602 // Return true only if all children are const.
603 for (Node child = n.getFirstChild(); child != null;
604 child = child.getNext()) {
605 if (!isLiteralValue(child, includeFunctions)) {
606 return false;
607 }
608 }
609 return true;
610
611 case Token.OBJECTLIT:
612 // Return true only if all values are const.
613 for (Node child = n.getFirstChild(); child != null;
614 child = child.getNext()) {
615 if (!isLiteralValue(child.getFirstChild(), includeFunctions)) {
616 return false;
617 }
618 }
619 return true;
620
621 case Token.FUNCTION:
622 return includeFunctions && !NodeUtil.isFunctionDeclaration(n);
623
624 default:
625 return isImmutableValue(n);
626 }
627 }
628
629 /**
630 * Determines whether the given value may be assigned to a define.
631 *
632 * @param val The value being assigned.
633 * @param defines The list of names of existing defines.
634 */
635 static boolean isValidDefineValue(Node val, Set<String> defines) {
636 switch (val.getType()) {
637 case Token.STRING:
638 case Token.NUMBER:
639 case Token.TRUE:
640 case Token.FALSE:
641 return true;
642
643 // Binary operators are only valid if both children are valid.
644 case Token.ADD:
645 case Token.BITAND:
646 case Token.BITNOT:
647 case Token.BITOR:
648 case Token.BITXOR:
649 case Token.DIV:
650 case Token.EQ:
651 case Token.GE:
652 case Token.GT:
653 case Token.LE:
654 case Token.LSH:
655 case Token.LT:
656 case Token.MOD:
657 case Token.MUL:
658 case Token.NE:
659 case Token.RSH:
660 case Token.SHEQ:
661 case Token.SHNE:
662 case Token.SUB:
663 case Token.URSH:
664 return isValidDefineValue(val.getFirstChild(), defines)
665 && isValidDefineValue(val.getLastChild(), defines);
666
667 // Unary operators are valid if the child is valid.
668 case Token.NOT:
669 case Token.NEG:
670 case Token.POS:
671 return isValidDefineValue(val.getFirstChild(), defines);
672
673 // Names are valid if and only if they are defines themselves.
674 case Token.NAME:
675 case Token.GETPROP:
676 if (val.isQualifiedName()) {
677 return defines.contains(val.getQualifiedName());
678 }
679 }
680 return false;
681 }
682
683 /**
684 * Returns whether this a BLOCK node with no children.
685 *
686 * @param block The node.
687 */
688 static boolean isEmptyBlock(Node block) {
689 if (!block.isBlock()) {
690 return false;
691 }
692
693 for (Node n = block.getFirstChild(); n != null; n = n.getNext()) {
694 if (!n.isEmpty()) {
695 return false;
696 }
697 }
698 return true;
699 }
700
701 static boolean isSimpleOperator(Node n) {
702 return isSimpleOperatorType(n.getType());
703 }
704
705 /**
706 * A "simple" operator is one whose children are expressions,
707 * has no direct side-effects (unlike '+='), and has no
708 * conditional aspects (unlike '||').
709 */
710 static boolean isSimpleOperatorType(int type) {
711 switch (type) {
712 case Token.ADD:
713 case Token.BITAND:
714 case Token.BITNOT:
715 case Token.BITOR:
716 case Token.BITXOR:
717 case Token.COMMA:
718 case Token.DIV:
719 case Token.EQ:
720 case Token.GE:
721 case Token.GETELEM:
722 case Token.GETPROP:
723 case Token.GT:
724 case Token.INSTANCEOF:
725 case Token.LE:
726 case Token.LSH:
727 case Token.LT:
728 case Token.MOD:
729 case Token.MUL:
730 case Token.NE:
731 case Token.NOT:
732 case Token.RSH:
733 case Token.SHEQ:
734 case Token.SHNE:
735 case Token.SUB:
736 case Token.TYPEOF:
737 case Token.VOID:
738 case Token.POS:
739 case Token.NEG:
740 case Token.URSH:
741 return true;
742
743 default:
744 return false;
745 }
746 }
747
748 /**
749 * Creates an EXPR_RESULT.
750 *
751 * @param child The expression itself.
752 * @return Newly created EXPR node with the child as subexpression.
753 */
754 static Node newExpr(Node child) {
755 return IR.exprResult(child).srcref(child);
756 }
757
758 /**
759 * Returns true if the node may create new mutable state, or change existing
760 * state.
761 *
762 * @see <a href="http://www.xkcd.org/326/">XKCD Cartoon</a>
763 */
764 static boolean mayEffectMutableState(Node n) {
765 return mayEffectMutableState(n, null);
766 }
767
768 static boolean mayEffectMutableState(Node n, AbstractCompiler compiler) {
769 return checkForStateChangeHelper(n, true, compiler);
770 }
771
772 /**
773 * Returns true if the node which may have side effects when executed.
774 */
775 static boolean mayHaveSideEffects(Node n) {
776 return mayHaveSideEffects(n, null);
777 }
778
779 static boolean mayHaveSideEffects(Node n, AbstractCompiler compiler) {
780 return checkForStateChangeHelper(n, false, compiler);
781 }
782
783 /**
784 * Returns true if some node in n's subtree changes application state.
785 * If {@code checkForNewObjects} is true, we assume that newly created
786 * mutable objects (like object literals) change state. Otherwise, we assume
787 * that they have no side effects.
788 */
789 private static boolean checkForStateChangeHelper(
790 Node n, boolean checkForNewObjects, AbstractCompiler compiler) {
791 // Rather than id which ops may have side effects, id the ones
792 // that we know to be safe
793 switch (n.getType()) {
794 // other side-effect free statements and expressions
795 case Token.CAST:
796 case Token.AND:
797 case Token.BLOCK:
798 case Token.EXPR_RESULT:
799 case Token.HOOK:
800 case Token.IF:
801 case Token.IN:
802 case Token.PARAM_LIST:
803 case Token.NUMBER:
804 case Token.OR:
805 case Token.THIS:
806 case Token.TRUE:
807 case Token.FALSE:
808 case Token.NULL:
809 case Token.STRING:
810 case Token.STRING_KEY:
811 case Token.SWITCH:
812 case Token.TRY:
813 case Token.EMPTY:
814 break;
815
816 // Throws are by definition side effects
817 case Token.THROW:
818 return true;
819
820 case Token.OBJECTLIT:
821 if (checkForNewObjects) {
822 return true;
823 }
824 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
825 if (checkForStateChangeHelper(
826 c.getFirstChild(), checkForNewObjects, compiler)) {
827 return true;
828 }
829 }
830 return false;
831
832 case Token.ARRAYLIT:
833 case Token.REGEXP:
834 if (checkForNewObjects) {
835 return true;
836 }
837 break;
838
839 case Token.VAR: // empty var statement (no declaration)
840 case Token.NAME: // variable by itself
841 if (n.getFirstChild() != null) {
842 return true;
843 }
844 break;
845
846 case Token.FUNCTION:
847 // Function expressions don't have side-effects, but function
848 // declarations change the namespace. Either way, we don't need to
849 // check the children, since they aren't executed at declaration time.
850 return checkForNewObjects || !isFunctionExpression(n);
851
852 case Token.NEW:
853 if (checkForNewObjects) {
854 return true;
855 }
856
857 if (!constructorCallHasSideEffects(n)) {
858 // loop below will see if the constructor parameters have
859 // side-effects
860 break;
861 }
862 return true;
863
864 case Token.CALL:
865 // calls to functions that have no side effects have the no
866 // side effect property set.
867 if (!functionCallHasSideEffects(n, compiler)) {
868 // loop below will see if the function parameters have
869 // side-effects
870 break;
871 }
872 return true;
873
874 default:
875 if (isSimpleOperator(n)) {
876 break;
877 }
878
879 if (isAssignmentOp(n)) {
880 Node assignTarget = n.getFirstChild();
881 if (assignTarget.isName()) {
882 return true;
883 }
884
885 // Assignments will have side effects if
886 // a) The RHS has side effects, or
887 // b) The LHS has side effects, or
888 // c) A name on the LHS will exist beyond the life of this statement.
889 if (checkForStateChangeHelper(
890 n.getFirstChild(), checkForNewObjects, compiler) ||
891 checkForStateChangeHelper(
892 n.getLastChild(), checkForNewObjects, compiler)) {
893 return true;
894 }
895
896 if (isGet(assignTarget)) {
897 // If the object being assigned to is a local object, don't
898 // consider this a side-effect as it can't be referenced
899 // elsewhere. Don't do this recursively as the property might
900 // be an alias of another object, unlike a literal below.
901 Node current = assignTarget.getFirstChild();
902 if (evaluatesToLocalValue(current)) {
903 return false;
904 }
905
906 // A literal value as defined by "isLiteralValue" is guaranteed
907 // not to be an alias, or any components which are aliases of
908 // other objects.
909 // If the root object is a literal don't consider this a
910 // side-effect.
911 while (isGet(current)) {
912 current = current.getFirstChild();
913 }
914
915 return !isLiteralValue(current, true);
916 } else {
917 // TODO(johnlenz): remove this code and make this an exception. This
918 // is here only for legacy reasons, the AST is not valid but
919 // preserve existing behavior.
920 return !isLiteralValue(assignTarget, true);
921 }
922 }
923
924 return true;
925 }
926
927 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
928 if (checkForStateChangeHelper(c, checkForNewObjects, compiler)) {
929 return true;
930 }
931 }
932
933 return false;
934 }
935
936 /**
937 * Do calls to this constructor have side effects?
938 *
939 * @param callNode - constructor call node
940 */
941 static boolean constructorCallHasSideEffects(Node callNode) {
942 return constructorCallHasSideEffects(callNode, null);
943 }
944
945 static boolean constructorCallHasSideEffects(
946 Node callNode, AbstractCompiler compiler) {
947 if (!callNode.isNew()) {
948 throw new IllegalStateException(
949 "Expected NEW node, got " + Token.name(callNode.getType()));
950 }
951
952 if (callNode.isNoSideEffectsCall()) {
953 return false;
954 }
955
956 Node nameNode = callNode.getFirstChild();
957 if (nameNode.isName() &&
958 CONSTRUCTORS_WITHOUT_SIDE_EFFECTS.contains(nameNode.getString())) {
959 return false;
960 }
961
962 return true;
963 }
964
965 // A list of built-in object creation or primitive type cast functions that
966 // can also be called as constructors but lack side-effects.
967 // TODO(johnlenz): consider adding an extern annotation for this.
968 private static final Set<String> BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS =
969 ImmutableSet.of(
970 "Object", "Array", "String", "Number", "Boolean", "RegExp", "Error");
971 private static final Set<String> OBJECT_METHODS_WITHOUT_SIDEEFFECTS =
972 ImmutableSet.of("toString", "valueOf");
973 private static final Set<String> REGEXP_METHODS =
974 ImmutableSet.of("test", "exec");
975 private static final Set<String> STRING_REGEXP_METHODS =
976 ImmutableSet.of("match", "replace", "search", "split");
977
978 /**
979 * Returns true if calls to this function have side effects.
980 *
981 * @param callNode - function call node
982 */
983 static boolean functionCallHasSideEffects(Node callNode) {
984 return functionCallHasSideEffects(callNode, null);
985 }
986
987 /**
988 * Returns true if calls to this function have side effects.
989 *
990 * @param callNode The call node to inspected.
991 * @param compiler A compiler object to provide program state changing
992 * context information. Can be null.
993 */
994 static boolean functionCallHasSideEffects(
995 Node callNode, @Nullable AbstractCompiler compiler) {
996 if (!callNode.isCall()) {
997 throw new IllegalStateException(
998 "Expected CALL node, got " + Token.name(callNode.getType()));
999 }
1000
1001 if (callNode.isNoSideEffectsCall()) {
1002 return false;
1003 }
1004
1005 Node nameNode = callNode.getFirstChild();
1006
1007 // Built-in functions with no side effects.
1008 if (nameNode.isName()) {
1009 String name = nameNode.getString();
1010 if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) {
1011 return false;
1012 }
1013 } else if (nameNode.isGetProp()) {
1014 if (callNode.hasOneChild()
1015 && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains(
1016 nameNode.getLastChild().getString())) {
1017 return false;
1018 }
1019
1020 if (callNode.isOnlyModifiesThisCall()
1021 && evaluatesToLocalValue(nameNode.getFirstChild())) {
1022 return false;
1023 }
1024
1025 // Math.floor has no side-effects.
1026 // TODO(nicksantos): This is a terrible terrible hack, until
1027 // I create a definitionProvider that understands namespacing.
1028 if (nameNode.getFirstChild().isName()) {
1029 if ("Math.floor".equals(nameNode.getQualifiedName())) {
1030 return false;
1031 }
1032 }
1033
1034 if (compiler != null && !compiler.hasRegExpGlobalReferences()) {
1035 if (nameNode.getFirstChild().isRegExp()
1036 && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) {
1037 return false;
1038 } else if (nameNode.getFirstChild().isString()
1039 && STRING_REGEXP_METHODS.contains(
1040 nameNode.getLastChild().getString())) {
1041 Node param = nameNode.getNext();
1042 if (param != null &&
1043 (param.isString() || param.isRegExp())) {
1044 return false;
1045 }
1046 }
1047 }
1048 }
1049
1050 return true;
1051 }
1052
1053 /**
1054 * @return Whether the call has a local result.
1055 */
1056 static boolean callHasLocalResult(Node n) {
1057 Preconditions.checkState(n.isCall());
1058 return (n.getSideEffectFlags() & Node.FLAG_LOCAL_RESULTS) > 0;
1059 }
1060
1061 /**
1062 * @return Whether the new has a local result.
1063 */
1064 static boolean newHasLocalResult(Node n) {
1065 Preconditions.checkState(n.isNew());
1066 return n.isOnlyModifiesThisCall();
1067 }
1068
1069 /**
1070 * Returns true if the current node's type implies side effects.
1071 *
1072 * This is a non-recursive version of the may have side effects
1073 * check; used to check wherever the current node's type is one of
1074 * the reason's why a subtree has side effects.
1075 */
1076 static boolean nodeTypeMayHaveSideEffects(Node n) {
1077 return nodeTypeMayHaveSideEffects(n, null);
1078 }
1079
1080 static boolean nodeTypeMayHaveSideEffects(Node n, AbstractCompiler compiler) {
1081 if (isAssignmentOp(n)) {
1082 return true;
1083 }
1084
1085 switch(n.getType()) {
1086 case Token.DELPROP:
1087 case Token.DEC:
1088 case Token.INC:
1089 case Token.THROW:
1090 return true;
1091 case Token.CALL:
1092 return NodeUtil.functionCallHasSideEffects(n, compiler);
1093 case Token.NEW:
1094 return NodeUtil.constructorCallHasSideEffects(n, compiler);
1095 case Token.NAME:
1096 // A variable definition.
1097 return n.hasChildren();
1098 default:
1099 return false;
1100 }
1101 }
1102
1103 /**
1104 * @return Whether the tree can be affected by side-effects or
1105 * has side-effects.
1106 */
1107 static boolean canBeSideEffected(Node n) {
1108 Set<String> emptySet = Collections.emptySet();
1109 return canBeSideEffected(n, emptySet);
1110 }
1111
1112 /**
1113 * @param knownConstants A set of names known to be constant value at
1114 * node 'n' (such as locals that are last written before n can execute).
1115 * @return Whether the tree can be affected by side-effects or
1116 * has side-effects.
1117 */
1118 static boolean canBeSideEffected(Node n, Set<String> knownConstants) {
1119 switch (n.getType()) {
1120 case Token.CALL:
1121 case Token.NEW:
1122 // Function calls or constructor can reference changed values.
1123 // TODO(johnlenz): Add some mechanism for determining that functions
1124 // are unaffected by side effects.
1125 return true;
1126 case Token.NAME:
1127 // Non-constant names values may have been changed.
1128 return !isConstantName(n)
1129 && !knownConstants.contains(n.getString());
1130
1131 // Properties on constant NAMEs can still be side-effected.
1132 case Token.GETPROP:
1133 case Token.GETELEM:
1134 return true;
1135
1136 case Token.FUNCTION:
1137 // Function expression are not changed by side-effects,
1138 // and function declarations are not part of expressions.
1139 Preconditions.checkState(isFunctionExpression(n));
1140 return false;
1141 }
1142
1143 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
1144 if (canBeSideEffected(c, knownConstants)) {
1145 return true;
1146 }
1147 }
1148
1149 return false;
1150 }
1151
1152 /*
1153 * 0 comma ,
1154 * 1 assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
1155 * 2 conditional ?:
1156 * 3 logical-or ||
1157 * 4 logical-and &&
1158 * 5 bitwise-or |
1159 * 6 bitwise-xor ^
1160 * 7 bitwise-and &
1161 * 8 equality == !=
1162 * 9 relational < <= > >=
1163 * 10 bitwise shift << >> >>>
1164 * 11 addition/subtraction + -
1165 * 12 multiply/divide * / %
1166 * 13 negation/increment ! ~ - ++ --
1167 * 14 call, member () [] .
1168 */
1169 static int precedence(int type) {
1170 switch (type) {
1171 case Token.COMMA: return 0;
1172 case Token.ASSIGN_BITOR:
1173 case Token.ASSIGN_BITXOR:
1174 case Token.ASSIGN_BITAND:
1175 case Token.ASSIGN_LSH:
1176 case Token.ASSIGN_RSH:
1177 case Token.ASSIGN_URSH:
1178 case Token.ASSIGN_ADD:
1179 case Token.ASSIGN_SUB:
1180 case Token.ASSIGN_MUL:
1181 case Token.ASSIGN_DIV:
1182 case Token.ASSIGN_MOD:
1183 case Token.ASSIGN: return 1;
1184 case Token.HOOK: return 2; // ?: operator
1185 case Token.OR: return 3;
1186 case Token.AND: return 4;
1187 case Token.BITOR: return 5;
1188 case Token.BITXOR: return 6;
1189 case Token.BITAND: return 7;
1190 case Token.EQ:
1191 case Token.NE:
1192 case Token.SHEQ:
1193 case Token.SHNE: return 8;
1194 case Token.LT:
1195 case Token.GT:
1196 case Token.LE:
1197 case Token.GE:
1198 case Token.INSTANCEOF:
1199 case Token.IN: return 9;
1200 case Token.LSH:
1201 case Token.RSH:
1202 case Token.URSH: return 10;
1203 case Token.SUB:
1204 case Token.ADD: return 11;
1205 case Token.MUL:
1206 case Token.MOD:
1207 case Token.DIV: return 12;
1208 case Token.INC:
1209 case Token.DEC:
1210 case Token.NEW:
1211 case Token.DELPROP:
1212 case Token.TYPEOF:
1213 case Token.VOID:
1214 case Token.NOT:
1215 case Token.BITNOT:
1216 case Token.POS:
1217 case Token.NEG: return 13;
1218
1219 case Token.CALL:
1220 case Token.GETELEM:
1221 case Token.GETPROP:
1222 // Data values
1223 case Token.ARRAYLIT:
1224 case Token.EMPTY: // TODO(johnlenz): remove this.
1225 case Token.FALSE:
1226 case Token.FUNCTION:
1227 case Token.NAME:
1228 case Token.NULL:
1229 case Token.NUMBER:
1230 case Token.OBJECTLIT:
1231 case Token.REGEXP:
1232 case Token.STRING:
1233 case Token.STRING_KEY:
1234 case Token.THIS:
1235 case Token.TRUE:
1236 return 15;
1237 case Token.CAST:
1238 return 16;
1239
1240 default: throw new Error("Unknown precedence for " +
1241 Token.name(type) +
1242 " (type " + type + ")");
1243 }
1244 }
1245
1246 static boolean isUndefined(Node n) {
1247 switch (n.getType()) {
1248 case Token.VOID:
1249 return true;
1250 case Token.NAME:
1251 return n.getString().equals("undefined");
1252 }
1253 return false;
1254 }
1255
1256 static boolean isNullOrUndefined(Node n) {
1257 return n.isNull() || isUndefined(n);
1258 }
1259
1260 static final Predicate<Node> IMMUTABLE_PREDICATE = new Predicate<Node>() {
1261 @Override
1262 public boolean apply(Node n) {
1263 return isImmutableValue(n);
1264 }
1265 };
1266
1267 static boolean isImmutableResult(Node n) {
1268 return allResultsMatch(n, IMMUTABLE_PREDICATE);
1269 }
1270
1271 /**
1272 * Apply the supplied predicate against
1273 * all possible result Nodes of the expression.
1274 */
1275 static boolean allResultsMatch(Node n, Predicate<Node> p) {
1276 switch (n.getType()) {
1277 case Token.CAST:
1278 return allResultsMatch(n.getFirstChild(), p);
1279 case Token.ASSIGN:
1280 case Token.COMMA:
1281 return allResultsMatch(n.getLastChild(), p);
1282 case Token.AND:
1283 case Token.OR:
1284 return allResultsMatch(n.getFirstChild(), p)
1285 && allResultsMatch(n.getLastChild(), p);
1286 case Token.HOOK:
1287 return allResultsMatch(n.getFirstChild().getNext(), p)
1288 && allResultsMatch(n.getLastChild(), p);
1289 default:
1290 return p.apply(n);
1291 }
1292 }
1293
1294 /**
1295 * Apply the supplied predicate against
1296 * all possible result Nodes of the expression.
1297 */
1298 static boolean anyResultsMatch(Node n, Predicate<Node> p) {
1299 switch (n.getType()) {
1300 case Token.CAST:
1301 return anyResultsMatch(n.getFirstChild(), p);
1302 case Token.ASSIGN:
1303 case Token.COMMA:
1304 return anyResultsMatch(n.getLastChild(), p);
1305 case Token.AND:
1306 case Token.OR:
1307 return anyResultsMatch(n.getFirstChild(), p)
1308 || anyResultsMatch(n.getLastChild(), p);
1309 case Token.HOOK:
1310 return anyResultsMatch(n.getFirstChild().getNext(), p)
1311 || anyResultsMatch(n.getLastChild(), p);
1312 default:
1313 return p.apply(n);
1314 }
1315 }
1316
1317 static class NumbericResultPredicate implements Predicate<Node> {
1318 @Override
1319 public boolean apply(Node n) {
1320 return isNumericResultHelper(n);
1321 }
1322 }
1323
1324 static final NumbericResultPredicate NUMBERIC_RESULT_PREDICATE =
1325 new NumbericResultPredicate();
1326
1327 /**
1328 * Returns true if the result of node evaluation is always a number
1329 */
1330 static boolean isNumericResult(Node n) {
1331 return allResultsMatch(n, NUMBERIC_RESULT_PREDICATE);
1332 }
1333
1334 static boolean isNumericResultHelper(Node n) {
1335 switch (n.getType()) {
1336 case Token.ADD:
1337 return !mayBeString(n.getFirstChild())
1338 && !mayBeString(n.getLastChild());
1339 case Token.BITNOT:
1340 case Token.BITOR:
1341 case Token.BITXOR:
1342 case Token.BITAND:
1343 case Token.LSH:
1344 case Token.RSH:
1345 case Token.URSH:
1346 case Token.SUB:
1347 case Token.MUL:
1348 case Token.MOD:
1349 case Token.DIV:
1350 case Token.INC:
1351 case Token.DEC:
1352 case Token.POS:
1353 case Token.NEG:
1354 case Token.NUMBER:
1355 return true;
1356 case Token.NAME:
1357 String name = n.getString();
1358 if (name.equals("NaN")) {
1359 return true;
1360 }
1361 if (name.equals("Infinity")) {
1362 return true;
1363 }
1364 return false;
1365 default:
1366 return false;
1367 }
1368 }
1369
1370 static class BooleanResultPredicate implements Predicate<Node> {
1371 @Override
1372 public boolean apply(Node n) {
1373 return isBooleanResultHelper(n);
1374 }
1375 }
1376
1377 static final BooleanResultPredicate BOOLEAN_RESULT_PREDICATE =
1378 new BooleanResultPredicate();
1379
1380 /**
1381 * @return Whether the result of node evaluation is always a boolean
1382 */
1383 static boolean isBooleanResult(Node n) {
1384 return allResultsMatch(n, BOOLEAN_RESULT_PREDICATE);
1385 }
1386
1387 static boolean isBooleanResultHelper(Node n) {
1388 switch (n.getType()) {
1389 // Primitives
1390 case Token.TRUE:
1391 case Token.FALSE:
1392 // Comparisons
1393 case Token.EQ:
1394 case Token.NE:
1395 case Token.SHEQ:
1396 case Token.SHNE:
1397 case Token.LT:
1398 case Token.GT:
1399 case Token.LE:
1400 case Token.GE:
1401 // Queries
1402 case Token.IN:
1403 case Token.INSTANCEOF:
1404 // Inversion
1405 case Token.NOT:
1406 // delete operator returns a boolean.
1407 case Token.DELPROP:
1408 return true;
1409 default:
1410 return false;
1411 }
1412 }
1413
1414
1415
1416 static class MayBeStringResultPredicate implements Predicate<Node> {
1417 @Override
1418 public boolean apply(Node n) {
1419 return mayBeStringHelper(n);
1420 }
1421 }
1422
1423 static final MayBeStringResultPredicate MAY_BE_STRING_PREDICATE =
1424 new MayBeStringResultPredicate();
1425
1426 /**
1427 * @returns Whether the results is possibly a string.
1428 */
1429 static boolean mayBeString(Node n) {
1430 return mayBeString(n, true);
1431 }
1432
1433 static boolean mayBeString(Node n, boolean recurse) {
1434 if (recurse) {
1435 return anyResultsMatch(n, MAY_BE_STRING_PREDICATE);
1436 } else {
1437 return mayBeStringHelper(n);
1438 }
1439 }
1440
1441 static boolean mayBeStringHelper(Node n) {
1442 return !isNumericResult(n) && !isBooleanResult(n)
1443 && !isUndefined(n) && !n.isNull();
1444 }
1445
1446 /**
1447 * Returns true if the operator is associative.
1448 * e.g. (a * b) * c = a * (b * c)
1449 * Note: "+" is not associative because it is also the concatenation
1450 * for strings. e.g. "a" + (1 + 2) is not "a" + 1 + 2
1451 */
1452 static boolean isAssociative(int type) {
1453 switch (type) {
1454 case Token.MUL:
1455 case Token.AND:
1456 case Token.OR:
1457 case Token.BITOR:
1458 case Token.BITXOR:
1459 case Token.BITAND:
1460 return true;
1461 default:
1462 return false;
1463 }
1464 }
1465
1466 /**
1467 * Returns true if the operator is commutative.
1468 * e.g. (a * b) * c = c * (b * a)
1469 * Note 1: "+" is not commutative because it is also the concatenation
1470 * for strings. e.g. "a" + (1 + 2) is not "a" + 1 + 2
1471 * Note 2: only operations on literals and pure functions are commutative.
1472 */
1473 static boolean isCommutative(int type) {
1474 switch (type) {
1475 case Token.MUL:
1476 case Token.BITOR:
1477 case Token.BITXOR:
1478 case Token.BITAND:
1479 return true;
1480 default:
1481 return false;
1482 }
1483 }
1484
1485 static boolean isAssignmentOp(Node n) {
1486 switch (n.getType()){
1487 case Token.ASSIGN:
1488 case Token.ASSIGN_BITOR:
1489 case Token.ASSIGN_BITXOR:
1490 case Token.ASSIGN_BITAND:
1491 case Token.ASSIGN_LSH:
1492 case Token.ASSIGN_RSH:
1493 case Token.ASSIGN_URSH:
1494 case Token.ASSIGN_ADD:
1495 case Token.ASSIGN_SUB:
1496 case Token.ASSIGN_MUL:
1497 case Token.ASSIGN_DIV:
1498 case Token.ASSIGN_MOD:
1499 return true;
1500 }
1501 return false;
1502 }
1503
1504 static int getOpFromAssignmentOp(Node n) {
1505 switch (n.getType()){
1506 case Token.ASSIGN_BITOR:
1507 return Token.BITOR;
1508 case Token.ASSIGN_BITXOR:
1509 return Token.BITXOR;
1510 case Token.ASSIGN_BITAND:
1511 return Token.BITAND;
1512 case Token.ASSIGN_LSH:
1513 return Token.LSH;
1514 case Token.ASSIGN_RSH:
1515 return Token.RSH;
1516 case Token.ASSIGN_URSH:
1517 return Token.URSH;
1518 case Token.ASSIGN_ADD:
1519 return Token.ADD;
1520 case Token.ASSIGN_SUB:
1521 return Token.SUB;
1522 case Token.ASSIGN_MUL:
1523 return Token.MUL;
1524 case Token.ASSIGN_DIV:
1525 return Token.DIV;
1526 case Token.ASSIGN_MOD:
1527 return Token.MOD;
1528 }
1529 throw new IllegalArgumentException("Not an assignment op:" + n);
1530 }
1531
1532 /**
1533 * Determines if the given node contains a function statement or function
1534 * expression.
1535 */
1536 static boolean containsFunction(Node n) {
1537 return containsType(n, Token.FUNCTION);
1538 }
1539
1540 /**
1541 * Returns true if the shallow scope contains references to 'this' keyword
1542 */
1543 static boolean referencesThis(Node n) {
1544 Node start = (n.isFunction()) ? n.getLastChild() : n;
1545 return containsType(start, Token.THIS, MATCH_NOT_FUNCTION);
1546 }
1547
1548 /**
1549 * Is this a GETPROP or GETELEM node?
1550 */
1551 static boolean isGet(Node n) {
1552 return n.isGetProp() || n.isGetElem();
1553 }
1554
1555 /**
1556 * Is this node the name of a variable being declared?
1557 *
1558 * @param n The node
1559 * @return True if {@code n} is NAME and {@code parent} is VAR
1560 */
1561 static boolean isVarDeclaration(Node n) {
1562 // There is no need to verify that parent != null because a NAME node
1563 // always has a parent in a valid parse tree.
1564 return n.isName() && n.getParent().isVar();
1565 }
1566
1567 /**
1568 * For an assignment or variable declaration get the assigned value.
1569 * @return The value node representing the new value.
1570 */
1571 static Node getAssignedValue(Node n) {
1572 Preconditions.checkState(n.isName());
1573 Node parent = n.getParent();
1574 if (parent.isVar()) {
1575 return n.getFirstChild();
1576 } else if (parent.isAssign() && parent.getFirstChild() == n) {
1577 return n.getNext();
1578 } else {
1579 return null;
1580 }
1581 }
1582
1583 /**
1584 * Is this node an assignment expression statement?
1585 *
1586 * @param n The node
1587 * @return True if {@code n} is EXPR_RESULT and {@code n}'s
1588 * first child is ASSIGN
1589 */
1590 static boolean isExprAssign(Node n) {
1591 return n.isExprResult()
1592 && n.getFirstChild().isAssign();
1593 }
1594
1595 /**
1596 * Is this node a call expression statement?
1597 *
1598 * @param n The node
1599 * @return True if {@code n} is EXPR_RESULT and {@code n}'s
1600 * first child is CALL
1601 */
1602 static boolean isExprCall(Node n) {
1603 return n.isExprResult()
1604 && n.getFirstChild().isCall();
1605 }
1606
1607 /**
1608 * @return Whether the node represents a FOR-IN loop.
1609 */
1610 static boolean isForIn(Node n) {
1611 return n.isFor()
1612 && n.getChildCount() == 3;
1613 }
1614
1615 /**
1616 * Determines whether the given node is a FOR, DO, or WHILE node.
1617 */
1618 static boolean isLoopStructure(Node n) {
1619 switch (n.getType()) {
1620 case Token.FOR:
1621 case Token.DO:
1622 case Token.WHILE:
1623 return true;
1624 default:
1625 return false;
1626 }
1627 }
1628
1629 /**
1630 * @param n The node to inspect.
1631 * @return If the node, is a FOR, WHILE, or DO, it returns the node for
1632 * the code BLOCK, null otherwise.
1633 */
1634 static Node getLoopCodeBlock(Node n) {
1635 switch (n.getType()) {
1636 case Token.FOR:
1637 case Token.WHILE:
1638 return n.getLastChild();
1639 case Token.DO:
1640 return n.getFirstChild();
1641 default:
1642 return null;
1643 }
1644 }
1645
1646 /**
1647 * @return Whether the specified node has a loop parent that
1648 * is within the current scope.
1649 */
1650 static boolean isWithinLoop(Node n) {
1651 for (Node parent : n.getAncestors()) {
1652 if (NodeUtil.isLoopStructure(parent)) {
1653 return true;
1654 }
1655
1656 if (parent.isFunction()) {
1657 break;
1658 }
1659 }
1660 return false;
1661 }
1662
1663 /**
1664 * Determines whether the given node is a FOR, DO, WHILE, WITH, or IF node.
1665 */
1666 static boolean isControlStructure(Node n) {
1667 switch (n.getType()) {
1668 case Token.FOR:
1669 case Token.DO:
1670 case Token.WHILE:
1671 case Token.WITH:
1672 case Token.IF:
1673 case Token.LABEL:
1674 case Token.TRY:
1675 case Token.CATCH:
1676 case Token.SWITCH:
1677 case Token.CASE:
1678 case Token.DEFAULT_CASE:
1679 return true;
1680 default:
1681 return false;
1682 }
1683 }
1684
1685 /**
1686 * Determines whether the given node is code node for FOR, DO,
1687 * WHILE, WITH, or IF node.
1688 */
1689 static boolean isControlStructureCodeBlock(Node parent, Node n) {
1690 switch (parent.getType()) {
1691 case Token.FOR:
1692 case Token.WHILE:
1693 case Token.LABEL:
1694 case Token.WITH:
1695 return parent.getLastChild() == n;
1696 case Token.DO:
1697 return parent.getFirstChild() == n;
1698 case Token.IF:
1699 return parent.getFirstChild() != n;
1700 case Token.TRY:
1701 return parent.getFirstChild() == n || parent.getLastChild() == n;
1702 case Token.CATCH:
1703 return parent.getLastChild() == n;
1704 case Token.SWITCH:
1705 case Token.CASE:
1706 return parent.getFirstChild() != n;
1707 case Token.DEFAULT_CASE:
1708 return true;
1709 default:
1710 Preconditions.checkState(isControlStructure(parent));
1711 return false;
1712 }
1713 }
1714
1715 /**
1716 * Gets the condition of an ON_TRUE / ON_FALSE CFG edge.
1717 * @param n a node with an outgoing conditional CFG edge
1718 * @return the condition node or null if the condition is not obviously a node
1719 */
1720 static Node getConditionExpression(Node n) {
1721 switch (n.getType()) {
1722 case Token.IF:
1723 case Token.WHILE:
1724 return n.getFirstChild();
1725 case Token.DO:
1726 return n.getLastChild();
1727 case Token.FOR:
1728 switch (n.getChildCount()) {
1729 case 3:
1730 return null;
1731 case 4:
1732 return n.getFirstChild().getNext();
1733 }
1734 throw new IllegalArgumentException("malformed 'for' statement " + n);
1735 case Token.CASE:
1736 return null;
1737 }
1738 throw new IllegalArgumentException(n + " does not have a condition.");
1739 }
1740
1741 /**
1742 * @return Whether the node is of a type that contain other statements.
1743 */
1744 static boolean isStatementBlock(Node n) {
1745 return n.isScript() || n.isBlock();
1746 }
1747
1748 /**
1749 * @return Whether the node is used as a statement.
1750 */
1751 static boolean isStatement(Node n) {
1752 return isStatementParent(n.getParent());
1753 }
1754
1755 static boolean isStatementParent(Node parent) {
1756 // It is not possible to determine definitely if a node is a statement
1757 // or not if it is not part of the AST. A FUNCTION node can be
1758 // either part of an expression or a statement.
1759 Preconditions.checkState(parent != null);
1760 switch (parent.getType()) {
1761 case Token.SCRIPT:
1762 case Token.BLOCK:
1763 case Token.LABEL:
1764 return true;
1765 default:
1766 return false;
1767 }
1768 }
1769
1770 /** Whether the node is part of a switch statement. */
1771 static boolean isSwitchCase(Node n) {
1772 return n.isCase() || n.isDefaultCase();
1773 }
1774
1775 /**
1776 * @return Whether the name is a reference to a variable, function or
1777 * function parameter (not a label or a empty function expression name).
1778 */
1779 static boolean isReferenceName(Node n) {
1780 return n.isName() && !n.getString().isEmpty();
1781 }
1782
1783 /** Whether the child node is the FINALLY block of a try. */
1784 static boolean isTryFinallyNode(Node parent, Node child) {
1785 return parent.isTry() && parent.getChildCount() == 3
1786 && child == parent.getLastChild();
1787 }
1788
1789 /** Whether the node is a CATCH container BLOCK. */
1790 static boolean isTryCatchNodeContainer(Node n) {
1791 Node parent = n.getParent();
1792 return parent.isTry()
1793 && parent.getFirstChild().getNext() == n;
1794 }
1795
1796 /** Safely remove children while maintaining a valid node structure. */
1797 static void removeChild(Node parent, Node node) {
1798 if (isTryFinallyNode(parent, node)) {
1799 if (NodeUtil.hasCatchHandler(getCatchBlock(parent))) {
1800 // A finally can only be removed if there is a catch.
1801 parent.removeChild(node);
1802 } else {
1803 // Otherwise, only its children can be removed.
1804 node.detachChildren();
1805 }
1806 } else if (node.isCatch()) {
1807 // The CATCH can can only be removed if there is a finally clause.
1808 Node tryNode = node.getParent().getParent();
1809 Preconditions.checkState(NodeUtil.hasFinally(tryNode));
1810 node.detachFromParent();
1811 } else if (isTryCatchNodeContainer(node)) {
1812 // The container node itself can't be removed, but the contained CATCH
1813 // can if there is a 'finally' clause
1814 Node tryNode = node.getParent();
1815 Preconditions.checkState(NodeUtil.hasFinally(tryNode));
1816 node.detachChildren();
1817 } else if (node.isBlock()) {
1818 // Simply empty the block. This maintains source location and
1819 // "synthetic"-ness.
1820 node.detachChildren();
1821 } else if (isStatementBlock(parent)
1822 || isSwitchCase(node)) {
1823 // A statement in a block can simply be removed.
1824 parent.removeChild(node);
1825 } else if (parent.isVar()) {
1826 if (parent.hasMoreThanOneChild()) {
1827 parent.removeChild(node);
1828 } else {
1829 // Remove the node from the parent, so it can be reused.
1830 parent.removeChild(node);
1831 // This would leave an empty VAR, remove the VAR itself.
1832 removeChild(parent.getParent(), parent);
1833 }
1834 } else if (parent.isLabel()
1835 && node == parent.getLastChild()) {
1836 // Remove the node from the parent, so it can be reused.
1837 parent.removeChild(node);
1838 // A LABEL without children can not be referred to, remove it.
1839 removeChild(parent.getParent(), parent);
1840 } else if (parent.isFor()
1841 && parent.getChildCount() == 4) {
1842 // Only Token.FOR can have an Token.EMPTY other control structure
1843 // need something for the condition. Others need to be replaced
1844 // or the structure removed.
1845 parent.replaceChild(node, IR.empty());
1846 } else {
1847 throw new IllegalStateException("Invalid attempt to remove node: " +
1848 node.toString() + " of " + parent.toString());
1849 }
1850 }
1851
1852 /**
1853 * Add a finally block if one does not exist.
1854 */
1855 static void maybeAddFinally(Node tryNode) {
1856 Preconditions.checkState(tryNode.isTry());
1857 if (!NodeUtil.hasFinally(tryNode)) {
1858 tryNode.addChildrenToBack(IR.block().srcref(tryNode));
1859 }
1860 }
1861
1862 /**
1863 * Merge a block with its parent block.
1864 * @return Whether the block was removed.
1865 */
1866 static boolean tryMergeBlock(Node block) {
1867 Preconditions.checkState(block.isBlock());
1868 Node parent = block.getParent();
1869 // Try to remove the block if its parent is a block/script or if its
1870 // parent is label and it has exactly one child.
1871 if (isStatementBlock(parent)) {
1872 Node previous = block;
1873 while (block.hasChildren()) {
1874 Node child = block.removeFirstChild();
1875 parent.addChildAfter(child, previous);
1876 previous = child;
1877 }
1878 parent.removeChild(block);
1879 return true;
1880 } else {
1881 return false;
1882 }
1883 }
1884
1885 /**
1886 * @param node A node
1887 * @return Whether the call is a NEW or CALL node.
1888 */
1889 static boolean isCallOrNew(Node node) {
1890 return node.isCall() || node.isNew();
1891 }
1892
1893 /**
1894 * Return a BLOCK node for the given FUNCTION node.
1895 */
1896 static Node getFunctionBody(Node fn) {
1897 Preconditions.checkArgument(fn.isFunction());
1898 return fn.getLastChild();
1899 }
1900
1901 /**
1902 * Is this node a function declaration? A function declaration is a function
1903 * that has a name that is added to the current scope (i.e. a function that
1904 * is not part of a expression; see {@link #isFunctionExpression}).
1905 */
1906 static boolean isFunctionDeclaration(Node n) {
1907 return n.isFunction() && isStatement(n);
1908 }
1909
1910 /**
1911 * Is this node a hoisted function declaration? A function declaration in the
1912 * scope root is hoisted to the top of the scope.
1913 * See {@link #isFunctionDeclaration}).
1914 */
1915 static boolean isHoistedFunctionDeclaration(Node n) {
1916 return isFunctionDeclaration(n)
1917 && (n.getParent().isScript()
1918 || n.getParent().getParent().isFunction());
1919 }
1920
1921 /**
1922 * Is a FUNCTION node an function expression? An function expression is one
1923 * that has either no name or a name that is not added to the current scope.
1924 *
1925 * <p>Some examples of function expressions:
1926 * <pre>
1927 * (function () {})
1928 * (function f() {})()
1929 * [ function f() {} ]
1930 * var f = function f() {};
1931 * for (function f() {};;) {}
1932 * </pre>
1933 *
1934 * <p>Some examples of functions that are <em>not</em> expressions:
1935 * <pre>
1936 * function f() {}
1937 * if (x); else function f() {}
1938 * for (;;) { function f() {} }
1939 * </pre>
1940 *
1941 * @param n A node
1942 * @return Whether n is an function used within an expression.
1943 */
1944 static boolean isFunctionExpression(Node n) {
1945 return n.isFunction() && !isStatement(n);
1946 }
1947
1948 /**
1949 * Returns whether this is a bleeding function (an anonymous named function
1950 * that bleeds into the inner scope).
1951 */
1952 static boolean isBleedingFunctionName(Node n) {
1953 return n.isName() && !n.getString().isEmpty() &&
1954 isFunctionExpression(n.getParent());
1955 }
1956
1957 /**
1958 * Determines if a node is a function expression that has an empty body.
1959 *
1960 * @param node a node
1961 * @return whether the given node is a function expression that is empty
1962 */
1963 static boolean isEmptyFunctionExpression(Node node) {
1964 return isFunctionExpression(node) && isEmptyBlock(node.getLastChild());
1965 }
1966
1967 /**
1968 * Determines if a function takes a variable number of arguments by
1969 * looking for references to the "arguments" var_args object.
1970 */
1971 static boolean isVarArgsFunction(Node function) {
1972 // TODO(johnlenz): rename this function
1973 Preconditions.checkArgument(function.isFunction());
1974 return isNameReferenced(
1975 function.getLastChild(),
1976 "arguments",
1977 MATCH_NOT_FUNCTION);
1978 }
1979
1980 /**
1981 * @return Whether node is a call to methodName.
1982 * a.f(...)
1983 * a['f'](...)
1984 */
1985 static boolean isObjectCallMethod(Node callNode, String methodName) {
1986 if (callNode.isCall()) {
1987 Node functionIndentifyingExpression = callNode.getFirstChild();
1988 if (isGet(functionIndentifyingExpression)) {
1989 Node last = functionIndentifyingExpression.getLastChild();
1990 if (last != null && last.isString()) {
1991 String propName = last.getString();
1992 return (propName.equals(methodName));
1993 }
1994 }
1995 }
1996 return false;
1997 }
1998
1999
2000 /**
2001 * @return Whether the callNode represents an expression in the form of:
2002 * x.call(...)
2003 * x['call'](...)
2004 */
2005 static boolean isFunctionObjectCall(Node callNode) {
2006 return isObjectCallMethod(callNode, "call");
2007 }
2008
2009 /**
2010 * @return Whether the callNode represents an expression in the form of:
2011 * x.apply(...)
2012 * x['apply'](...)
2013 */
2014 static boolean isFunctionObjectApply(Node callNode) {
2015 return isObjectCallMethod(callNode, "apply");
2016 }
2017
2018 /**
2019 * Determines whether this node is strictly on the left hand side of an assign
2020 * or var initialization. Notably, this does not include all L-values, only
2021 * statements where the node is used only as an L-value.
2022 *
2023 * @param n The node
2024 * @param parent Parent of the node
2025 * @return True if n is the left hand of an assign
2026 */
2027 static boolean isVarOrSimpleAssignLhs(Node n, Node parent) {
2028 return (parent.isAssign() && parent.getFirstChild() == n) ||
2029 parent.isVar();
2030 }
2031
2032 /**
2033 * Determines whether this node is used as an L-value. Notice that sometimes
2034 * names are used as both L-values and R-values.
2035 *
2036 * We treat "var x;" as a pseudo-L-value, which kind of makes sense if you
2037 * treat it as "assignment to 'undefined' at the top of the scope". But if
2038 * we're honest with ourselves, it doesn't make sense, and we only do this
2039 * because it makes sense to treat this as syntactically similar to
2040 * "var x = 0;".
2041 *
2042 * @param n The node
2043 * @return True if n is an L-value.
2044 */
2045 public static boolean isLValue(Node n) {
2046 Preconditions.checkArgument(n.isName() || n.isGetProp() ||
2047 n.isGetElem());
2048 Node parent = n.getParent();
2049 if (parent == null) {
2050 return false;
2051 }
2052 return (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n)
2053 || (NodeUtil.isForIn(parent) && parent.getFirstChild() == n)
2054 || parent.isVar()
2055 || (parent.isFunction() && parent.getFirstChild() == n)
2056 || parent.isDec()
2057 || parent.isInc()
2058 || parent.isParamList()
2059 || parent.isCatch();
2060 }
2061
2062 /**
2063 * Determines whether a node represents an object literal key
2064 * (e.g. key1 in {key1: value1, key2: value2}).
2065 *
2066 * @param node A node
2067 */
2068 static boolean isObjectLitKey(Node node) {
2069 switch (node.getType()) {
2070 case Token.STRING_KEY:
2071 case Token.GETTER_DEF:
2072 case Token.SETTER_DEF:
2073 return true;
2074 }
2075 return false;
2076 }
2077
2078 /**
2079 * Get the name of an object literal key.
2080 *
2081 * @param key A node
2082 */
2083 static String getObjectLitKeyName(Node key) {
2084 switch (key.getType()) {
2085 case Token.STRING_KEY:
2086 case Token.GETTER_DEF:
2087 case Token.SETTER_DEF:
2088 return key.getString();
2089 }
2090 throw new IllegalStateException("Unexpected node type: " + key);
2091 }
2092
2093 /**
2094 * @param key A OBJECTLIT key node.
2095 * @return The type expected when using the key.
2096 */
2097 static JSType getObjectLitKeyTypeFromValueType(Node key, JSType valueType) {
2098 if (valueType != null) {
2099 switch (key.getType()) {
2100 case Token.GETTER_DEF:
2101 // GET must always return a function type.
2102 if (valueType.isFunctionType()) {
2103 FunctionType fntype = valueType.toMaybeFunctionType();
2104 valueType = fntype.getReturnType();
2105 } else {
2106 return null;
2107 }
2108 break;
2109 case Token.SETTER_DEF:
2110 if (valueType.isFunctionType()) {
2111 // SET must always return a function type.
2112 FunctionType fntype = valueType.toMaybeFunctionType();
2113 Node param = fntype.getParametersNode().getFirstChild();
2114 // SET function must always have one parameter.
2115 valueType = param.getJSType();
2116 } else {
2117 return null;
2118 }
2119 break;
2120 }
2121 }
2122 return valueType;
2123 }
2124
2125 /**
2126 * Determines whether a node represents an object literal get or set key
2127 * (e.g. key1 in {get key1() {}, set key2(a){}).
2128 *
2129 * @param node A node
2130 */
2131 static boolean isGetOrSetKey(Node node) {
2132 switch (node.getType()) {
2133 case Token.GETTER_DEF:
2134 case Token.SETTER_DEF:
2135 return true;
2136 }
2137 return false;
2138 }
2139
2140 /**
2141 * Converts an operator's token value (see {@link Token}) to a string
2142 * representation.
2143 *
2144 * @param operator the operator's token value to convert
2145 * @return the string representation or {@code null} if the token value is
2146 * not an operator
2147 */
2148 static String opToStr(int operator) {
2149 switch (operator) {
2150 case Token.BITOR: return "|";
2151 case Token.OR: return "||";
2152 case Token.BITXOR: return "^";
2153 case Token.AND: return "&&";
2154 case Token.BITAND: return "&";
2155 case Token.SHEQ: return "===";
2156 case Token.EQ: return "==";
2157 case Token.NOT: return "!";
2158 case Token.NE: return "!=";
2159 case Token.SHNE: return "!==";
2160 case Token.LSH: return "<<";
2161 case Token.IN: return "in";
2162 case Token.LE: return "<=";
2163 case Token.LT: return "<";
2164 case Token.URSH: return ">>>";
2165 case Token.RSH: return ">>";
2166 case Token.GE: return ">=";
2167 case Token.GT: return ">";
2168 case Token.MUL: return "*";
2169 case Token.DIV: return "/";
2170 case Token.MOD: return "%";
2171 case Token.BITNOT: return "~";
2172 case Token.ADD: return "+";
2173 case Token.SUB: return "-";
2174 case Token.POS: return "+";
2175 case Token.NEG: return "-";
2176 case Token.ASSIGN: return "=";
2177 case Token.ASSIGN_BITOR: return "|=";
2178 case Token.ASSIGN_BITXOR: return "^=";
2179 case Token.ASSIGN_BITAND: return "&=";
2180 case Token.ASSIGN_LSH: return "<<=";
2181 case Token.ASSIGN_RSH: return ">>=";
2182 case Token.ASSIGN_URSH: return ">>>=";
2183 case Token.ASSIGN_ADD: return "+=";
2184 case Token.ASSIGN_SUB: return "-=";
2185 case Token.ASSIGN_MUL: return "*=";
2186 case Token.ASSIGN_DIV: return "/=";
2187 case Token.ASSIGN_MOD: return "%=";
2188 case Token.VOID: return "void";
2189 case Token.TYPEOF: return "typeof";
2190 case Token.INSTANCEOF: return "instanceof";
2191 default: return null;
2192 }
2193 }
2194
2195 /**
2196 * Converts an operator's token value (see {@link Token}) to a string
2197 * representation or fails.
2198 *
2199 * @param operator the operator's token value to convert
2200 * @return the string representation
2201 * @throws Error if the token value is not an operator
2202 */
2203 static String opToStrNoFail(int operator) {
2204 String res = opToStr(operator);
2205 if (res == null) {
2206 throw new Error("Unknown op " + operator + ": " +
2207 Token.name(operator));
2208 }
2209 return res;
2210 }
2211
2212 /**
2213 * @return true if n or any of its children are of the specified type
2214 */
2215 static boolean containsType(Node node,
2216 int type,
2217 Predicate<Node> traverseChildrenPred) {
2218 return has(node, new MatchNodeType(type), traverseChildrenPred);
2219 }
2220
2221 /**
2222 * @return true if n or any of its children are of the specified type
2223 */
2224 static boolean containsType(Node node, int type) {
2225 return containsType(node, type, Predicates.<Node>alwaysTrue());
2226 }
2227
2228
2229 /**
2230 * Given a node tree, finds all the VAR declarations in that tree that are
2231 * not in an inner scope. Then adds a new VAR node at the top of the current
2232 * scope that redeclares them, if necessary.
2233 */
2234 static void redeclareVarsInsideBranch(Node branch) {
2235 Collection<Node> vars = getVarsDeclaredInBranch(branch);
2236 if (vars.isEmpty()) {
2237 return;
2238 }
2239
2240 Node parent = getAddingRoot(branch);
2241 for (Node nameNode : vars) {
2242 Node var = IR.var(
2243 IR.name(nameNode.getString())
2244 .srcref(nameNode))
2245 .srcref(nameNode);
2246 copyNameAnnotations(nameNode, var.getFirstChild());
2247 parent.addChildToFront(var);
2248 }
2249 }
2250
2251 /**
2252 * Copy any annotations that follow a named value.
2253 * @param source
2254 * @param destination
2255 */
2256 static void copyNameAnnotations(Node source, Node destination) {
2257 if (source.getBooleanProp(Node.IS_CONSTANT_NAME)) {
2258 destination.putBooleanProp(Node.IS_CONSTANT_NAME, true);
2259 }
2260 }
2261
2262 /**
2263 * Gets a Node at the top of the current scope where we can add new var
2264 * declarations as children.
2265 */
2266 private static Node getAddingRoot(Node n) {
2267 Node addingRoot = null;
2268 Node ancestor = n;
2269 while (null != (ancestor = ancestor.getParent())) {
2270 int type = ancestor.getType();
2271 if (type == Token.SCRIPT) {
2272 addingRoot = ancestor;
2273 break;
2274 } else if (type == Token.FUNCTION) {
2275 addingRoot = ancestor.getLastChild();
2276 break;
2277 }
2278 }
2279
2280 // make sure that the adding root looks ok
2281 Preconditions.checkState(addingRoot.isBlock() ||
2282 addingRoot.isScript());
2283 Preconditions.checkState(addingRoot.getFirstChild() == null ||
2284 !addingRoot.getFirstChild().isScript());
2285 return addingRoot;
2286 }
2287
2288 /**
2289 * Creates a node representing a qualified name.
2290 *
2291 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
2292 * @return A NAME or GETPROP node
2293 */
2294 public static Node newQualifiedNameNode(
2295 CodingConvention convention, String name) {
2296 int endPos = name.indexOf('.');
2297 if (endPos == -1) {
2298 return newName(convention, name);
2299 }
2300 Node node;
2301 String nodeName = name.substring(0, endPos);
2302 if ("this".equals(nodeName)) {
2303 node = IR.thisNode();
2304 } else {
2305 node = newName(convention, nodeName);
2306 }
2307 int startPos;
2308 do {
2309 startPos = endPos + 1;
2310 endPos = name.indexOf('.', startPos);
2311 String part = (endPos == -1
2312 ? name.substring(startPos)
2313 : name.substring(startPos, endPos));
2314 Node propNode = IR.string(part);
2315 if (convention.isConstantKey(part)) {
2316 propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
2317 }
2318 node = IR.getprop(node, propNode);
2319 } while (endPos != -1);
2320
2321 return node;
2322 }
2323
2324 /**
2325 * Creates a node representing a qualified name, copying over the source
2326 * location information from the basis node and assigning the given original
2327 * name to the node.
2328 *
2329 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
2330 * @param basisNode The node that represents the name as currently found in
2331 * the AST.
2332 * @param originalName The original name of the item being represented by the
2333 * NAME node. Used for debugging information.
2334 *
2335 * @return A NAME or GETPROP node
2336 */
2337 static Node newQualifiedNameNode(
2338 CodingConvention convention, String name, Node basisNode,
2339 String originalName) {
2340 Node node = newQualifiedNameNode(convention, name);
2341 setDebugInformation(node, basisNode, originalName);
2342 return node;
2343 }
2344
2345 /**
2346 * Gets the root node of a qualified name. Must be either NAME or THIS.
2347 */
2348 static Node getRootOfQualifiedName(Node qName) {
2349 for (Node current = qName; true;
2350 current = current.getFirstChild()) {
2351 if (current.isName() || current.isThis()) {
2352 return current;
2353 }
2354 Preconditions.checkState(current.isGetProp());
2355 }
2356 }
2357
2358 /**
2359 * Sets the debug information (source file info and original name)
2360 * on the given node.
2361 *
2362 * @param node The node on which to set the debug information.
2363 * @param basisNode The basis node from which to copy the source file info.
2364 * @param originalName The original name of the node.
2365 */
2366 static void setDebugInformation(Node node, Node basisNode,
2367 String originalName) {
2368 node.copyInformationFromForTree(basisNode);
2369 node.putProp(Node.ORIGINALNAME_PROP, originalName);
2370 }
2371
2372 private static Node newName(
2373 CodingConvention convention, String name) {
2374 Node nameNode = IR.name(name);
2375 if (convention.isConstant(name)) {
2376 nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
2377 }
2378 return nameNode;
2379 }
2380
2381 /**
2382 * Creates a new node representing an *existing* name, copying over the source
2383 * location information from the basis node.
2384 *
2385 * @param name The name for the new NAME node.
2386 * @param srcref The node that represents the name as currently found in
2387 * the AST.
2388 *
2389 * @return The node created.
2390 */
2391 static Node newName(CodingConvention convention, String name, Node srcref) {
2392 return newName(convention, name).srcref(srcref);
2393 }
2394
2395 /**
2396 * Creates a new node representing an *existing* name, copying over the source
2397 * location information from the basis node and assigning the given original
2398 * name to the node.
2399 *
2400 * @param name The name for the new NAME node.
2401 * @param basisNode The node that represents the name as currently found in
2402 * the AST.
2403 * @param originalName The original name of the item being represented by the
2404 * NAME node. Used for debugging information.
2405 *
2406 * @return The node created.
2407 */
2408 static Node newName(
2409 CodingConvention convention, String name,
2410 Node basisNode, String originalName) {
2411 Node nameNode = newName(convention, name, basisNode);
2412 nameNode.putProp(Node.ORIGINALNAME_PROP, originalName);
2413 return nameNode;
2414 }
2415
2416 /** Test if all characters in the string are in the Basic Latin (aka ASCII)
2417 * character set - that they have UTF-16 values equal to or below 0x7f.
2418 * This check can find which identifiers with Unicode characters need to be
2419 * escaped in order to allow resulting files to be processed by non-Unicode
2420 * aware UNIX tools and editors.
2421 * *
2422 * See http://en.wikipedia.org/wiki/Latin_characters_in_Unicode
2423 * for more on Basic Latin.
2424 *
2425 * @param s The string to be checked for ASCII-goodness.
2426 *
2427 * @return True if all characters in the string are in Basic Latin set.
2428 */
2429 static boolean isLatin(String s) {
2430 int len = s.length();
2431 for (int index = 0; index < len; index++) {
2432 char c = s.charAt(index);
2433 if (c > LARGEST_BASIC_LATIN) {
2434 return false;
2435 }
2436 }
2437 return true;
2438 }
2439
2440 /**
2441 * Determines whether the given name is a valid variable name.
2442 */
2443 static boolean isValidSimpleName(String name) {
2444 return TokenStream.isJSIdentifier(name) &&
2445 !TokenStream.isKeyword(name) &&
2446 // no Unicode escaped characters - some browsers are less tolerant
2447 // of Unicode characters that might be valid according to the
2448 // language spec.
2449 // Note that by this point, Unicode escapes have been converted
2450 // to UTF-16 characters, so we're only searching for character
2451 // values, not escapes.
2452 isLatin(name);
2453 }
2454
2455 /**
2456 * Determines whether the given name is a valid qualified name.
2457 */
2458 // TODO(nicksantos): This should be moved into a "Language" API,
2459 // so that the results are different for es5 and es3.
2460 public static boolean isValidQualifiedName(String name) {
2461 if (name.endsWith(".") || name.startsWith(".")) {
2462 return false;
2463 }
2464 String[] parts = name.split("\\.");
2465 for (String part : parts) {
2466 if (!isValidSimpleName(part)) {
2467 return false;
2468 }
2469 }
2470 return true;
2471 }
2472
2473 /**
2474 * Determines whether the given name can appear on the right side of
2475 * the dot operator. Many properties (like reserved words) cannot.
2476 */
2477 static boolean isValidPropertyName(String name) {
2478 return isValidSimpleName(name);
2479 }
2480
2481 private static class VarCollector implements Visitor {
2482 final Map<String, Node> vars = Maps.newLinkedHashMap();
2483
2484 @Override
2485 public void visit(Node n) {
2486 if (n.isName()) {
2487 Node parent = n.getParent();
2488 if (parent != null && parent.isVar()) {
2489 String name = n.getString();
2490 if (!vars.containsKey(name)) {
2491 vars.put(name, n);
2492 }
2493 }
2494 }
2495 }
2496 }
2497
2498 /**
2499 * Retrieves vars declared in the current node tree, excluding descent scopes.
2500 */
2501 static Collection<Node> getVarsDeclaredInBranch(Node root) {
2502 VarCollector collector = new VarCollector();
2503 visitPreOrder(
2504 root,
2505 collector,
2506 MATCH_NOT_FUNCTION);
2507 return collector.vars.values();
2508 }
2509
2510 /**
2511 * @return {@code true} if the node an assignment to a prototype property of
2512 * some constructor.
2513 */
2514 static boolean isPrototypePropertyDeclaration(Node n) {
2515 return isExprAssign(n) &&
2516 isPrototypeProperty(n.getFirstChild().getFirstChild());
2517 }
2518
2519 /**
2520 * @return Whether the node represents a qualified prototype property.
2521 */
2522 static boolean isPrototypeProperty(Node n) {
2523 String lhsString = n.getQualifiedName();
2524 return lhsString != null && lhsString.contains(".prototype.");
2525 }
2526
2527 /**
2528 * @return The class name part of a qualified prototype name.
2529 */
2530 static Node getPrototypeClassName(Node qName) {
2531 Node cur = qName;
2532 while (cur.isGetProp()) {
2533 if (cur.getLastChild().getString().equals("prototype")) {
2534 return cur.getFirstChild();
2535 } else {
2536 cur = cur.getFirstChild();
2537 }
2538 }
2539 return null;
2540 }
2541
2542 /**
2543 * @return The string property name part of a qualified prototype name.
2544 */
2545 static String getPrototypePropertyName(Node qName) {
2546 String qNameStr = qName.getQualifiedName();
2547 int prototypeIdx = qNameStr.lastIndexOf(".prototype.");
2548 int memberIndex = prototypeIdx + ".prototype".length() + 1;
2549 return qNameStr.substring(memberIndex);
2550 }
2551
2552 /**
2553 * Create a node for an empty result expression:
2554 * "void 0"
2555 */
2556 static Node newUndefinedNode(Node srcReferenceNode) {
2557 Node node = IR.voidNode(IR.number(0));
2558 if (srcReferenceNode != null) {
2559 node.copyInformationFromForTree(srcReferenceNode);
2560 }
2561 return node;
2562 }
2563
2564 /**
2565 * Create a VAR node containing the given name and initial value expression.
2566 */
2567 static Node newVarNode(String name, Node value) {
2568 Node nodeName = IR.name(name);
2569 if (value != null) {
2570 Preconditions.checkState(value.getNext() == null);
2571 nodeName.addChildToBack(value);
2572 nodeName.srcref(value);
2573 }
2574 Node var = IR.var(nodeName).srcref(nodeName);
2575
2576 return var;
2577 }
2578
2579 /**
2580 * A predicate for matching name nodes with the specified node.
2581 */
2582 private static class MatchNameNode implements Predicate<Node>{
2583 final String name;
2584
2585 MatchNameNode(String name){
2586 this.name = name;
2587 }
2588
2589 @Override
2590 public boolean apply(Node n) {
2591 return n.isName() && n.getString().equals(name);
2592 }
2593 }
2594
2595 /**
2596 * A predicate for matching nodes with the specified type.
2597 */
2598 static class MatchNodeType implements Predicate<Node>{
2599 final int type;
2600
2601 MatchNodeType(int type){
2602 this.type = type;
2603 }
2604
2605 @Override
2606 public boolean apply(Node n) {
2607 return n.getType() == type;
2608 }
2609 }
2610
2611
2612 /**
2613 * A predicate for matching var or function declarations.
2614 */
2615 static class MatchDeclaration implements Predicate<Node> {
2616 @Override
2617 public boolean apply(Node n) {
2618 return isFunctionDeclaration(n) || n.isVar();
2619 }
2620 }
2621
2622 /**
2623 * A predicate for matching anything except function nodes.
2624 */
2625 private static class MatchNotFunction implements Predicate<Node>{
2626 @Override
2627 public boolean apply(Node n) {
2628 return !n.isFunction();
2629 }
2630 }
2631
2632 static final Predicate<Node> MATCH_NOT_FUNCTION = new MatchNotFunction();
2633
2634 /**
2635 * A predicate for matching statements without exiting the current scope.
2636 */
2637 static class MatchShallowStatement implements Predicate<Node>{
2638 @Override
2639 public boolean apply(Node n) {
2640 Node parent = n.getParent();
2641 return n.isBlock()
2642 || (!n.isFunction() && (parent == null
2643 || isControlStructure(parent)
2644 || isStatementBlock(parent)));
2645 }
2646 }
2647
2648 /**
2649 * Finds the number of times a type is referenced within the node tree.
2650 */
2651 static int getNodeTypeReferenceCount(
2652 Node node, int type, Predicate<Node> traverseChildrenPred) {
2653 return getCount(node, new MatchNodeType(type), traverseChildrenPred);
2654 }
2655
2656 /**
2657 * Whether a simple name is referenced within the node tree.
2658 */
2659 static boolean isNameReferenced(Node node,
2660 String name,
2661 Predicate<Node> traverseChildrenPred) {
2662 return has(node, new MatchNameNode(name), traverseChildrenPred);
2663 }
2664
2665 /**
2666 * Whether a simple name is referenced within the node tree.
2667 */
2668 static boolean isNameReferenced(Node node, String name) {
2669 return isNameReferenced(node, name, Predicates.<Node>alwaysTrue());
2670 }
2671
2672 /**
2673 * Finds the number of times a simple name is referenced within the node tree.
2674 */
2675 static int getNameReferenceCount(Node node, String name) {
2676 return getCount(
2677 node, new MatchNameNode(name), Predicates.<Node>alwaysTrue());
2678 }
2679
2680 /**
2681 * @return Whether the predicate is true for the node or any of its children.
2682 */
2683 static boolean has(Node node,
2684 Predicate<Node> pred,
2685 Predicate<Node> traverseChildrenPred) {
2686 if (pred.apply(node)) {
2687 return true;
2688 }
2689
2690 if (!traverseChildrenPred.apply(node)) {
2691 return false;
2692 }
2693
2694 for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
2695 if (has(c, pred, traverseChildrenPred)) {
2696 return true;
2697 }
2698 }
2699
2700 return false;
2701 }
2702
2703 /**
2704 * @return The number of times the the predicate is true for the node
2705 * or any of its children.
2706 */
2707 static int getCount(
2708 Node n, Predicate<Node> pred, Predicate<Node> traverseChildrenPred) {
2709 int total = 0;
2710
2711 if (pred.apply(n)) {
2712 total++;
2713 }
2714
2715 if (traverseChildrenPred.apply(n)) {
2716 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
2717 total += getCount(c, pred, traverseChildrenPred);
2718 }
2719 }
2720
2721 return total;
2722 }
2723
2724 /**
2725 * Interface for use with the visit method.
2726 * @see #visit
2727 */
2728 static interface Visitor {
2729 void visit(Node node);
2730 }
2731
2732 /**
2733 * A pre-order traversal, calling Visitor.visit for each child matching
2734 * the predicate.
2735 */
2736 static void visitPreOrder(Node node,
2737 Visitor visitor,
2738 Predicate<Node> traverseChildrenPred) {
2739 visitor.visit(node);
2740
2741 if (traverseChildrenPred.apply(node)) {
2742 for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
2743 visitPreOrder(c, visitor, traverseChildrenPred);
2744 }
2745 }
2746 }
2747
2748 /**
2749 * A post-order traversal, calling Visitor.visit for each child matching
2750 * the predicate.
2751 */
2752 static void visitPostOrder(Node node,
2753 Visitor visitor,
2754 Predicate<Node> traverseChildrenPred) {
2755 if (traverseChildrenPred.apply(node)) {
2756 for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
2757 visitPostOrder(c, visitor, traverseChildrenPred);
2758 }
2759 }
2760
2761 visitor.visit(node);
2762 }
2763
2764 /**
2765 * @return Whether a TRY node has a finally block.
2766 */
2767 static boolean hasFinally(Node n) {
2768 Preconditions.checkArgument(n.isTry());
2769 return n.getChildCount() == 3;
2770 }
2771
2772 /**
2773 * @return The BLOCK node containing the CATCH node (if any)
2774 * of a TRY.
2775 */
2776 static Node getCatchBlock(Node n) {
2777 Preconditions.checkArgument(n.isTry());
2778 return n.getFirstChild().getNext();
2779 }
2780
2781 /**
2782 * @return Whether BLOCK (from a TRY node) contains a CATCH.
2783 * @see NodeUtil#getCatchBlock
2784 */
2785 static boolean hasCatchHandler(Node n) {
2786 Preconditions.checkArgument(n.isBlock());
2787 return n.hasChildren() && n.getFirstChild().isCatch();
2788 }
2789
2790 /**
2791 * @param fnNode The function.
2792 * @return The Node containing the Function parameters.
2793 */
2794 public static Node getFunctionParameters(Node fnNode) {
2795 // Function NODE: [ FUNCTION -> NAME, LP -> ARG1, ARG2, ... ]
2796 Preconditions.checkArgument(fnNode.isFunction());
2797 return fnNode.getFirstChild().getNext();
2798 }
2799
2800 /**
2801 * <p>Determines whether a variable is constant:
2802 * <ol>
2803 * <li>In Normalize, any name that matches the
2804 * {@link CodingConvention#isConstant(String)} is annotated with an
2805 * IS_CONSTANT_NAME property.
2806 * </ol>
2807 *
2808 * @param node A NAME or STRING node
2809 * @return True if a name node represents a constant variable
2810 */
2811 static boolean isConstantName(Node node) {
2812 return node.getBooleanProp(Node.IS_CONSTANT_NAME);
2813 }
2814
2815 /** Whether the given name is constant by coding convention. */
2816 static boolean isConstantByConvention(
2817 CodingConvention convention, Node node, Node parent) {
2818 if (parent.isGetProp() && node == parent.getLastChild()) {
2819 return convention.isConstantKey(node.getString());
2820 } else if (isObjectLitKey(node)) {
2821 return convention.isConstantKey(node.getString());
2822 } else if (node.isName()) {
2823 return convention.isConstant(node.getString());
2824 }
2825 return false;
2826 }
2827
2828 /**
2829 * Get the JSDocInfo for a function.
2830 */
2831 public static JSDocInfo getFunctionJSDocInfo(Node n) {
2832 Preconditions.checkState(n.isFunction());
2833 JSDocInfo fnInfo = n.getJSDocInfo();
2834 if (fnInfo == null && NodeUtil.isFunctionExpression(n)) {
2835 // Look for the info on other nodes.
2836 Node parent = n.getParent();
2837 if (parent.isAssign()) {
2838 // on ASSIGNs
2839 fnInfo = parent.getJSDocInfo();
2840 } else if (parent.isName()) {
2841 // on var NAME = function() { ... };
2842 fnInfo = parent.getParent().getJSDocInfo();
2843 }
2844 }
2845 return fnInfo;
2846 }
2847
2848 /**
2849 * @param n The node.
2850 * @return The source name property on the node or its ancestors.
2851 */
2852 public static String getSourceName(Node n) {
2853 String sourceName = null;
2854 while (sourceName == null && n != null) {
2855 sourceName = n.getSourceFileName();
2856 n = n.getParent();
2857 }
2858 return sourceName;
2859 }
2860
2861 /**
2862 * @param n The node.
2863 * @return The source name property on the node or its ancestors.
2864 */
2865 public static StaticSourceFile getSourceFile(Node n) {
2866 StaticSourceFile sourceName = null;
2867 while (sourceName == null && n != null) {
2868 sourceName = n.getStaticSourceFile();
2869 n = n.getParent();
2870 }
2871 return sourceName;
2872 }
2873
2874 /**
2875 * @param n The node.
2876 * @return The InputId property on the node or its ancestors.
2877 */
2878 public static InputId getInputId(Node n) {
2879 while (n != null && !n.isScript()) {
2880 n = n.getParent();
2881 }
2882
2883 return (n != null && n.isScript()) ? n.getInputId() : null;
2884 }
2885
2886 /**
2887 * A new CALL node with the "FREE_CALL" set based on call target.
2888 */
2889 static Node newCallNode(Node callTarget, Node... parameters) {
2890 boolean isFreeCall = !isGet(callTarget);
2891 Node call = IR.call(callTarget);
2892 call.putBooleanProp(Node.FREE_CALL, isFreeCall);
2893 for (Node parameter : parameters) {
2894 call.addChildToBack(parameter);
2895 }
2896 return call;
2897 }
2898
2899 /**
2900 * @return Whether the node is known to be a value that is not referenced
2901 * elsewhere.
2902 */
2903 static boolean evaluatesToLocalValue(Node value) {
2904 return evaluatesToLocalValue(value, Predicates.<Node>alwaysFalse());
2905 }
2906
2907 /**
2908 * @param locals A predicate to apply to unknown local values.
2909 * @return Whether the node is known to be a value that is not a reference
2910 * outside the expression scope.
2911 */
2912 static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) {
2913 switch (value.getType()) {
2914 case Token.CAST:
2915 return evaluatesToLocalValue(value.getFirstChild(), locals);
2916 case Token.ASSIGN:
2917 // A result that is aliased by a non-local name, is the effectively the
2918 // same as returning a non-local name, but this doesn't matter if the
2919 // value is immutable.
2920 return NodeUtil.isImmutableValue(value.getLastChild())
2921 || (locals.apply(value)
2922 && evaluatesToLocalValue(value.getLastChild(), locals));
2923 case Token.COMMA:
2924 return evaluatesToLocalValue(value.getLastChild(), locals);
2925 case Token.AND:
2926 case Token.OR:
2927 return evaluatesToLocalValue(value.getFirstChild(), locals)
2928 && evaluatesToLocalValue(value.getLastChild(), locals);
2929 case Token.HOOK:
2930 return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)
2931 && evaluatesToLocalValue(value.getLastChild(), locals);
2932 case Token.INC:
2933 case Token.DEC:
2934 if (value.getBooleanProp(Node.INCRDECR_PROP)) {
2935 return evaluatesToLocalValue(value.getFirstChild(), locals);
2936 } else {
2937 return true;
2938 }
2939 case Token.THIS:
2940 return locals.apply(value);
2941 case Token.NAME:
2942 return isImmutableValue(value) || locals.apply(value);
2943 case Token.GETELEM:
2944 case Token.GETPROP:
2945 // There is no information about the locality of object properties.
2946 return locals.apply(value);
2947 case Token.CALL:
2948 return callHasLocalResult(value)
2949 || isToStringMethodCall(value)
2950 || locals.apply(value);
2951 case Token.NEW:
2952 return newHasLocalResult(value)
2953 || locals.apply(value);
2954 case Token.FUNCTION:
2955 case Token.REGEXP:
2956 case Token.ARRAYLIT:
2957 case Token.OBJECTLIT:
2958 // Literals objects with non-literal children are allowed.
2959 return true;
2960 case Token.DELPROP:
2961 case Token.IN:
2962 // TODO(johnlenz): should IN operator be included in #isSimpleOperator?
2963 return true;
2964 default:
2965 // Other op force a local value:
2966 // x = '' + g (x is now an local string)
2967 // x -= g (x is now an local number)
2968 if (isAssignmentOp(value)
2969 || isSimpleOperator(value)
2970 || isImmutableValue(value)) {
2971 return true;
2972 }
2973
2974 throw new IllegalStateException(
2975 "Unexpected expression node" + value +
2976 "\n parent:" + value.getParent());
2977 }
2978 }
2979
2980 /**
2981 * Given the first sibling, this returns the nth
2982 * sibling or null if no such sibling exists.
2983 * This is like "getChildAtIndex" but returns null for non-existent indexes.
2984 */
2985 private static Node getNthSibling(Node first, int index) {
2986 Node sibling = first;
2987 while (index != 0 && sibling != null) {
2988 sibling = sibling.getNext();
2989 index--;
2990 }
2991 return sibling;
2992 }
2993
2994 /**
2995 * Given the function, this returns the nth
2996 * argument or null if no such parameter exists.
2997 */
2998 static Node getArgumentForFunction(Node function, int index) {
2999 Preconditions.checkState(function.isFunction());
3000 return getNthSibling(
3001 function.getFirstChild().getNext().getFirstChild(), index);
3002 }
3003
3004 /**
3005 * Given the new or call, this returns the nth
3006 * argument of the call or null if no such argument exists.
3007 */
3008 static Node getArgumentForCallOrNew(Node call, int index) {
3009 Preconditions.checkState(isCallOrNew(call));
3010 return getNthSibling(
3011 call.getFirstChild().getNext(), index);
3012 }
3013
3014 /**
3015 * Returns whether this is a target of a call or new.
3016 */
3017 static boolean isCallOrNewTarget(Node target) {
3018 Node parent = target.getParent();
3019 return parent != null
3020 && NodeUtil.isCallOrNew(parent)
3021 && parent.getFirstChild() == target;
3022 }
3023
3024 private static boolean isToStringMethodCall(Node call) {
3025 Node getNode = call.getFirstChild();
3026 if (isGet(getNode)) {
3027 Node propNode = getNode.getLastChild();
3028 return propNode.isString() && "toString".equals(propNode.getString());
3029 }
3030 return false;
3031 }
3032
3033 /** Find the best JSDoc for the given node. */
3034 static JSDocInfo getBestJSDocInfo(Node n) {
3035 JSDocInfo info = n.getJSDocInfo();
3036 if (info == null) {
3037 Node parent = n.getParent();
3038 if (parent == null) {
3039 return null;
3040 }
3041
3042 if (parent.isName()) {
3043 return getBestJSDocInfo(parent);
3044 } else if (parent.isAssign()) {
3045 return getBestJSDocInfo(parent);
3046 } else if (isObjectLitKey(parent)) {
3047 return parent.getJSDocInfo();
3048 } else if (parent.isFunction()) {
3049 return parent.getJSDocInfo();
3050 } else if (parent.isVar() && parent.hasOneChild()) {
3051 return parent.getJSDocInfo();
3052 } else if ((parent.isHook() && parent.getFirstChild() != n) ||
3053 parent.isOr() ||
3054 parent.isAnd() ||
3055 (parent.isComma() && parent.getFirstChild() != n)) {
3056 return getBestJSDocInfo(parent);
3057 } else if (parent.isCast()) {
3058 return parent.getJSDocInfo();
3059 }
3060 }
3061 return info;
3062 }
3063
3064 /** Find the l-value that the given r-value is being assigned to. */
3065 static Node getBestLValue(Node n) {
3066 Node parent = n.getParent();
3067 boolean isFunctionDeclaration = isFunctionDeclaration(n);
3068 if (isFunctionDeclaration) {
3069 return n.getFirstChild();
3070 } else if (parent.isName()) {
3071 return parent;
3072 } else if (parent.isAssign()) {
3073 return parent.getFirstChild();
3074 } else if (isObjectLitKey(parent)) {
3075 return parent;
3076 } else if (
3077 (parent.isHook() && parent.getFirstChild() != n) ||
3078 parent.isOr() ||
3079 parent.isAnd() ||
3080 (parent.isComma() && parent.getFirstChild() != n)) {
3081 return getBestLValue(parent);
3082 } else if (parent.isCast()) {
3083 return getBestLValue(parent);
3084 }
3085 return null;
3086 }
3087
3088 /** Gets the r-value of a node returned by getBestLValue. */
3089 static Node getRValueOfLValue(Node n) {
3090 Node parent = n.getParent();
3091 switch (parent.getType()) {
3092 case Token.ASSIGN:
3093 return n.getNext();
3094 case Token.VAR:
3095 return n.getFirstChild();
3096 case Token.FUNCTION:
3097 return parent;
3098 }
3099 return null;
3100 }
3101
3102 /** Get the owner of the given l-value node. */
3103 static Node getBestLValueOwner(@Nullable Node lValue) {
3104 if (lValue == null || lValue.getParent() == null) {
3105 return null;
3106 }
3107 if (isObjectLitKey(lValue)) {
3108 return getBestLValue(lValue.getParent());
3109 } else if (isGet(lValue)) {
3110 return lValue.getFirstChild();
3111 }
3112
3113 return null;
3114 }
3115
3116 /** Get the name of the given l-value node. */
3117 static String getBestLValueName(@Nullable Node lValue) {
3118 if (lValue == null || lValue.getParent() == null) {
3119 return null;
3120 }
3121 if (isObjectLitKey(lValue)) {
3122 Node owner = getBestLValue(lValue.getParent());
3123 if (owner != null) {
3124 String ownerName = getBestLValueName(owner);
3125 if (ownerName != null) {
3126 return ownerName + "." + getObjectLitKeyName(lValue);
3127 }
3128 }
3129 return null;
3130 }
3131 return lValue.getQualifiedName();
3132 }
3133
3134 /**
3135 * @returns false iff the result of the expression is not consumed.
3136 */
3137 static boolean isExpressionResultUsed(Node expr) {
3138 // TODO(johnlenz): consider sharing some code with trySimpleUnusedResult.
3139 Node parent = expr.getParent();
3140 switch (parent.getType()) {
3141 case Token.BLOCK:
3142 case Token.EXPR_RESULT:
3143 return false;
3144 case Token.CAST:
3145 return isExpressionResultUsed(parent);
3146 case Token.HOOK:
3147 case Token.AND:
3148 case Token.OR:
3149 return (expr == parent.getFirstChild())
3150 ? true : isExpressionResultUsed(parent);
3151 case Token.COMMA:
3152 Node gramps = parent.getParent();
3153 if (gramps.isCall() &&
3154 parent == gramps.getFirstChild()) {
3155 // Semantically, a direct call to eval is different from an indirect
3156 // call to an eval. See ECMA-262 S15.1.2.1. So it's OK for the first
3157 // expression to a comma to be a no-op if it's used to indirect
3158 // an eval. This we pretend that this is "used".
3159 if (expr == parent.getFirstChild() &&
3160 parent.getChildCount() == 2 &&
3161 expr.getNext().isName() &&
3162 "eval".equals(expr.getNext().getString())) {
3163 return true;
3164 }
3165 }
3166
3167 return (expr == parent.getFirstChild())
3168 ? false : isExpressionResultUsed(parent);
3169 case Token.FOR:
3170 if (!NodeUtil.isForIn(parent)) {
3171 // Only an expression whose result is in the condition part of the
3172 // expression is used.
3173 return (parent.getChildAtIndex(1) == expr);
3174 }
3175 break;
3176 }
3177 return true;
3178 }
3179
3180 /**
3181 * @param n The expression to check.
3182 * @return Whether the expression is unconditionally executed only once in the
3183 * containing execution scope.
3184 */
3185 static boolean isExecutedExactlyOnce(Node n) {
3186 inspect: do {
3187 Node parent = n.getParent();
3188 switch (parent.getType()) {
3189 case Token.IF:
3190 case Token.HOOK:
3191 case Token.AND:
3192 case Token.OR:
3193 if (parent.getFirstChild() != n) {
3194 return false;
3195 }
3196 // other ancestors may be conditional
3197 continue inspect;
3198 case Token.FOR:
3199 if (NodeUtil.isForIn(parent)) {
3200 if (parent.getChildAtIndex(1) != n) {
3201 return false;
3202 }
3203 } else {
3204 if (parent.getFirstChild() != n) {
3205 return false;
3206 }
3207 }
3208 // other ancestors may be conditional
3209 continue inspect;
3210 case Token.WHILE:
3211 case Token.DO:
3212 return false;
3213 case Token.TRY:
3214 // Consider all code under a try/catch to be conditionally executed.
3215 if (!hasFinally(parent) || parent.getLastChild() != n) {
3216 return false;
3217 }
3218 continue inspect;
3219 case Token.CASE:
3220 case Token.DEFAULT_CASE:
3221 return false;
3222 case Token.SCRIPT:
3223 case Token.FUNCTION:
3224 // Done, we've reached the scope root.
3225 break inspect;
3226 }
3227 } while ((n = n.getParent()) != null);
3228 return true;
3229 }
3230
3231 /**
3232 * @return An appropriate AST node for the boolean value.
3233 */
3234 static Node booleanNode(boolean value) {
3235 return value ? IR.trueNode() : IR.falseNode();
3236 }
3237
3238 /**
3239 * @return An appropriate AST node for the double value.
3240 */
3241 static Node numberNode(double value, Node srcref) {
3242 Node result;
3243 if (Double.isNaN(value)) {
3244 result = IR.name("NaN");
3245 } else if (value == Double.POSITIVE_INFINITY) {
3246 result = IR.name("Infinity");
3247 } else if (value == Double.NEGATIVE_INFINITY) {
3248 result = IR.neg(IR.name("Infinity"));
3249 } else {
3250 result = IR.number(value);
3251 }
3252 if (srcref != null) {
3253 result.srcrefTree(srcref);
3254 }
3255 return result;
3256 }
3257
3258 static boolean isNaN(Node n) {
3259 if ((n.isName() && n.getString().equals("NaN")) ||
3260 (n.getType() == Token.DIV &&
3261 n.getFirstChild().isNumber() && n.getFirstChild().getDouble() == 0 &&
3262 n.getLastChild().isNumber() && n.getLastChild().getDouble() == 0)) {
3263 return true;
3264 }
3265 return false;
3266 }
3267 }