-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
SymbolTable.java
1896 lines (1686 loc) · 62.4 KB
/
SymbolTable.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 2011 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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.common.collect.Table;
import com.google.javascript.jscomp.parsing.parser.util.format.SimpleFormat;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Marker;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.SourcePosition;
import com.google.javascript.rhino.StaticRef;
import com.google.javascript.rhino.StaticScope;
import com.google.javascript.rhino.StaticSlot;
import com.google.javascript.rhino.StaticSourceFile;
import com.google.javascript.rhino.StaticSymbolTable;
import com.google.javascript.rhino.jstype.EnumType;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.SimpleReference;
import com.google.javascript.rhino.jstype.SimpleSlot;
import com.google.javascript.rhino.jstype.StaticTypedScope;
import com.google.javascript.rhino.jstype.StaticTypedSlot;
import com.google.javascript.rhino.jstype.UnionType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* A symbol table for people that want to use Closure Compiler as an indexer.
*
* Contains an index of all the symbols in the code within a compilation
* job. The API is designed for people who want to visit all the symbols, rather
* than people who want to lookup a specific symbol by a certain key.
*
* We can use this to combine different types of symbol tables. For example,
* one class might have a {@code StaticSymbolTable} of all variable references,
* and another class might have a {@code StaticSymbolTable} of all type names
* in JSDoc comments. This class allows you to combine them into a unified
* index.
*
* Most passes build their own "partial" symbol table that implements the same
* interface (StaticSymbolTable, StaticSlot, and friends). Individual compiler
* passes usually need more or less metadata about the certainty of symbol
* information. Building a complete symbol table with all the necessary metadata
* for all passes would be too slow. However, as long as these "partial" symbol
* tables implement the proper interfaces, we should be able to add them to this
* symbol table to make it more complete.
*
* If clients want fast lookup, they should build their own wrapper around
* this symbol table that indexes symbols or references by the desired lookup
* key.
*
* By design, when this symbol table creates symbols for types, it tries
* to mimic the symbol table you would get in an OO language. For example,
* the "type Foo" and "the constructor that creates objects of type Foo"
* are the same symbol. The types of "Foo.prototype" and "new Foo()" also
* have the same symbol. Although JSCompiler internally treats these as
* distinct symbols, we assume that most clients will not care about
* the distinction.
*
* @see #addSymbolsFrom For more information on how to write plugins for this
* symbol table.
*
* @author nicksantos@google.com (Nick Santos)
*/
public final class SymbolTable {
private static final Logger logger =
Logger.getLogger(SymbolTable.class.getName());
/**
* The name we use for the JavaScript built-in Global object. It's
* anonymous in JavaScript, so we have to give it an invalid identifier
* to avoid conflicts with user-defined property names.
*/
public static final String GLOBAL_THIS = "*global*";
/**
* All symbols in the program, uniquely identified by the node where
* they're declared and their name.
*/
private final Table<Node, String, Symbol> symbols = HashBasedTable.create();
/**
* All syntactic scopes in the program, uniquely identified by the node where
* they're declared.
*/
private final Map<Node, SymbolScope> scopes = new LinkedHashMap<>();
/**
* All Nodes with JSDocInfo in the program.
*/
private final List<Node> docInfos = new ArrayList<>();
private SymbolScope globalScope = null;
private final AbstractCompiler compiler;
private final JSTypeRegistry registry;
/**
* Clients should get a symbol table by asking the compiler at the end
* of a compilation job.
*/
SymbolTable(AbstractCompiler compiler, JSTypeRegistry registry) {
this.compiler = compiler;
this.registry = registry;
}
public Iterable<Reference> getReferences(Symbol symbol) {
return Collections.unmodifiableCollection(symbol.references.values());
}
public ImmutableList<Reference> getReferenceList(Symbol symbol) {
return ImmutableList.copyOf(symbol.references.values());
}
public Iterable<Symbol> getAllSymbols() {
return Collections.unmodifiableCollection(symbols.values());
}
/**
* Get the symbols in their natural ordering.
* Always returns a mutable list.
*/
public List<Symbol> getAllSymbolsSorted() {
List<Symbol> sortedSymbols = getNaturalSymbolOrdering().sortedCopy(symbols.values());
return sortedSymbols;
}
/**
* Gets the 'natural' ordering of symbols.
*
* Right now, we only guarantee that symbols in the global scope will come
* before symbols in local scopes. After that, the order is deterministic but
* undefined.
*/
public Ordering<Symbol> getNaturalSymbolOrdering() {
return symbolOrdering;
}
public SymbolScope getScope(Symbol slot) {
return slot.scope;
}
public Collection<Node> getAllJSDocInfoNodes() {
return Collections.unmodifiableList(docInfos);
}
/**
* Declare a symbol after the main symbol table was constructed.
* Throws an exception if you try to declare a symbol twice.
*/
public Symbol declareInferredSymbol(
SymbolScope scope, String name, Node declNode) {
return declareSymbol(name, null, true, scope, declNode, null);
}
/**
* Gets the scope that contains the given node.
* If {@code n} is a function name, we return the scope that contains the
* function, not the function itself.
*/
public SymbolScope getEnclosingScope(Node n) {
Node current = n.getParent();
if (n.isName() &&
n.getParent().isFunction()) {
current = current.getParent();
}
for (; current != null; current = current.getParent()) {
if (scopes.containsKey(current)) {
return scopes.get(current);
}
}
return null;
}
/**
* If {@code sym} is a function, try to find a Symbol for
* a parameter with the given name.
*
* Returns null if we couldn't find one.
*
* Notice that this just makes a best effort, and may not be able
* to find parameters for non-conventional function definitions.
* For example, we would not be able to find "y" in this code:
* <code>
* var x = x() ? function(y) {} : function(y) {};
* </code>
*/
public Symbol getParameterInFunction(Symbol sym, String paramName) {
SymbolScope scope = getScopeInFunction(sym);
if (scope != null) {
Symbol param = scope.getSlot(paramName);
if (param != null && param.scope == scope) {
return param;
}
}
return null;
}
private SymbolScope getScopeInFunction(Symbol sym) {
FunctionType type = sym.getFunctionType();
if (type == null) {
return null;
}
Node functionNode = type.getSource();
if (functionNode == null) {
return null;
}
return scopes.get(functionNode);
}
/**
* All local scopes are associated with a function, and some functions
* are associated with a symbol. Returns the symbol associated with the given
* scope.
*/
public Symbol getSymbolForScope(SymbolScope scope) {
if (scope.getSymbolForScope() == null) {
scope.setSymbolForScope(findSymbolForScope(scope));
}
return scope.getSymbolForScope();
}
/**
* Find the symbol associated with the given scope.
* Notice that we won't always be able to figure out this association
* dynamically, so sometimes we'll just create the association when we
* create the scope.
*/
private Symbol findSymbolForScope(SymbolScope scope) {
Node rootNode = scope.getRootNode();
if (rootNode.getParent() == null) {
return globalScope.getSlot(GLOBAL_THIS);
}
if (!rootNode.isFunction()) {
return null;
}
String name = NodeUtil.getBestLValueName(
NodeUtil.getBestLValue(rootNode));
return name == null ? null : scope.getParentScope().getQualifiedSlot(name);
}
/**
* Get all symbols associated with the type of the given symbol.
*
* For example, given a variable x declared as
* /* @type {Array|Date} /
* var x = f();
* this will return the constructors for Array and Date.
*/
public Iterable<Symbol> getAllSymbolsForTypeOf(Symbol sym) {
return getAllSymbolsForType(getType(sym));
}
/**
* Returns the global scope.
*/
public SymbolScope getGlobalScope() {
return globalScope;
}
/**
* Gets the symbol for the given constructor or interface.
*/
public Symbol getSymbolDeclaredBy(FunctionType fn) {
checkState(fn.isConstructor() || fn.isInterface());
ObjectType instanceType = fn.getInstanceType();
return getSymbolForName(fn.getSource(), instanceType.getReferenceName());
}
/**
* Gets the symbol for the given enum.
*/
public Symbol getSymbolDeclaredBy(EnumType enumType) {
return getSymbolForName(null,
enumType.getElementsType().getReferenceName());
}
/**
* Gets the symbol for the prototype if this is the symbol for a constructor
* or interface.
*/
public Symbol getSymbolForInstancesOf(Symbol sym) {
FunctionType fn = sym.getFunctionType();
if (fn != null && fn.isNominalConstructor()) {
return getSymbolForInstancesOf(fn);
}
return null;
}
/**
* Gets the symbol for the prototype of the given constructor or interface.
*/
public Symbol getSymbolForInstancesOf(FunctionType fn) {
checkState(fn.isConstructor() || fn.isInterface());
ObjectType pType = fn.getPrototype();
return getSymbolForName(fn.getSource(), pType.getReferenceName());
}
private Symbol getSymbolForName(Node source, String name) {
if (name == null || globalScope == null) {
return null;
}
SymbolScope scope = source == null ?
globalScope : getEnclosingScope(source);
// scope will sometimes be null if one of the type-stripping passes
// was run, and the symbol isn't in the AST anymore.
return scope == null ? null : scope.getQualifiedSlot(name);
}
/**
* Gets all symbols associated with the given type.
* For union types, this may be multiple symbols.
* For instance types, this will return the constructor of
* that instance.
*/
public List<Symbol> getAllSymbolsForType(JSType type) {
if (type == null) {
return ImmutableList.of();
}
UnionType unionType = type.toMaybeUnionType();
if (unionType != null) {
List<Symbol> result = new ArrayList<>(2);
for (JSType alt : unionType.getAlternates()) {
// Our type system never has nested unions.
Symbol altSym = getSymbolForTypeHelper(alt, true);
if (altSym != null) {
result.add(altSym);
}
}
return result;
}
Symbol result = getSymbolForTypeHelper(type, true);
return result == null
? ImmutableList.<Symbol>of() : ImmutableList.of(result);
}
/**
* Gets all symbols associated with the given type.
* If there is more that one symbol associated with the given type,
* return null.
* @param type The type.
* @param linkToCtor If true, we should link instance types back
* to their constructor function. If false, we should link
* instance types back to their prototype. See the comments
* at the top of this file for more information on how
* our internal type system is more granular than Symbols.
*/
private Symbol getSymbolForTypeHelper(JSType type, boolean linkToCtor) {
if (type == null) {
return null;
}
if (type.isGlobalThisType()) {
return globalScope.getSlot(GLOBAL_THIS);
} else if (type.isNominalConstructor()) {
return linkToCtor ?
globalScope.getSlot("Function") :
getSymbolDeclaredBy(type.toMaybeFunctionType());
} else if (type.isFunctionPrototypeType()) {
FunctionType ownerFn = ((ObjectType) type).getOwnerFunction();
if (!ownerFn.isConstructor() && !ownerFn.isInterface()) {
return null;
}
return linkToCtor ?
getSymbolDeclaredBy(ownerFn) :
getSymbolForInstancesOf(ownerFn);
} else if (type.isInstanceType()) {
FunctionType ownerFn = ((ObjectType) type).getConstructor();
return linkToCtor ?
getSymbolDeclaredBy(ownerFn) :
getSymbolForInstancesOf(ownerFn);
} else if (type.isFunctionType()) {
return linkToCtor ?
globalScope.getSlot("Function") :
globalScope.getQualifiedSlot("Function.prototype");
} else if (type.autoboxesTo() != null) {
return getSymbolForTypeHelper(type.autoboxesTo(), linkToCtor);
} else {
return null;
}
}
@SuppressWarnings("unused")
public String toDebugString() {
StringBuilder builder = new StringBuilder();
for (Symbol symbol : getAllSymbols()) {
toDebugString(builder, symbol);
}
return builder.toString();
}
private void toDebugString(StringBuilder builder, Symbol symbol) {
SymbolScope scope = symbol.scope;
if (scope.isGlobalScope()) {
builder.append(
SimpleFormat.format("'%s' : in global scope:\n", symbol.getName()));
} else if (scope.getRootNode() != null) {
builder.append(
SimpleFormat.format("'%s' : in scope %s:%d\n",
symbol.getName(),
scope.getRootNode().getSourceFileName(),
scope.getRootNode().getLineno()));
} else if (scope.getSymbolForScope() != null) {
builder.append(
SimpleFormat.format("'%s' : in scope %s\n", symbol.getName(),
scope.getSymbolForScope().getName()));
} else {
builder.append(
SimpleFormat.format("'%s' : in unknown scope\n", symbol.getName()));
}
int refCount = 0;
for (Reference ref : getReferences(symbol)) {
builder.append(
SimpleFormat.format(" Ref %d: %s:%d\n",
refCount,
ref.getNode().getSourceFileName(),
ref.getNode().getLineno()));
refCount++;
}
}
/**
* Make sure all the given scopes in {@code otherSymbolTable}
* are in this symbol table.
*/
<S extends StaticScope> void addScopes(Collection<S> scopes) {
for (S scope : scopes) {
createScopeFrom(scope);
}
}
/** Finds all the scopes and adds them to this symbol table. */
void findScopes(Node externs, Node root) {
NodeTraversal t =
new NodeTraversal(
compiler,
new NodeTraversal.AbstractScopedCallback() {
@Override
public void enterScope(NodeTraversal t) {
createScopeFrom(t.getScope());
}
@Override
public void visit(NodeTraversal t, Node n, Node p) {}
},
SyntacticScopeCreator.makeUntyped(compiler));
t.traverseRoots(externs, root);
}
/** Gets all the scopes in this symbol table. */
public Collection<SymbolScope> getAllScopes() {
return Collections.unmodifiableCollection(scopes.values());
}
/**
* Finds anonymous functions in local scopes, and gives them names
* and symbols. They will show up as local variables with names
* "function%0", "function%1", etc.
*/
public void addAnonymousFunctions() {
TreeSet<SymbolScope> scopes = new TreeSet<>(lexicalScopeOrdering);
for (SymbolScope scope : getAllScopes()) {
if (scope.isLexicalScope()) {
scopes.add(scope);
}
}
for (SymbolScope scope : scopes) {
addAnonymousFunctionsInScope(scope);
}
}
private void addAnonymousFunctionsInScope(SymbolScope scope) {
Symbol sym = getSymbolForScope(scope);
if (sym == null) {
// JSCompiler has no symbol for this scope. Check to see if it's a
// local function. If it is, give it a name.
if (scope.isLexicalScope() &&
!scope.isGlobalScope() &&
scope.getRootNode() != null &&
!scope.getRootNode().isFromExterns() &&
scope.getParentScope() != null) {
SymbolScope parent = scope.getParentScope();
int count = parent.innerAnonFunctionsWithNames++;
String innerName = "function%" + count;
scope.setSymbolForScope(
declareInferredSymbol(
parent, innerName, scope.getRootNode()));
}
}
}
/**
* Make sure all the symbols and references in {@code otherSymbolTable}
* are in this symbol table.
*
* Uniqueness of symbols and references is determined by the associated
* node.
*
* If multiple symbol tables are mixed in, we do not check for consistency
* between symbol tables. The first symbol we see dictates the type
* information for that symbol.
*/
<S extends StaticSlot, R extends StaticRef>
void addSymbolsFrom(StaticSymbolTable<S, R> otherSymbolTable) {
for (S otherSymbol : otherSymbolTable.getAllSymbols()) {
String name = otherSymbol.getName();
SymbolScope myScope = createScopeFrom(
otherSymbolTable.getScope(otherSymbol));
StaticRef decl = findBestDeclToAdd(otherSymbolTable, otherSymbol);
Symbol mySymbol = null;
if (decl != null) {
Node declNode = decl.getNode();
// If we have a declaration node, we can ensure the symbol is declared.
mySymbol = isAnySymbolDeclared(name, declNode, myScope);
if (mySymbol == null) {
mySymbol = copySymbolTo(otherSymbol, declNode, myScope);
}
} else {
// If we don't have a declaration node, we won't be able to declare
// a symbol in this symbol table. But we may be able to salvage the
// references if we already have a symbol.
mySymbol = myScope.getOwnSlot(name);
}
if (mySymbol != null) {
for (R otherRef : otherSymbolTable.getReferences(otherSymbol)) {
if (isGoodRefToAdd(otherRef)) {
mySymbol.defineReferenceAt(otherRef.getNode());
}
}
}
}
}
/**
* Checks if any symbol is already declared at the given node and scope
* for the given name. If so, returns it.
*/
private Symbol isAnySymbolDeclared(
String name, Node declNode, SymbolScope scope) {
Symbol sym = symbols.get(declNode, name);
if (sym == null) {
// Sometimes, our symbol tables will disagree on where the
// declaration node should be. In the rare case where this happens,
// trust the existing symbol.
// See SymbolTableTest#testDeclarationDisagreement.
return scope.ownSymbols.get(name);
}
return sym;
}
/** Helper for addSymbolsFrom, to determine the best declaration spot. */
private <S extends StaticSlot, R extends StaticRef>
StaticRef findBestDeclToAdd(StaticSymbolTable<S, R> otherSymbolTable, S slot) {
StaticRef decl = slot.getDeclaration();
if (isGoodRefToAdd(decl)) {
return decl;
}
for (R ref : otherSymbolTable.getReferences(slot)) {
if (isGoodRefToAdd(ref)) {
return ref;
}
}
return null;
}
/**
* Helper for addSymbolsFrom, to determine whether a reference is
* acceptable. A reference must be in the normal source tree.
*/
private boolean isGoodRefToAdd(@Nullable StaticRef ref) {
return ref != null && ref.getNode() != null
&& ref.getNode().getStaticSourceFile() != null
&& !Compiler.SYNTHETIC_EXTERNS.equals(
ref.getNode().getStaticSourceFile().getName());
}
private Symbol copySymbolTo(StaticSlot sym, SymbolScope scope) {
return copySymbolTo(sym, sym.getDeclaration().getNode(), scope);
}
private Symbol copySymbolTo(
StaticSlot sym, Node declNode, SymbolScope scope) {
// All symbols must have declaration nodes.
checkNotNull(declNode);
return declareSymbol(
sym.getName(), getType(sym), isTypeInferred(sym), scope, declNode,
sym.getJSDocInfo());
}
private Symbol addSymbol(
String name, JSType type, boolean inferred, SymbolScope scope,
Node declNode) {
Symbol symbol = new Symbol(name, type, inferred, scope);
Symbol replacedSymbol = symbols.put(declNode, name, symbol);
Preconditions.checkState(
replacedSymbol == null,
"Found duplicate symbol %s in global index. Type %s", name, type);
replacedSymbol = scope.ownSymbols.put(name, symbol);
Preconditions.checkState(
replacedSymbol == null,
"Found duplicate symbol %s in its scope. Type %s", name, type);
return symbol;
}
private Symbol declareSymbol(
String name, JSType type, boolean inferred,
SymbolScope scope, Node declNode, JSDocInfo info) {
Symbol symbol = addSymbol(name, type, inferred, scope, declNode);
symbol.setJSDocInfo(info);
symbol.setDeclaration(symbol.defineReferenceAt(declNode));
return symbol;
}
private void removeSymbol(Symbol s) {
SymbolScope scope = getScope(s);
if (!scope.ownSymbols.remove(s.getName()).equals(s)) {
throw new IllegalStateException("Symbol not found in scope " + s);
}
if (!symbols.remove(s.getDeclaration().getNode(), s.getName()).equals(s)) {
throw new IllegalStateException("Symbol not found in table " + s);
}
// If s declares a property scope then all child symbols should be removed as well.
// For example:
// let foo = {a: 1, b: 2};
// foo declares property scope with a and b as its children. When removing foo we should also
// remove a and b.
if (s.propertyScope != null && s.propertyScope.getSymbolForScope().equals(s)) {
// Need to iterate over copy of values list because removeSymbol() will change the map
// and we'll get ConcurrentModificationException
for (Symbol childSymbol : ImmutableList.copyOf(s.propertyScope.ownSymbols.values())) {
removeSymbol(childSymbol);
}
scopes.remove(s.getDeclarationNode());
}
}
/**
* Not all symbol tables record references to "namespace" objects.
* For example, if you have:
* goog.dom.DomHelper = function() {};
* The symbol table may not record that as a reference to "goog.dom",
* because that would be redundant.
*/
void fillNamespaceReferences() {
for (Symbol symbol : getAllSymbolsSorted()) {
String qName = symbol.getName();
int rootIndex = qName.indexOf('.');
if (rootIndex == -1) {
continue;
}
Symbol root = symbol.scope.getQualifiedSlot(
qName.substring(0, rootIndex));
if (root == null) {
// In theory, this should never happen, but we fail quietly anyway
// just to be safe.
continue;
}
for (Reference ref : getReferences(symbol)) {
Node currentNode = ref.getNode();
if (!currentNode.isQualifiedName()) {
continue;
}
while (currentNode.isGetProp()) {
currentNode = currentNode.getFirstChild();
String name = currentNode.getQualifiedName();
if (name != null) {
Symbol namespace =
isAnySymbolDeclared(name, currentNode, root.scope);
if (namespace == null) {
namespace = root.scope.getQualifiedSlot(name);
}
if (namespace == null && root.scope.isGlobalScope()) {
namespace = declareSymbol(name,
registry.getNativeType(JSTypeNative.UNKNOWN_TYPE),
true,
root.scope,
currentNode,
null /* JsDoc info */);
}
if (namespace != null) {
namespace.defineReferenceAt(currentNode);
}
}
}
}
}
}
@SuppressWarnings("ReferenceEquality")
void fillPropertyScopes() {
// Collect all object symbols.
// All symbols that came from goog.module are collected separately because they will have to
// be processed first. See explanation below.
List<Symbol> types = new ArrayList<>();
List<Symbol> googModuleExportTypes = new ArrayList<>();
// Create a property scope for each named type and each anonymous object,
// and populate it with that object's properties.
//
// We notably don't want to create a property scope for 'x' in
// var x = new Foo();
// where x is just an instance of another type.
for (Symbol sym : getAllSymbols()) {
if (needsPropertyScope(sym)) {
if (sym.getName().startsWith("module$exports")) {
googModuleExportTypes.add(sym);
} else {
types.add(sym);
}
}
}
// The order of operations here is significant.
//
// When we add properties to Foo, we'll remove Foo.prototype from
// the symbol table and replace it with a fresh symbol in Foo's
// property scope. So the symbol for Foo.prototype in
// {@code instances} will be stale.
//
// To prevent this, we sort the list by the reverse of the
// default symbol order, which will do the right thing. Essentially going from leaf symbols
// to roots.
//
// Also sorting all symbols is not enough. There is a tricky case with symbols declared in
// goog.module that also has declareLegacyNamespace. Example:
//
// goog.module('x.y');
// goog.module.declareLegacyNamespace();
// exports.foo = function() {};
//
// Symbols are following:
// x.y
// x
// module$exports$x$y.foo
// module$exports$x$y
//
// If we order them in reverse lexicographical order symbols x.y and x will be processed before
// foo. This is wrong as foo is in fact property of x.y namespace. So we must process all
// module$exports$ symbols first. That's why we collected them in a separate list.
//
Collections.sort(types, getNaturalSymbolOrdering().reverse());
Collections.sort(googModuleExportTypes, getNaturalSymbolOrdering().reverse());
Iterable<Symbol> allTypes = Iterables.concat(googModuleExportTypes, types);
// If you though we are done with tricky case - you were wrong. There is another one!
// The problem with the same property scope appearing several times. For example when using
// aliases:
//
// const OBJ = {one: 1};
// function() {
// const alias = OBJ;
// console.log(alias.one);
// }
//
// In this case both 'OBJ' and 'alias' are considered property scopes and are candidates for
// processing even though they share the same "type" which is "{one: 1}". As they share the same
// type we need to process only one of them. To do that we build a "type => root symbol" map.
// In this case the map will be {one: 1} => OBJ. Using this map will skip 'alias' when creating
// property scopes.
//
// NOTE: we are using IdentityHashMap to compare types using == because we need to find symbols
// that point to the exact same type instance.
Map<JSType, Symbol> symbolThatDeclaresType = new IdentityHashMap<>();
for (Symbol s : allTypes) {
// Symbols are sorted in reverse order so that those with more outer scope will come later in
// the list, and therefore override those set by aliases in more inner scope. The sorting
// happens few lines above.
symbolThatDeclaresType.put(s.getType(), s);
}
for (Symbol s : allTypes) {
// Create property scopes only based on "root" symbols for each type to handle aliases.
if (s.getType() == null || symbolThatDeclaresType.get(s.getType()).equals(s)) {
createPropertyScopeFor(s);
}
}
// Now we need to set the new property scope symbol to all aliases.
for (Symbol s : allTypes) {
if (s.getType() != null) {
s.propertyScope = symbolThatDeclaresType.get(s.getType()).getPropertyScope();
}
}
pruneOrphanedNames();
}
private boolean needsPropertyScope(Symbol sym) {
ObjectType type = ObjectType.cast(getType(sym));
if (type == null) {
return false;
}
// Anonymous objects
if (type.getReferenceName() == null) {
return true;
}
// Constructors/prototypes
// Should this check for
// (type.isNominalConstructor() || type.isFunctionPrototypeType())
// ?
if (sym.getName().equals(type.getReferenceName())) {
return true;
}
// Enums
return type.isEnumType()
&& sym.getName().equals(type.toMaybeEnumType().getElementsType().getReferenceName());
}
/**
* Removes symbols where the namespace they're on has been removed.
*
* After filling property scopes, we may have two symbols represented
* in different ways. For example, "A.superClass_.foo" and B.prototype.foo".
*
* This resolves that ambiguity by pruning the duplicates.
* If we have a lexical symbol with a constructor in its property
* chain, then we assume there's also a property path to this symbol.
* In other words, we can remove "A.superClass_.foo" because it's rooted
* at "A", and we built a property scope for "A" above.
*/
void pruneOrphanedNames() {
nextSymbol: for (Symbol s : getAllSymbolsSorted()) {
if (s.isProperty()) {
continue;
}
String currentName = s.getName();
int dot = -1;
while (-1 != (dot = currentName.lastIndexOf('.'))) {
currentName = currentName.substring(0, dot);
Symbol owner = s.scope.getQualifiedSlot(currentName);
if (owner != null
&& getType(owner) != null
&& (getType(owner).isNominalConstructor() ||
getType(owner).isFunctionPrototypeType() ||
getType(owner).isEnumType())) {
removeSymbol(s);
continue nextSymbol;
}
}
}
}
/**
* Create symbols and references for all properties of types in
* this symbol table.
*
* This gets a little bit tricky, because of the way this symbol table
* conflates "type Foo" and "the constructor of type Foo". So if you
* have:
*
* <code>
* SymbolTable symbolTable = for("var x = new Foo();");
* Symbol x = symbolTable.getGlobalScope().getSlot("x");
* Symbol type = symbolTable.getAllSymbolsForType(getType(x)).get(0);
* </code>
*
* Then type.getPropertyScope() will have the properties of the
* constructor "Foo". To get the properties of instances of "Foo",
* you will need to call:
*
* <code>
* Symbol instance = symbolTable.getSymbolForInstancesOf(type);
* </code>
*
* As described at the top of this file, notice that "new Foo()" and
* "Foo.prototype" are represented by the same symbol.
*/
void fillPropertySymbols(Node externs, Node root) {
(new PropertyRefCollector()).process(externs, root);
}
/** Index JSDocInfo. */
void fillJSDocInfo(Node externs, Node root) {
NodeTraversal t =
new NodeTraversal(
compiler,
new JSDocInfoCollector(compiler.getTypeRegistry()),
SyntacticScopeCreator.makeUntyped(compiler));
t.traverseRoots(externs, root);
// Create references to parameters in the JSDoc.
for (Symbol sym : getAllSymbolsSorted()) {
JSDocInfo info = sym.getJSDocInfo();
if (info == null) {
continue;
}
for (Marker marker : info.getMarkers()) {
SourcePosition<Node> pos = marker.getNameNode();
if (pos == null) {
continue;
}
Node paramNode = pos.getItem();
String name = paramNode.getString();
Symbol param = getParameterInFunction(sym, name);
if (param == null) {
// There is no reference to this parameter in the actual JavaScript
// code, so we'll try to create a special JsDoc-only symbol in
// a JsDoc-only scope.
SourcePosition<Node> typePos = marker.getType();
JSType type = null;
if (typePos != null) {
type = typePos.getItem().getJSType();
}
if (sym.docScope == null) {
sym.docScope = new SymbolScope(null /* root */,
null /* parent scope */, null /* type of this */, sym);
}
// Check to make sure there's no existing symbol. In theory, this
// should never happen, but we check anyway and fail silently
// if our assumptions are wrong. (We do not want to put the symbol
// table into an invalid state).
Symbol existingSymbol =
isAnySymbolDeclared(name, paramNode, sym.docScope);
if (existingSymbol == null) {
declareSymbol(name, type, type == null, sym.docScope, paramNode,
null /* info */);
}
} else {
param.defineReferenceAt(paramNode);
}
}
}
}
/** Records the visibility of each symbol. */
void fillSymbolVisibility(Node externs, Node root) {
CollectFileOverviewVisibility collectPass =
new CollectFileOverviewVisibility(compiler);
collectPass.process(externs, root);