-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
NodeUtil.java
4910 lines (4465 loc) · 139 KB
/
NodeUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2004 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.InputId;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.StaticSourceFile;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TokenStream;
import com.google.javascript.rhino.TokenUtil;
import com.google.javascript.rhino.TypeI;
import com.google.javascript.rhino.dtoa.DToA;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.TernaryValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* NodeUtil contains generally useful AST utilities.
*
* @author nicksantos@google.com (Nick Santos)
* @author johnlenz@google.com (John Lenz)
*/
public final class NodeUtil {
public static final String EXTERN_OBJECT_PROPERTY_STRING =
"JSCompiler_ObjectPropertyString";
static final long MAX_POSITIVE_INTEGER_NUMBER = 1L << 53;
static final String JSC_PROPERTY_NAME_FN = "JSCompiler_renameProperty";
static final char LARGEST_BASIC_LATIN = 0x7f;
/** the set of builtin constructors that don't have side effects. */
private static final ImmutableSet<String> CONSTRUCTORS_WITHOUT_SIDE_EFFECTS =
ImmutableSet.of("Array", "Date", "Error", "Object", "RegExp", "XMLHttpRequest");
// Utility class; do not instantiate.
private NodeUtil() {}
static boolean isImpureTrue(Node n) {
return getImpureBooleanValue(n) == TernaryValue.TRUE;
}
/**
* Gets the boolean value of a node that represents a expression. This method
* effectively emulates the <code>Boolean()</code> JavaScript cast function.
* Note: unlike getPureBooleanValue this function does not return UNKNOWN
* for expressions with side-effects.
*/
static TernaryValue getImpureBooleanValue(Node n) {
switch (n.getToken()) {
case ASSIGN:
case COMMA:
// For ASSIGN and COMMA the value is the value of the RHS.
return getImpureBooleanValue(n.getLastChild());
case NOT:
TernaryValue value = getImpureBooleanValue(n.getLastChild());
return value.not();
case AND: {
TernaryValue lhs = getImpureBooleanValue(n.getFirstChild());
TernaryValue rhs = getImpureBooleanValue(n.getLastChild());
return lhs.and(rhs);
}
case OR: {
TernaryValue lhs = getImpureBooleanValue(n.getFirstChild());
TernaryValue rhs = getImpureBooleanValue(n.getLastChild());
return lhs.or(rhs);
}
case HOOK: {
TernaryValue trueValue = getImpureBooleanValue(
n.getSecondChild());
TernaryValue falseValue = getImpureBooleanValue(n.getLastChild());
if (trueValue.equals(falseValue)) {
return trueValue;
} else {
return TernaryValue.UNKNOWN;
}
}
case NEW:
case ARRAYLIT:
case OBJECTLIT:
// ignoring side-effects
return TernaryValue.TRUE;
case VOID:
return TernaryValue.FALSE;
default:
return getPureBooleanValue(n);
}
}
/**
* Gets the boolean value of a node that represents a literal. This method
* effectively emulates the <code>Boolean()</code> JavaScript cast function
* except it return UNKNOWN for known values with side-effects, use
* getImpureBooleanValue if you don't care about side-effects.
*/
static TernaryValue getPureBooleanValue(Node n) {
switch (n.getToken()) {
case TEMPLATELIT:
if (n.hasOneChild()) {
return TernaryValue.forBoolean(!n.getFirstChild().getString().isEmpty());
}
break;
case STRING:
return TernaryValue.forBoolean(n.getString().length() > 0);
case NUMBER:
return TernaryValue.forBoolean(n.getDouble() != 0);
case NOT:
return getPureBooleanValue(n.getLastChild()).not();
case NULL:
case FALSE:
return TernaryValue.FALSE;
case VOID:
if (!mayHaveSideEffects(n.getFirstChild())) {
return TernaryValue.FALSE;
}
break;
case NAME:
String name = n.getString();
if ("undefined".equals(name)
|| "NaN".equals(name)) {
// We assume here that programs don't change the value of the keyword
// undefined to something other than the value undefined.
return TernaryValue.FALSE;
} else if ("Infinity".equals(name)) {
return TernaryValue.TRUE;
}
break;
case TRUE:
case REGEXP:
return TernaryValue.TRUE;
case FUNCTION:
case CLASS:
case NEW:
case ARRAYLIT:
case OBJECTLIT:
if (!mayHaveSideEffects(n)) {
return TernaryValue.TRUE;
}
break;
default:
break;
}
return TernaryValue.UNKNOWN;
}
/**
* Gets the value of a node as a String, or null if it cannot be converted.
* When it returns a non-null String, this method effectively emulates the
* <code>String()</code> JavaScript cast function.
*/
public static String getStringValue(Node n) {
// TODO(user): regex literals as well.
switch (n.getToken()) {
case STRING:
case STRING_KEY:
return n.getString();
case NAME:
String name = n.getString();
if ("undefined".equals(name)
|| "Infinity".equals(name)
|| "NaN".equals(name)) {
return name;
}
break;
case NUMBER:
return DToA.numberToString(n.getDouble());
case FALSE:
return "false";
case TRUE:
return "true";
case NULL:
return "null";
case VOID:
return "undefined";
case NOT:
TernaryValue child = getPureBooleanValue(n.getFirstChild());
if (child != TernaryValue.UNKNOWN) {
return child.toBoolean(true) ? "false" : "true"; // reversed.
}
break;
case ARRAYLIT:
return arrayToString(n);
case OBJECTLIT:
return "[object Object]";
default:
break;
}
return null;
}
/**
* When converting arrays to string using Array.prototype.toString or
* Array.prototype.join, the rules for conversion to String are different
* than converting each element individually. Specifically, "null" and
* "undefined" are converted to an empty string.
* @param n A node that is a member of an Array.
* @return The string representation.
*/
static String getArrayElementStringValue(Node n) {
return (NodeUtil.isNullOrUndefined(n) || n.isEmpty())
? "" : getStringValue(n);
}
static String arrayToString(Node literal) {
Node first = literal.getFirstChild();
StringBuilder result = new StringBuilder();
for (Node n = first; n != null; n = n.getNext()) {
String childValue = getArrayElementStringValue(n);
if (childValue == null) {
return null;
}
if (n != first) {
result.append(',');
}
result.append(childValue);
}
return result.toString();
}
public static Double getNumberValue(Node n) {
return getNumberValue(n, false);
}
/**
* Gets the value of a node as a Number, or null if it cannot be converted.
* When it returns a non-null Double, this method effectively emulates the
* <code>Number()</code> JavaScript cast function.
*
* @param n The node.
* @param useType If true, return 0.0 if the type is null, and NaN if the type is undefined.
* @return The value of a node as a Number, or null if it cannot be converted.
*/
static Double getNumberValue(Node n, boolean useType) {
switch (n.getToken()) {
case TRUE:
return 1.0;
case FALSE:
case NULL:
return 0.0;
case NUMBER:
return n.getDouble();
case VOID:
if (mayHaveSideEffects(n.getFirstChild())) {
return null;
} else {
return Double.NaN;
}
case NAME:
// Check for known constants
String name = n.getString();
if (name.equals("undefined")) {
return Double.NaN;
}
if (name.equals("NaN")) {
return Double.NaN;
}
if (name.equals("Infinity")) {
return Double.POSITIVE_INFINITY;
}
if (useType) {
TypeI type = n.getTypeI();
if (type != null) {
if (type.isVoidType()) {
return Double.NaN;
} else if (type.isNullType()) {
return 0.0;
}
}
}
return null;
case NEG:
if (n.hasOneChild() && n.getFirstChild().isName()
&& n.getFirstChild().getString().equals("Infinity")) {
return Double.NEGATIVE_INFINITY;
}
return null;
case NOT:
TernaryValue child = getPureBooleanValue(n.getFirstChild());
if (child != TernaryValue.UNKNOWN) {
return child.toBoolean(true) ? 0.0 : 1.0; // reversed.
}
break;
case STRING:
return getStringNumberValue(n.getString());
case ARRAYLIT:
case OBJECTLIT:
String value = getStringValue(n);
return value != null ? getStringNumberValue(value) : null;
default:
break;
}
return null;
}
static Double getStringNumberValue(String rawJsString) {
if (rawJsString.contains("\u000b")) {
// vertical tab is not always whitespace
return null;
}
String s = trimJsWhiteSpace(rawJsString);
// return ScriptRuntime.toNumber(s);
if (s.isEmpty()) {
return 0.0;
}
if (s.length() > 2
&& s.charAt(0) == '0'
&& (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
// Attempt to convert hex numbers.
try {
return Double.valueOf(Integer.parseInt(s.substring(2), 16));
} catch (NumberFormatException e) {
return Double.NaN;
}
}
if (s.length() > 3
&& (s.charAt(0) == '-' || s.charAt(0) == '+')
&& s.charAt(1) == '0'
&& (s.charAt(2) == 'x' || s.charAt(2) == 'X')) {
// hex numbers with explicit signs vary between browsers.
return null;
}
// Firefox and IE treat the "Infinity" differently. Firefox is case
// insensitive, but IE treats "infinity" as NaN. So leave it alone.
if (s.equals("infinity")
|| s.equals("-infinity")
|| s.equals("+infinity")) {
return null;
}
try {
return Double.parseDouble(s);
} catch (NumberFormatException e) {
return Double.NaN;
}
}
static String trimJsWhiteSpace(String s) {
int start = 0;
int end = s.length();
while (end > 0
&& TokenUtil.isStrWhiteSpaceChar(s.charAt(end - 1)) == TernaryValue.TRUE) {
end--;
}
while (start < end
&& TokenUtil.isStrWhiteSpaceChar(s.charAt(start)) == TernaryValue.TRUE) {
start++;
}
return s.substring(start, end);
}
/**
* @param n A function or class node.
* @return The name of the given function or class, if it has one.
*/
public static String getName(Node n) {
Node nameNode = getNameNode(n);
return nameNode == null ? null : nameNode.getQualifiedName();
}
/**
* Gets the node of a function or class's name. This method recognizes five forms:
* <ul>
* <li>{@code class name {...}}</li>
* <li>{@code var name = class {...}}</li>
* <li>{@code qualified.name = class {...}}</li>
* <li>{@code var name2 = class name1 {...}}</li>
* <li>{@code qualified.name2 = class name1 {...}}</li>
* </ul>
* In two last cases with named function expressions, the second name is
* returned (the variable or qualified name).
*
* @param n A function or class node
* @return the node best representing the class's name
*/
public static Node getNameNode(Node n) {
Preconditions.checkState(n.isFunction() || n.isClass());
Node parent = n.getParent();
switch (parent.getToken()) {
case NAME:
// var name = function() ...
// var name2 = function name1() ...
return parent;
case ASSIGN: {
// qualified.name = function() ...
// qualified.name2 = function name1() ...
Node firstChild = parent.getFirstChild();
return firstChild.isQualifiedName() ? firstChild : null;
}
default:
// function name() ...
Node funNameNode = n.getFirstChild();
// Don't return the name node for anonymous functions/classes.
// TODO(tbreisacher): Currently we do two kinds of "empty" checks because
// anonymous classes have an EMPTY name node while anonymous functions
// have a STRING node with an empty string. Consider making these the same.
return (funNameNode.isEmpty() || funNameNode.getString().isEmpty())
? null : funNameNode;
}
}
/** Set the given function/class node to an empty name */
public static void removeName(Node n) {
Preconditions.checkState(n.isFunction() || n.isClass());
Node originalName = n.getFirstChild();
Node emptyName = n.isFunction() ? IR.name("") : IR.empty();
n.replaceChild(originalName, emptyName.useSourceInfoFrom(originalName));
}
/**
* Gets the function's name. This method recognizes the forms:
* <ul>
* <li>{@code {'name': function() ...}}</li>
* <li>{@code {name: function() ...}}</li>
* <li>{@code function name() ...}</li>
* <li>{@code var name = function() ...}</li>
* <li>{@code var obj = {name() {} ...}}</li>
* <li>{@code qualified.name = function() ...}</li>
* <li>{@code var name2 = function name1() ...}</li>
* <li>{@code qualified.name2 = function name1() ...}</li>
* </ul>
*
* @param n a node whose type is {@link Token#FUNCTION}
* @return the function's name, or {@code null} if it has no name
*/
public static String getNearestFunctionName(Node n) {
if (!n.isFunction()) {
return null;
}
String name = getName(n);
if (name != null) {
return name;
}
// Check for the form { 'x' : function() { }} and {x() {}}
Node parent = n.getParent();
switch (parent.getToken()) {
case MEMBER_FUNCTION_DEF:
case SETTER_DEF:
case GETTER_DEF:
case STRING_KEY:
// Return the name of the literal's key.
return parent.getString();
case NUMBER:
return getStringValue(parent);
default:
break;
}
return null;
}
public static Node getClassMembers(Node n) {
Preconditions.checkArgument(n.isClass());
return n.getLastChild();
}
/**
* Returns true if this is an immutable value.
*/
static boolean isImmutableValue(Node n) {
// TODO(johnlenz): rename this function. It is currently being used
// in two disjoint cases:
// 1) We only care about the result of the expression
// (in which case NOT here should return true)
// 2) We care that expression is a side-effect free and can't
// be side-effected by other expressions.
// This should only be used to say the value is immuable and
// hasSideEffects and canBeSideEffected should be used for the other case.
switch (n.getToken()) {
case STRING:
case NUMBER:
case NULL:
case TRUE:
case FALSE:
return true;
case CAST:
case NOT:
case VOID:
case NEG:
return isImmutableValue(n.getFirstChild());
case NAME:
String name = n.getString();
// We assume here that programs don't change the value of the keyword
// undefined to something other than the value undefined.
return "undefined".equals(name) || "Infinity".equals(name) || "NaN".equals(name);
default:
break;
}
return false;
}
/**
* Returns true if the operator on this node is symmetric
*/
static boolean isSymmetricOperation(Node n) {
switch (n.getToken()) {
case EQ: // equal
case NE: // not equal
case SHEQ: // exactly equal
case SHNE: // exactly not equal
case MUL: // multiply, unlike add it only works on numbers
// or results NaN if any of the operators is not a number
return true;
default:
break;
}
return false;
}
/**
* Returns true if the operator on this node is relational.
* the returned set does not include the equalities.
*/
static boolean isRelationalOperation(Node n) {
switch (n.getToken()) {
case GT: // equal
case GE: // not equal
case LT: // exactly equal
case LE: // exactly not equal
return true;
default:
break;
}
return false;
}
static boolean isAssignmentTarget(Node n) {
Node parent = n.getParent();
if ((isAssignmentOp(parent) && parent.getFirstChild() == n)
|| parent.isInc()
|| parent.isDec()
|| (parent.isForIn() && parent.getFirstChild() == n)) {
// If GETPROP/GETELEM is used as assignment target the object literal is
// acting as a temporary we can't fold it here:
// "{a:x}.a += 1" is not "x += 1"
return true;
}
return false;
}
/**
* Returns the inverse of an operator if it is invertible.
* ex. '>' ==> '<'
*/
static Token getInverseOperator(Token type) {
switch (type) {
case GT:
return Token.LT;
case LT:
return Token.GT;
case GE:
return Token.LE;
case LE:
return Token.GE;
default:
throw new IllegalArgumentException("Unexpected token: " + type);
}
}
/**
* Returns true if this is a literal value. We define a literal value
* as any node that evaluates to the same thing regardless of when or
* where it is evaluated. So /xyz/ and [3, 5] are literals, but
* the name a is not.
*
* <p>Function literals do not meet this definition, because they
* lexically capture variables. For example, if you have
* <code>
* function() { return a; }
* </code>
* If it is evaluated in a different scope, then it
* captures a different variable. Even if the function did not read
* any captured variables directly, it would still fail this definition,
* because it affects the lifecycle of variables in the enclosing scope.
*
* <p>However, a function literal with respect to a particular scope is
* a literal.
*
* @param includeFunctions If true, all function expressions will be
* treated as literals.
*/
public static boolean isLiteralValue(Node n, boolean includeFunctions) {
switch (n.getToken()) {
case CAST:
return isLiteralValue(n.getFirstChild(), includeFunctions);
case ARRAYLIT:
for (Node child = n.getFirstChild(); child != null;
child = child.getNext()) {
if ((!child.isEmpty()) && !isLiteralValue(child, includeFunctions)) {
return false;
}
}
return true;
case REGEXP:
// Return true only if all descendants are const.
for (Node child = n.getFirstChild(); child != null;
child = child.getNext()) {
if (!isLiteralValue(child, includeFunctions)) {
return false;
}
}
return true;
case OBJECTLIT:
// Return true only if all values are const.
for (Node child = n.getFirstChild(); child != null;
child = child.getNext()) {
if (!isLiteralValue(child.getFirstChild(), includeFunctions)) {
return false;
}
}
return true;
case FUNCTION:
return includeFunctions && !NodeUtil.isFunctionDeclaration(n);
default:
return isImmutableValue(n);
}
}
/**
* Returns true iff the value associated with the node is a JS string literal,
* or a concatenation thereof.
*/
static boolean isStringLiteralValue(Node node) {
if (node.isString()) {
return true;
} else if (node.isAdd()) {
Preconditions.checkState(node.hasTwoChildren(), node);
Node left = node.getFirstChild();
Node right = node.getLastChild();
return isStringLiteralValue(left) && isStringLiteralValue(right);
}
return false;
}
/**
* Determines whether the given value may be assigned to a define.
*
* @param val The value being assigned.
* @param defines The list of names of existing defines.
*/
static boolean isValidDefineValue(Node val, Set<String> defines) {
switch (val.getToken()) {
case STRING:
case NUMBER:
case TRUE:
case FALSE:
return true;
// Binary operators are only valid if both children are valid.
case AND:
case OR:
case ADD:
case BITAND:
case BITNOT:
case BITOR:
case BITXOR:
case DIV:
case EQ:
case EXPONENT:
case GE:
case GT:
case LE:
case LSH:
case LT:
case MOD:
case MUL:
case NE:
case RSH:
case SHEQ:
case SHNE:
case SUB:
case URSH:
return isValidDefineValue(val.getFirstChild(), defines)
&& isValidDefineValue(val.getLastChild(), defines);
case HOOK:
return isValidDefineValue(val.getFirstChild(), defines)
&& isValidDefineValue(val.getSecondChild(), defines)
&& isValidDefineValue(val.getLastChild(), defines);
// Unary operators are valid if the child is valid.
case NOT:
case NEG:
case POS:
return isValidDefineValue(val.getFirstChild(), defines);
// Names are valid if and only if they are defines themselves.
case NAME:
case GETPROP:
if (val.isQualifiedName()) {
return defines.contains(val.getQualifiedName());
}
break;
default:
break;
}
return false;
}
/**
* Returns whether this a BLOCK node with no children.
*
* @param block The node.
*/
static boolean isEmptyBlock(Node block) {
if (!block.isNormalBlock()) {
return false;
}
for (Node n = block.getFirstChild(); n != null; n = n.getNext()) {
if (!n.isEmpty()) {
return false;
}
}
return true;
}
static boolean isBinaryOperator(Node n) {
return isBinaryOperatorType(n.getToken());
}
/**
* An operator with two operands that does not assign a value to either.
* Once you cut through the layers of rules, these all parse similarly, taking
* LeftHandSideExpression operands on either side.
* Comma is not included, because it takes AssignmentExpression operands, making its syntax
* different.
*/
static boolean isBinaryOperatorType(Token type) {
switch (type) {
case OR:
case AND:
case BITOR:
case BITXOR:
case BITAND:
case EQ:
case NE:
case SHEQ:
case SHNE:
case LT:
case GT:
case LE:
case GE:
case INSTANCEOF:
case IN:
case LSH:
case RSH:
case URSH:
case ADD:
case SUB:
case MUL:
case DIV:
case MOD:
case EXPONENT:
return true;
default:
return false;
}
}
static boolean isUnaryOperator(Node n) {
return isUnaryOperatorType(n.getToken());
}
/**
* An operator taking only one operand.
* These all parse very similarly, taking LeftHandSideExpression operands.
*/
static boolean isUnaryOperatorType(Token type) {
switch (type) {
case DELPROP:
case VOID:
case TYPEOF:
case POS:
case NEG:
case BITNOT:
case NOT:
return true;
default:
return false;
}
}
static boolean isUpdateOperator(Node n) {
return isUpdateOperatorType(n.getToken());
}
static boolean isUpdateOperatorType(Token type) {
switch (type) {
case INC:
case DEC:
return true;
default:
return false;
}
}
static boolean isSimpleOperator(Node n) {
return isSimpleOperatorType(n.getToken());
}
/**
* A "simple" operator is one whose children are expressions,
* has no direct side-effects (unlike '+='), and has no
* conditional aspects (unlike '||').
*/
static boolean isSimpleOperatorType(Token type) {
switch (type) {
case ADD:
case BITAND:
case BITNOT:
case BITOR:
case BITXOR:
case COMMA:
case DIV:
case EQ:
case EXPONENT:
case GE:
case GETELEM:
case GETPROP:
case GT:
case INSTANCEOF:
case LE:
case LSH:
case LT:
case MOD:
case MUL:
case NE:
case NOT:
case RSH:
case SHEQ:
case SHNE:
case SUB:
case TYPEOF:
case VOID:
case POS:
case NEG:
case URSH:
return true;
default:
return false;
}
}
static boolean isTypedefDecl(Node n) {
if (n.isVar()
|| (n.isName() && n.getParent().isVar())
|| (n.isGetProp() && n.getParent().isExprResult())) {
JSDocInfo jsdoc = getBestJSDocInfo(n);
return jsdoc != null && jsdoc.hasTypedefType();
}
return false;
}
static boolean isEnumDecl(Node n) {
if (n.isVar()
|| (n.isName() && n.getParent().isVar())
|| (n.isGetProp() && n.getParent().isAssign() && n.getGrandparent().isExprResult())
|| (n.isAssign() && n.getParent().isExprResult())) {
JSDocInfo jsdoc = getBestJSDocInfo(n);
return jsdoc != null && jsdoc.hasEnumParameterType();
}
return false;
}
/**
* Returns true iff this node defines a namespace, e.g.,
*
* /** @const * / var goog = {};
* /** @const * / var goog = goog || {};
* /** @const * / goog.math = goog.math || {};
*/
static boolean isNamespaceDecl(Node n) {
JSDocInfo jsdoc = getBestJSDocInfo(n);
if (jsdoc != null && !jsdoc.getTypeNodes().isEmpty()) {
return false;
}
// In externs, we allow namespace definitions without @const.
// This is a worse design than always requiring @const, but it helps with
// namespaces that are defined in many places, such as gapi.
// Also, omitting @const in externs is not as confusing as in source code,
// because assigning an object literal in externs only makes sense when
// defining a namespace or enum.
if (!n.isFromExterns()
&& (jsdoc == null || !jsdoc.isConstant())) {
return false;
}
Node qnameNode;
Node initializer;
if (n.getParent().isVar()) {
qnameNode = n;
initializer = n.getFirstChild();
} else if (n.isExprResult()) {
Node expr = n.getFirstChild();
if (!expr.isAssign() || !expr.getFirstChild().isGetProp()) {
return false;
}
qnameNode = expr.getFirstChild();
initializer = expr.getLastChild();
} else if (n.isGetProp()) {
Node parent = n.getParent();
if (!parent.isAssign() || !parent.getParent().isExprResult()) {
return false;
}
qnameNode = n;
initializer = parent.getLastChild();
} else {
return false;
}
if (initializer == null || qnameNode == null) {
return false;
}
if (initializer.isObjectLit()) {
return true;
}
return initializer.isOr()
&& qnameNode.matchesQualifiedName(initializer.getFirstChild())
&& initializer.getLastChild().isObjectLit();