-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GlobalNamespace.java
1651 lines (1491 loc) · 50 KB
/
GlobalNamespace.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 2006 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 static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.rhino.jstype.JSTypeNative.GLOBAL_THIS;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.StaticSourceFile;
import com.google.javascript.rhino.StaticSymbolTable;
import com.google.javascript.rhino.TokenStream;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.StaticTypedRef;
import com.google.javascript.rhino.jstype.StaticTypedScope;
import com.google.javascript.rhino.jstype.StaticTypedSlot;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Builds a global namespace of all the objects and their properties in the global scope. Also
* builds an index of all the references to those names.
*
* @author nicksantos@google.com (Nick Santos)
*/
class GlobalNamespace
implements StaticTypedScope, StaticSymbolTable<GlobalNamespace.Name, GlobalNamespace.Ref> {
private final AbstractCompiler compiler;
private final Node root;
private final Node externsRoot;
private SourceKind sourceKind;
private Scope externsScope;
private boolean generated = false;
enum SourceKind {
EXTERN,
TYPE_SUMMARY,
CODE;
static SourceKind fromScriptNode(Node n) {
if (!n.isFromExterns()) {
return CODE;
} else if (NodeUtil.isFromTypeSummary(n)) {
return TYPE_SUMMARY;
} else {
return EXTERN;
}
}
}
/**
* Each reference has an index in post-order.
* Notice that some nodes are represented by 2 Ref objects, so
* this index is not necessarily unique.
*/
private int currentPreOrderIndex = 0;
/** Global namespace tree */
private final List<Name> globalNames = new ArrayList<>();
/** Maps names (e.g. "a.b.c") to nodes in the global namespace tree */
private final Map<String, Name> nameMap = new HashMap<>();
/**
* Creates an instance that may emit warnings when building the namespace.
*
* @param compiler The AbstractCompiler, for reporting code changes
* @param root The root of the rest of the code to build a namespace for.
*/
GlobalNamespace(AbstractCompiler compiler, Node root) {
this(compiler, null, root);
}
/**
* Creates an instance that may emit warnings when building the namespace.
*
* @param compiler The AbstractCompiler, for reporting code changes
* @param externsRoot The root of the externs to build a namespace for. If
* this is null, externs and properties defined on extern types will not
* be included in the global namespace. If non-null, it allows
* user-defined function on extern types to be included in the global
* namespace. E.g. String.foo.
* @param root The root of the rest of the code to build a namespace for.
*/
GlobalNamespace(AbstractCompiler compiler, Node externsRoot, Node root) {
this.compiler = compiler;
this.externsRoot = externsRoot;
this.root = root;
}
boolean hasExternsRoot() {
return externsRoot != null;
}
@Override
public Node getRootNode() {
return root.getParent();
}
@Override
public StaticTypedScope getParentScope() {
return null;
}
@Override
public Name getSlot(String name) {
return getOwnSlot(name);
}
@Override
public Name getOwnSlot(String name) {
ensureGenerated();
return nameMap.get(name);
}
@Override
public JSType getTypeOfThis() {
return compiler.getTypeRegistry().getNativeObjectType(GLOBAL_THIS);
}
@Override
public Iterable<Ref> getReferences(Name slot) {
ensureGenerated();
return Collections.unmodifiableList(slot.getRefs());
}
@Override
public StaticTypedScope getScope(Name slot) {
return this;
}
@Override
public Iterable<Name> getAllSymbols() {
ensureGenerated();
return Collections.unmodifiableCollection(getNameIndex().values());
}
private void ensureGenerated() {
if (!generated) {
process();
}
}
/**
* Gets a list of the roots of the forest of the global names, where the
* roots are the top-level names.
*/
List<Name> getNameForest() {
ensureGenerated();
return globalNames;
}
/**
* Gets an index of all the global names, indexed by full qualified name
* (as in "a", "a.b.c", etc.).
*/
Map<String, Name> getNameIndex() {
ensureGenerated();
return nameMap;
}
/**
* A simple data class that contains the information necessary to inspect
* a node for changes to the global namespace.
*/
static class AstChange {
final JSModule module;
final Scope scope;
final Node node;
AstChange(JSModule module, Scope scope, Node node) {
this.module = module;
this.scope = scope;
this.node = node;
}
@Override
public boolean equals(Object obj) {
checkState(obj instanceof AstChange);
AstChange other = (AstChange) obj;
return Objects.equals(this.module, other.module)
&& Objects.equals(this.scope, other.scope)
&& Objects.equals(this.node, other.node);
}
@Override
public int hashCode() {
return Objects.hash(this.module, this.scope, this.node);
}
}
/**
* If the client adds new nodes to the AST, scan these new nodes
* to see if they've added any references to the global namespace.
* @param newNodes New nodes to check.
*/
void scanNewNodes(Set<AstChange> newNodes) {
BuildGlobalNamespace builder = new BuildGlobalNamespace();
for (AstChange info : newNodes) {
if (!info.node.isQualifiedName() && !NodeUtil.isObjectLitKey(info.node)) {
continue;
}
scanFromNode(builder, info.module, info.scope, info.node);
}
}
private void scanFromNode(
BuildGlobalNamespace builder, JSModule module, Scope scope, Node n) {
// Check affected parent nodes first.
if (n.isName() || n.isGetProp()) {
scanFromNode(builder, module, scope, n.getParent());
}
builder.collect(module, scope, n);
}
/**
* Builds the namespace lazily.
*/
private void process() {
if (hasExternsRoot()) {
sourceKind = SourceKind.EXTERN;
NodeTraversal.traverse(compiler, externsRoot, new BuildGlobalNamespace());
}
sourceKind = SourceKind.CODE;
NodeTraversal.traverse(compiler, root, new BuildGlobalNamespace());
generated = true;
externsScope = null;
}
/**
* Determines whether a name reference in a particular scope is a global name
* reference.
*
* @param name A variable or property name (e.g. "a" or "a.b.c.d")
* @param s The scope in which the name is referenced
* @return Whether the name reference is a global name reference
*/
private boolean isGlobalNameReference(String name, Scope s) {
String topVarName = getTopVarName(name);
return isGlobalVarReference(topVarName, s);
}
/**
* Gets the top variable name from a possibly namespaced name.
*
* @param name A variable or qualified property name (e.g. "a" or "a.b.c.d")
* @return The top variable name (e.g. "a")
*/
private static String getTopVarName(String name) {
int firstDotIndex = name.indexOf('.');
return firstDotIndex == -1 ? name : name.substring(0, firstDotIndex);
}
/**
* Determines whether a variable name reference in a particular scope is a
* global variable reference.
*
* @param name A variable name (e.g. "a")
* @param s The scope in which the name is referenced
* @return Whether the name reference is a global variable reference
*/
private boolean isGlobalVarReference(String name, Scope s) {
Var v = s.getVar(name);
if (v == null && externsScope != null) {
v = externsScope.getVar(name);
}
return v != null && !v.isLocal();
}
// -------------------------------------------------------------------------
/** Builds a tree representation of the global namespace. Omits prototypes. */
private class BuildGlobalNamespace extends NodeTraversal.AbstractPreOrderCallback {
/** Collect the references in pre-order. */
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (hasExternsRoot()) {
if (n == externsRoot) {
// If we are traversing the externs, then we save a pointer to the scope
// generated by them, so that we can do lookups in it later.
externsScope = t.getScope();
} else if (n.isScript()) {
// When checking type-summary files, we want to consider them like normal code
// for some things (like alias inlining) but like externs for other things.
sourceKind = SourceKind.fromScriptNode(n);
}
}
collect(t.getModule(), t.getScope(), n);
return true;
}
public void collect(JSModule module, Scope scope, Node n) {
Node parent = n.getParent();
String name;
boolean isSet = false;
Name.Type type = Name.Type.OTHER;
boolean isPropAssign = false;
boolean shouldCreateProp = true;
switch (n.getToken()) {
case GETTER_DEF:
case SETTER_DEF:
case STRING_KEY:
case MEMBER_FUNCTION_DEF:
// This may be a key in an object literal declaration.
name = null;
if (parent.isObjectLit()) {
name = getNameForObjLitKey(n);
} else if (parent.isClassMembers()) {
name = getNameForClassMembers(n);
}
if (name == null) {
return;
}
isSet = true;
switch (n.getToken()) {
case MEMBER_FUNCTION_DEF:
type = getValueType(n.getFirstChild());
if (n.getParent().isClassMembers() && !n.isStaticMember()) {
shouldCreateProp = false;
}
break;
case STRING_KEY:
type = getValueType(n.getFirstChild());
break;
case GETTER_DEF:
type = Name.Type.GET;
break;
case SETTER_DEF:
type = Name.Type.SET;
break;
default:
throw new IllegalStateException("unexpected:" + n);
}
break;
case NAME:
// This may be a variable get or set.
switch (parent.getToken()) {
case VAR:
case LET:
case CONST:
isSet = true;
Node rvalue = n.getFirstChild();
type = (rvalue == null) ? Name.Type.OTHER : getValueType(rvalue);
break;
case ASSIGN:
if (parent.getFirstChild() == n) {
isSet = true;
type = getValueType(n.getNext());
}
break;
case GETPROP:
return;
case FUNCTION:
Node grandparent = parent.getParent();
if (grandparent == null || NodeUtil.isFunctionExpression(parent)) {
return;
}
isSet = true;
type = Name.Type.FUNCTION;
break;
case CATCH:
case INC:
case DEC:
isSet = true;
type = Name.Type.OTHER;
break;
case CLASS:
// The first child is the class name, and the second child is the superclass name.
if (parent.getFirstChild() == n) {
isSet = true;
type = Name.Type.CLASS;
}
break;
case STRING_KEY:
case ARRAY_PATTERN:
case DEFAULT_VALUE:
case COMPUTED_PROP:
case REST:
// This may be a set.
if (NodeUtil.isLhsByDestructuring(n)) {
isSet = true;
type = Name.Type.OTHER;
}
break;
default:
if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) {
isSet = true;
type = Name.Type.OTHER;
}
}
name = n.getString();
break;
case GETPROP:
// This may be a namespaced name get or set.
if (parent != null) {
switch (parent.getToken()) {
case ASSIGN:
if (parent.getFirstChild() == n) {
isSet = true;
type = getValueType(n.getNext());
isPropAssign = true;
}
break;
case INC:
case DEC:
isSet = true;
type = Name.Type.OTHER;
break;
case GETPROP:
return;
default:
if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) {
isSet = true;
type = Name.Type.OTHER;
}
}
}
if (!n.isQualifiedName()) {
return;
}
name = n.getQualifiedName();
break;
case CALL:
if (isObjectHasOwnPropertyCall(n)) {
String qname = n.getFirstFirstChild().getQualifiedName();
Name globalName = getOrCreateName(qname, true);
globalName.usedHasOwnProperty = true;
}
return;
default:
return;
}
// We are only interested in global names.
if (!isGlobalNameReference(name, scope)) {
return;
}
if (isSet) {
// Use the closest hoist scope to select handleSetFromGlobal or handleSetFromLocal
// because they use the term 'global' in an ES5, pre-block-scoping sense.
Scope hoistScope = scope.getClosestHoistScope();
if (hoistScope.isGlobal()) {
handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type, shouldCreateProp);
} else {
handleSetFromLocal(module, scope, n, parent, name, shouldCreateProp);
}
} else {
handleGet(module, scope, n, parent, name);
}
}
/**
* Gets the fully qualified name corresponding to an object literal key,
* as long as it and its prefix property names are valid JavaScript
* identifiers. The object literal may be nested inside of other object
* literals.
*
* For example, if called with node {@code n} representing "z" in any of
* the following expressions, the result would be "w.x.y.z":
* <code> var w = {x: {y: {z: 0}}}; </code>
* <code> w.x = {y: {z: 0}}; </code>
* <code> w.x.y = {'a': 0, 'z': 0}; </code>
*
* @param n A child of an OBJLIT node
* @return The global name, or null if {@code n} doesn't correspond to the
* key of an object literal that can be named
*/
String getNameForObjLitKey(Node n) {
Node parent = n.getParent();
checkState(parent.isObjectLit());
Node grandparent = parent.getParent();
if (grandparent == null) {
return null;
}
Node greatGrandparent = grandparent.getParent();
String name;
switch (grandparent.getToken()) {
case NAME:
// VAR
// NAME (grandparent)
// OBJLIT (parent)
// STRING (n)
if (greatGrandparent == null || !NodeUtil.isNameDeclaration(greatGrandparent)) {
return null;
}
name = grandparent.getString();
break;
case ASSIGN:
// ASSIGN (grandparent)
// NAME|GETPROP
// OBJLIT (parent)
// STRING (n)
Node lvalue = grandparent.getFirstChild();
name = lvalue.getQualifiedName();
break;
case STRING_KEY:
// OBJLIT
// STRING (grandparent)
// OBJLIT (parent)
// STRING (n)
if (greatGrandparent != null && greatGrandparent.isObjectLit()) {
name = getNameForObjLitKey(grandparent);
} else {
return null;
}
break;
default:
return null;
}
if (name != null) {
String key = n.getString();
if (TokenStream.isJSIdentifier(key)) {
return name + '.' + key;
}
}
return null;
}
/**
* Gets the fully qualified name corresponding to an class member function,
* as long as it and its prefix property names are valid JavaScript
* identifiers.
*
* For example, if called with node {@code n} representing "y" in any of
* the following expressions, the result would be "x.y":
* <code> class x{y(){}}; </code>
* <code> var x = class{y(){}}; </code>
* <code> var x; x = class{y(){}}; </code>
*
* @param n A child of an CLASS_MEMBERS node
* @return The global name, or null if {@code n} doesn't correspond to
* a class member function that can be named
*/
String getNameForClassMembers(Node n) {
Node parent = n.getParent();
checkState(parent.isClassMembers());
String className = NodeUtil.getName(parent.getParent());
return className == null ? null : className + '.' + n.getString();
}
/**
* Gets the type of a value or simple expression.
*
* @param n An r-value in an assignment or variable declaration (not null)
* @return A {@link Name.Type}
*/
Name.Type getValueType(Node n) {
// Shorthand assignment of extended object literal
if (n == null) {
return Name.Type.OTHER;
}
switch (n.getToken()) {
case CLASS:
return Name.Type.CLASS;
case OBJECTLIT:
return Name.Type.OBJECTLIT;
case FUNCTION:
return Name.Type.FUNCTION;
case OR:
// Recurse on the second value. If the first value were an object
// literal or function, then the OR would be meaningless and the
// second value would be dead code. Assume that if the second value
// is an object literal or function, then the first value will also
// evaluate to one when it doesn't evaluate to false.
return getValueType(n.getLastChild());
case HOOK:
// The same line of reasoning used for the OR case applies here.
Node second = n.getSecondChild();
Name.Type t = getValueType(second);
if (t != Name.Type.OTHER) {
return t;
}
Node third = second.getNext();
return getValueType(third);
default:
break;
}
return Name.Type.OTHER;
}
/**
* Updates our representation of the global namespace to reflect an assignment to a global name
* in any scope where variables are hoisted to the global scope (i.e. the global scope in an ES5
* sense).
*
* @param module the current module
* @param scope the current scope
* @param n The node currently being visited
* @param parent {@code n}'s parent
* @param name The global name (e.g. "a" or "a.b.c.d")
* @param isPropAssign Whether this set corresponds to a property
* assignment of the form <code>a.b.c = ...;</code>
* @param type The type of the value that the name is being assigned
*/
void handleSetFromGlobal(JSModule module, Scope scope,
Node n, Node parent, String name,
boolean isPropAssign, Name.Type type, boolean shouldCreateProp) {
if (maybeHandlePrototypePrefix(module, scope, n, parent, name)) {
return;
}
Name nameObj = getOrCreateName(name, shouldCreateProp);
nameObj.type = type;
if (n.getBooleanProp(Node.MODULE_EXPORT)) {
nameObj.isModuleProp = true;
}
maybeRecordEs6Subclass(n, parent, nameObj);
Ref set = new Ref(module, scope, n, nameObj, Ref.Type.SET_FROM_GLOBAL,
currentPreOrderIndex++);
nameObj.addRef(set);
if (isNestedAssign(parent)) {
// This assignment is both a set and a get that creates an alias.
Ref get = new Ref(module, scope, n, nameObj, Ref.Type.ALIASING_GET,
currentPreOrderIndex++);
nameObj.addRef(get);
Ref.markTwins(set, get);
} else if (isTypeDeclaration(n)) {
// Names with a @constructor or @enum annotation are always collapsed
nameObj.setDeclaredType();
}
}
/**
* Given a new node and its name that is an ES6 class, checks if it is an ES6 class with an ES6
* superclass. If the superclass is a simple or qualified names, adds itself to the parent's
* list of subclasses. Otherwise this does nothing.
*
* @param n The node being visited.
* @param parent {@code n}'s parent
* @param subclassNameObj The Name of the new node being visited.
*/
private void maybeRecordEs6Subclass(Node n, Node parent, Name subclassNameObj) {
if (subclassNameObj.type != Name.Type.CLASS || parent == null) {
return;
}
Node superclass = null;
if (parent.isClass()) {
superclass = parent.getSecondChild();
} else if (n.isName() || n.isGetProp()){
Node classNode = NodeUtil.getAssignedValue(n);
if (classNode != null && classNode.isClass()) {
superclass = classNode.getSecondChild();
}
}
// TODO(lharker): figure out what should we do when n is an object literal key.
// e.g. var obj = {foo: class extends Parent {}};
// If there's no superclass, or the superclass expression is more complicated than a simple
// or qualified name, return.
if (superclass == null
|| superclass.isEmpty()
|| !(superclass.isName() || superclass.isGetProp())) {
return;
}
String superclassName = superclass.getQualifiedName();
Name superclassNameObj = getOrCreateName(superclassName, true);
// If the superclass is an ES3/5 class we don't record its subclasses.
if (superclassNameObj != null && superclassNameObj.type == Name.Type.CLASS) {
superclassNameObj.addSubclass(subclassNameObj);
}
}
/**
* Determines whether a set operation is a constructor or enumeration
* or interface declaration. The set operation may either be an assignment
* to a name, a variable declaration, or an object literal key mapping.
*
* @param n The node that represents the name being set
* @return Whether the set operation is either a constructor or enum
* declaration
*/
private boolean isTypeDeclaration(Node n) {
Node valueNode = NodeUtil.getRValueOfLValue(n);
JSDocInfo info = NodeUtil.getBestJSDocInfo(n);
// Heed the annotations only if they're sensibly used.
return info != null
&& valueNode != null
&& ((info.isConstructor() && valueNode.isFunction())
|| (info.isInterface() && valueNode.isFunction())
|| (info.hasEnumParameterType() && valueNode.isObjectLit()));
}
/**
* Updates our representation of the global namespace to reflect an
* assignment to a global name in a local scope.
*
* @param module The current module
* @param scope The current scope
* @param n The node currently being visited
* @param parent {@code n}'s parent
* @param name The global name (e.g. "a" or "a.b.c.d")
*/
void handleSetFromLocal(JSModule module, Scope scope, Node n, Node parent,
String name, boolean shouldCreateProp) {
if (maybeHandlePrototypePrefix(module, scope, n, parent, name)) {
return;
}
Name nameObj = getOrCreateName(name, shouldCreateProp);
Ref set = new Ref(module, scope, n, nameObj,
Ref.Type.SET_FROM_LOCAL, currentPreOrderIndex++);
nameObj.addRef(set);
if (n.getBooleanProp(Node.MODULE_EXPORT)) {
nameObj.isModuleProp = true;
}
if (isNestedAssign(parent)) {
// This assignment is both a set and a get that creates an alias.
Ref get = new Ref(module, scope, n, nameObj,
Ref.Type.ALIASING_GET, currentPreOrderIndex++);
nameObj.addRef(get);
Ref.markTwins(set, get);
}
}
/**
* Updates our representation of the global namespace to reflect a read
* of a global name.
*
* @param module The current module
* @param scope The current scope
* @param n The node currently being visited
* @param parent {@code n}'s parent
* @param name The global name (e.g. "a" or "a.b.c.d")
*/
void handleGet(JSModule module, Scope scope,
Node n, Node parent, String name) {
if (maybeHandlePrototypePrefix(module, scope, n, parent, name)) {
return;
}
Ref.Type type;
switch (parent.getToken()) {
case EXPR_RESULT:
case IF:
case INSTANCEOF:
case TYPEOF:
case VOID:
case NOT:
case BITNOT:
case POS:
case NEG:
type = Ref.Type.DIRECT_GET;
break;
case CALL:
if (n == parent.getFirstChild()) {
// It is a call target
type = Ref.Type.CALL_GET;
} else if (isClassDefiningCall(parent)) {
type = Ref.Type.DIRECT_GET;
} else {
type = Ref.Type.ALIASING_GET;
}
break;
case NEW:
type = n == parent.getFirstChild() ? Ref.Type.DIRECT_GET : Ref.Type.ALIASING_GET;
break;
case OR:
case AND:
// This node is x or y in (x||y) or (x&&y). We only know that an
// alias is not getting created for this name if the result is used
// in a boolean context or assigned to the same name
// (e.g. var a = a || {}).
type = determineGetTypeForHookOrBooleanExpr(module, scope, parent, name);
break;
case HOOK:
if (n != parent.getFirstChild()) {
// This node is y or z in (x?y:z). We only know that an alias is
// not getting created for this name if the result is assigned to
// the same name (e.g. var a = a ? a : {}).
type = determineGetTypeForHookOrBooleanExpr(module, scope, parent, name);
} else {
type = Ref.Type.DIRECT_GET;
}
break;
case DELPROP:
type = Ref.Type.DELETE_PROP;
break;
case CLASS:
// This node is the superclass in an extends clause.
type = Ref.Type.DIRECT_GET;
break;
default:
type = Ref.Type.ALIASING_GET;
break;
}
handleGet(module, scope, n, parent, name, type, true);
}
/**
* Updates our representation of the global namespace to reflect a read of a global name.
*
* @param module The current module
* @param scope The current scope
* @param n The node currently being visited
* @param parent {@code n}'s parent
* @param name The global name (e.g. "a" or "a.b.c.d")
* @param type The reference type
*/
void handleGet(
JSModule module,
Scope scope,
Node n,
Node parent,
String name,
Ref.Type type,
boolean shouldCreateProp) {
Name nameObj = getOrCreateName(name, shouldCreateProp);
// No need to look up additional ancestors, since they won't be used.
nameObj.addRef(new Ref(module, scope, n, nameObj, type, currentPreOrderIndex++));
}
private boolean isClassDefiningCall(Node callNode) {
CodingConvention convention = compiler.getCodingConvention();
// Look for goog.inherits, goog.mixin
SubclassRelationship classes =
convention.getClassesDefinedByCall(callNode);
if (classes != null) {
return true;
}
// Look for calls to goog.addSingletonGetter calls.
String className = convention.getSingletonGetterClassName(callNode);
return className != null;
}
/** Detect calls of the form a.b.hasOwnProperty(c); that prevent property collapsing on a.b */
private boolean isObjectHasOwnPropertyCall(Node callNode) {
checkArgument(callNode.isCall(), callNode);
if (!callNode.hasTwoChildren()) {
return false;
}
Node fn = callNode.getFirstChild();
if (!fn.isGetProp()) {
return false;
}
Node callee = fn.getFirstChild();
Node method = fn.getSecondChild();
return method.isString()
&& "hasOwnProperty".equals(method.getString())
&& callee.isQualifiedName();
}
/**
* Determines whether the result of a hook (x?y:z) or boolean expression
* (x||y) or (x&&y) is assigned to a specific global name.
*
* @param module The current module
* @param scope The current scope
* @param parent The parent of the current node in the traversal. This node
* should already be known to be a HOOK, AND, or OR node.
* @param name A name that is already known to be global in the current
* scope (e.g. "a" or "a.b.c.d")
* @return The expression's get type, either {@link Ref.Type#DIRECT_GET} or
* {@link Ref.Type#ALIASING_GET}
*/
Ref.Type determineGetTypeForHookOrBooleanExpr(
JSModule module, Scope scope, Node parent, String name) {
Node prev = parent;
for (Node anc : parent.getAncestors()) {
switch (anc.getToken()) {
case INSTANCEOF:
case EXPR_RESULT:
case VAR:
case LET:
case CONST:
case IF:
case WHILE:
case FOR:
case FOR_IN:
case TYPEOF:
case VOID:
case NOT:
case BITNOT:
case POS:
case NEG:
return Ref.Type.DIRECT_GET;
case HOOK:
if (anc.getFirstChild() == prev) {
return Ref.Type.DIRECT_GET;
}
break;
case ASSIGN:
if (!anc.getFirstChild().matchesQualifiedName(name)) {
return Ref.Type.ALIASING_GET;
}
break;
case NAME: // a variable declaration
if (!name.equals(anc.getString())) {
return Ref.Type.ALIASING_GET;
}
break;
case CALL:
if (anc.getFirstChild() != prev) {
return Ref.Type.ALIASING_GET;
}
break;
case DELPROP:
return Ref.Type.DELETE_PROP;
default:
break;
}
prev = anc;
}
return Ref.Type.ALIASING_GET;
}
/**
* Updates our representation of the global namespace to reflect a read
* of a global name's longest prefix before the "prototype" property if the
* name includes the "prototype" property. Does nothing otherwise.
*
* @param module The current module
* @param scope The current scope
* @param n The node currently being visited
* @param parent {@code n}'s parent
* @param name The global name (e.g. "a" or "a.b.c.d")
* @return Whether the name was handled
*/
boolean maybeHandlePrototypePrefix(JSModule module, Scope scope,
Node n, Node parent, String name) {
// We use a string-based approach instead of inspecting the parse tree
// to avoid complexities with object literals, possibly nested, beneath
// assignments.
int numLevelsToRemove;
String prefix;
if (name.endsWith(".prototype")) {
numLevelsToRemove = 1;
prefix = name.substring(0, name.length() - 10);
} else {
int i = name.indexOf(".prototype.");
if (i == -1) {
return false;
}
prefix = name.substring(0, i);
numLevelsToRemove = 2;
i = name.indexOf('.', i + 11);
while (i >= 0) {
numLevelsToRemove++;
i = name.indexOf('.', i + 1);
}
}
if (parent != null && NodeUtil.isObjectLitKey(n)) {
// Object literal keys have no prefix that's referenced directly per
// key, so we're done.
return true;
}
for (int i = 0; i < numLevelsToRemove; i++) {
parent = n;
n = n.getFirstChild();
}
handleGet(module, scope, n, parent, prefix, Ref.Type.PROTOTYPE_GET, true);
return true;
}