-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
TypedScopeCreator.java
3162 lines (2836 loc) · 128 KB
/
TypedScopeCreator.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 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.jscomp.TypeCheck.MULTIPLE_VAR_DEF;
import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_OBJECT_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.DATE_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.FUNCTION_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.GENERATOR_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.GLOBAL_THIS;
import static com.google.javascript.rhino.jstype.JSTypeNative.ITERABLE_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ITERATOR_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NO_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_OBJECT_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.REGEXP_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.REGEXP_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_OBJECT_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Table;
import com.google.javascript.jscomp.CodingConvention.DelegateRelationship;
import com.google.javascript.jscomp.CodingConvention.ObjectLiteralCast;
import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
import com.google.javascript.jscomp.FunctionTypeBuilder.AstFunctionContents;
import com.google.javascript.jscomp.NodeTraversal.AbstractScopedCallback;
import com.google.javascript.jscomp.NodeTraversal.AbstractShallowStatementCallback;
import com.google.javascript.jscomp.modules.Binding;
import com.google.javascript.jscomp.modules.Export;
import com.google.javascript.jscomp.modules.Module;
import com.google.javascript.jscomp.modules.ModuleMap;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.InputId;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.NominalTypeBuilder;
import com.google.javascript.rhino.QualifiedName;
import com.google.javascript.rhino.StaticSymbolTable;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.EnumType;
import com.google.javascript.rhino.jstype.FunctionParamBuilder;
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.Property;
import com.google.javascript.rhino.jstype.StaticTypedScope;
import com.google.javascript.rhino.jstype.TemplateType;
import com.google.javascript.rhino.jstype.TemplateTypeMap;
import com.google.javascript.rhino.jstype.TemplateTypeMapReplacer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.annotation.Nullable;
/**
* Creates the symbol table of variables available in the current scope and their types.
*
* <p>Scopes created by this class are very different from scopes created by the syntactic scope
* creator. These scopes have type information, and include some qualified names in addition to
* variables (like Class.staticMethod).
*
* <p>When building scope information, also declares relevant information about types in the type
* registry.
*
* @author nicksantos@google.com (Nick Santos)
*/
final class TypedScopeCreator implements ScopeCreator, StaticSymbolTable<TypedVar, TypedVar> {
/** A suffix for naming delegate proxies differently from their base. */
static final String DELEGATE_PROXY_SUFFIX = ObjectType.createDelegateSuffix("Proxy");
static final DiagnosticType MALFORMED_TYPEDEF =
DiagnosticType.warning(
"JSC_MALFORMED_TYPEDEF",
"Typedef for {0} does not have any type information");
static final DiagnosticType ENUM_INITIALIZER =
DiagnosticType.warning(
"JSC_ENUM_INITIALIZER_NOT_ENUM",
"enum initializer must be an object literal or an enum");
static final DiagnosticType INVALID_ENUM_KEY =
DiagnosticType.warning(
"JSC_INVALID_ENUM_KEY", "enum key must be a string or numeric literal");
static final DiagnosticType CTOR_INITIALIZER =
DiagnosticType.warning(
"JSC_CTOR_INITIALIZER_NOT_CTOR",
"Constructor {0} must be initialized at declaration");
static final DiagnosticType IFACE_INITIALIZER =
DiagnosticType.warning(
"JSC_IFACE_INITIALIZER_NOT_IFACE",
"Interface {0} must be initialized at declaration");
static final DiagnosticType CONSTRUCTOR_EXPECTED =
DiagnosticType.warning(
"JSC_REFLECT_CONSTRUCTOR_EXPECTED",
"Constructor expected as first argument");
static final DiagnosticType UNKNOWN_LENDS =
DiagnosticType.warning(
"JSC_UNKNOWN_LENDS",
"Variable {0} not declared before @lends annotation.");
static final DiagnosticType LENDS_ON_NON_OBJECT =
DiagnosticType.warning(
"JSC_LENDS_ON_NON_OBJECT",
"May only lend properties to object types. {0} has type {1}.");
static final DiagnosticType INCOMPATIBLE_ALIAS_ANNOTATION =
DiagnosticType.warning(
"JSC_INCOMPATIBLE_ALIAS_ANNOTATION",
"Annotation {0} on {1} incompatible with aliased type.");
static final DiagnosticType DYNAMIC_EXTENDS_WITHOUT_JSDOC =
DiagnosticType.warning(
"JSC_DYNAMIC_EXTENDS_WITHOUT_JSDOC",
"The right-hand side of an extends clause must be a qualified name, or else @extends must"
+ " be specified in JSDoc");
static final DiagnosticType CONFLICTING_GETTER_SETTER_TYPE =
DiagnosticType.warning(
"JSC_CONFLICTING_GETTER_SETTER_TYPE",
"The types of the getter and setter for property ''{0}'' do not match.\n"
+ "getter type is: {1}\n"
+ "setter type is: {2}");
static final DiagnosticGroup ALL_DIAGNOSTICS = new DiagnosticGroup(
DELEGATE_PROXY_SUFFIX,
MALFORMED_TYPEDEF,
ENUM_INITIALIZER,
CTOR_INITIALIZER,
IFACE_INITIALIZER,
CONSTRUCTOR_EXPECTED,
UNKNOWN_LENDS,
LENDS_ON_NON_OBJECT,
INCOMPATIBLE_ALIAS_ANNOTATION,
DYNAMIC_EXTENDS_WITHOUT_JSDOC);
private final AbstractCompiler compiler;
private final ErrorReporter typeParsingErrorReporter;
private final TypeValidator validator;
private final CodingConvention codingConvention;
private final JSTypeRegistry typeRegistry;
private final ModuleMap moduleMap;
private final ModuleImportResolver moduleImportResolver;
private final List<FunctionType> delegateProxyCtors = new ArrayList<>();
private final Map<String, String> delegateCallingConventions = new HashMap<>();
private final Map<Node, TypedScope> memoized = new LinkedHashMap<>();
// Set of functions with non-empty returns, for passing to FunctionTypeBuilder.
private final Set<Node> functionsWithNonEmptyReturns = new HashSet<>();
// Includes both simple and qualified names.
private final Set<ScopedName> escapedVarNames = new HashSet<>();
// Count of how many times each variable is assigned, for marking effectively final.
private final Multiset<ScopedName> assignedVarNames = HashMultiset.create();
// For convenience
private final ObjectType unknownType;
private final List<DeferredSetType> deferredSetTypes = new ArrayList<>();
// Set of NAME, GETPROP, and STRING_KEY lvalues which should be treated as const declarations when
// assigned. Treat simple names in this list as if they were declared `const`. E.g. treat `exports
// = class {};` as `const exports = class {};`. Treat GETPROP and STRING_KEY nodes as if they were
// annotated @const.
private final Set<Node> undeclaredNamesForClosure = new HashSet<>();
/**
* Defer attachment of types to nodes until all type names
* have been resolved. Then, we can resolve the type and attach it.
*/
private class DeferredSetType {
final Node node;
final JSType type;
DeferredSetType(Node node, JSType type) {
checkNotNull(node);
checkNotNull(type);
this.node = node;
this.type = type;
}
void resolve() {
node.setJSType(type.resolve(typeParsingErrorReporter));
}
}
/** Stores the type and qualified name for a destructuring rvalue. */
private static class RValueInfo {
@Nullable final JSType type;
@Nullable final QualifiedName qualifiedName;
RValueInfo(JSType type, QualifiedName qualifiedName) {
this.type = type;
this.qualifiedName = qualifiedName;
}
static RValueInfo empty() {
return new RValueInfo(null, null);
}
}
TypedScopeCreator(AbstractCompiler compiler) {
this(compiler, compiler.getCodingConvention());
}
TypedScopeCreator(AbstractCompiler compiler, CodingConvention codingConvention) {
this.compiler = compiler;
this.validator = compiler.getTypeValidator();
this.codingConvention = codingConvention;
this.typeRegistry = compiler.getTypeRegistry();
this.typeParsingErrorReporter = typeRegistry.getErrorReporter();
this.unknownType = typeRegistry.getNativeObjectType(UNKNOWN_TYPE);
this.moduleMap = compiler.getModuleMap();
this.moduleImportResolver = new ModuleImportResolver(this.moduleMap, getNodeToScopeMapper());
}
private void report(JSError error) {
compiler.report(error);
}
@Override
public ImmutableList<TypedVar> getReferences(TypedVar var) {
return ImmutableList.of(var);
}
@Override
public TypedScope getScope(TypedVar var) {
return var.scope;
}
@Override
public Iterable<TypedVar> getAllSymbols() {
List<TypedVar> vars = new ArrayList<>();
for (TypedScope s : memoized.values()) {
Iterables.addAll(vars, s.getAllSymbols());
}
return vars;
}
/**
* Returns a function mapping a scope root node to a {@link TypedScope}.
*
* <p>This method mostly exists in lieu of an interface representing root node -> scope.
*/
public Function<Node, TypedScope> getNodeToScopeMapper() {
return memoized::get;
}
Collection<TypedScope> getAllMemoizedScopes() {
// Return scopes in reverse order of creation so that IIFEs will
// come before the global scope.
return Lists.reverse(ImmutableList.copyOf(memoized.values()));
}
/**
* Removes all scopes with root nodes from a given script file.
*
* @param scriptName the name of the script file to remove nodes for.
*/
void removeScopesForScript(String scriptName) {
memoized.keySet().removeIf(n -> scriptName.equals(NodeUtil.getSourceName(n)));
}
/** Create a scope if it doesn't already exist, looking up in the map for the parent scope. */
TypedScope createScope(Node n) {
TypedScope s = memoized.get(n);
return s != null
? s
: createScope(n, createScope(NodeUtil.getEnclosingScopeRoot(n.getParent())));
}
/**
* Creates a scope with all types declared. Declares newly discovered types
* and type properties in the type registry.
*/
@Override
public TypedScope createScope(Node root, AbstractScope<?, ?> parent) {
checkArgument(parent == null || parent instanceof TypedScope);
TypedScope typedParent = (TypedScope) parent;
TypedScope scope = memoized.get(root);
if (scope != null) {
checkState(typedParent == scope.getParent());
} else {
scope = createScopeInternal(root, typedParent);
memoized.put(root, scope);
}
return scope;
}
private TypedScope createScopeInternal(Node root, TypedScope typedParent) {
// Constructing the global scope is very different than constructing
// inner scopes, because only global scopes can contain named classes that
// show up in the type registry.
TypedScope newScope = null;
AbstractScopeBuilder scopeBuilder = null;
if (typedParent == null) {
JSType globalThis =
typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS);
// Mark the main root, the externs root, and the src root
// with the global this type.
root.setJSType(globalThis);
root.getFirstChild().setJSType(globalThis);
root.getLastChild().setJSType(globalThis);
// Run a first-order analysis over the syntax tree.
new FirstOrderFunctionAnalyzer().process(root.getFirstChild(), root.getLastChild());
// Find all the classes in the global scope.
newScope = createInitialScope(root);
} else {
newScope = new TypedScope(typedParent, root);
}
if (root.isModuleBody()) {
initializeModuleScope(root, newScope);
}
if (root.isFunction()) {
scopeBuilder = new FunctionScopeBuilder(newScope);
} else if (root.isClass()) {
scopeBuilder = new ClassScopeBuilder(newScope);
} else {
scopeBuilder = new NormalScopeBuilder(newScope);
}
scopeBuilder.build();
if (typedParent == null) {
List<NominalTypeBuilder> delegateProxies = new ArrayList<>();
for (FunctionType delegateProxyCtor : delegateProxyCtors) {
delegateProxies.add(
new NominalTypeBuilder(delegateProxyCtor, delegateProxyCtor.getInstanceType()));
}
codingConvention.defineDelegateProxyPrototypeProperties(
typeRegistry, delegateProxies, delegateCallingConventions);
}
return newScope;
}
/** Builds the beginning of a module-scope. This can be an ES module or a goog.module. */
private void initializeModuleScope(Node moduleBody, TypedScope moduleScope) {
Node scriptNode = moduleBody.getParent();
if (scriptNode.getBooleanProp(Node.GOOG_MODULE)) {
Node googModuleCall = moduleBody.getFirstChild();
Node namespace = googModuleCall.getFirstChild().getSecondChild();
String closureModuleNamespace = namespace.getString();
Module module = moduleMap.getClosureModule(closureModuleNamespace);
declareExportsInModuleScope(module, moduleBody, moduleScope);
markGoogModuleExportsAsConst(module);
}
}
/**
* Ensures that the name `exports` is declared in goog.module scope.
*
* <p>If a goog.module explicitly assigns to exports, we want to treat that assignment inside the
* scope as if it were a declaration: `const exports = ...`. This method only handles cases where
* we want to treat exports as implicitly declared.
*/
private void declareExportsInModuleScope(
Module googModule, Node moduleBody, TypedScope moduleScope) {
if (!googModule.namespace().containsKey(Export.NAMESPACE)) {
// The goog.module never assigns `exports = ...`, so declare `exports` as an object literal.
moduleScope.declare(
"exports",
googModule.metadata().rootNode(),
typeRegistry.createAnonymousObjectType(null),
compiler.getInput(moduleBody.getInputId()),
/* inferred= */ false);
}
}
/**
* Adds nodes representing goog.module exports to a list, to treat them as @const.
*
* <p>This method handles the following styles of exports:
*
* <ul>
* <li>{@code exports = class {}} adds the NAME node `exports`
* <li>{@code exports = {Foo};} adds the NAME node `exports` and the STRING_KEY node `Foo`
* <li>{@code exports.Foo = Foo;} adds the GETPROP node `exports.Foo`
* </ul>
*/
private void markGoogModuleExportsAsConst(Module googModule) {
for (Binding binding : googModule.namespace().values()) {
Node exportedNode = binding.originatingExport().exportNode();
undeclaredNamesForClosure.add(exportedNode);
}
}
/**
* Patches a given global scope by removing variables previously declared in
* a script and re-traversing a new version of that script.
*
* @param globalScope The global scope generated by {@code createScope}.
* @param scriptRoot The script that is modified.
*/
void patchGlobalScope(TypedScope globalScope, Node scriptRoot) {
// Preconditions: This is supposed to be called only on (named) SCRIPT nodes
// and a global typed scope should have been generated already.
checkState(scriptRoot.isScript());
checkNotNull(globalScope);
checkState(globalScope.isGlobal());
String scriptName = NodeUtil.getSourceName(scriptRoot);
checkNotNull(scriptName);
Predicate<Node> inScript = n -> scriptName.equals(NodeUtil.getSourceName(n));
escapedVarNames.removeIf(var -> inScript.test(var.getScopeRoot()));
assignedVarNames.removeIf(var -> inScript.test(var.getScopeRoot()));
functionsWithNonEmptyReturns.removeIf(inScript);
new FirstOrderFunctionAnalyzer().process(null, scriptRoot);
// TODO(bashir): Variable declaration is not the only side effect of last
// global scope generation but here we only wipe that part off.
// Remove all variables that were previously declared in this scripts.
// First find all vars to remove then remove them because of iterator.
List<TypedVar> varsToRemove = new ArrayList<>();
for (TypedVar oldVar : globalScope.getVarIterable()) {
if (scriptName.equals(oldVar.getInputName())) {
varsToRemove.add(oldVar);
}
}
for (TypedVar var : varsToRemove) {
// By removing the type here, we're potentially invalidating any files that contain
// references to this type. Those files will need to be recompiled. Ideally, this
// was handled by the compiler (see b/29121507), but in the meantime users of incremental
// compilation will need to manage it themselves (e.g., by recompiling dependent files
// based on the dep graph).
String typeName = var.getName();
globalScope.undeclare(var);
globalScope.getTypeOfThis().toObjectType().removeProperty(typeName);
if (typeRegistry.getType(globalScope, typeName) != null) {
typeRegistry.removeType(globalScope, typeName);
}
}
// Now re-traverse the given script.
NormalScopeBuilder scopeBuilder = new NormalScopeBuilder(globalScope);
NodeTraversal.traverse(compiler, scriptRoot, scopeBuilder);
}
/**
* Create the outermost scope. This scope contains native binding such as {@code Object}, {@code
* Date}, etc.
*/
@VisibleForTesting
TypedScope createInitialScope(Node root) {
NodeTraversal.traverse(
compiler,
root,
new IdentifyGlobalEnumsAndTypedefsAsNonNullable(typeRegistry, codingConvention));
TypedScope s = TypedScope.createGlobalScope(root);
declareNativeFunctionType(s, ARRAY_FUNCTION_TYPE);
declareNativeFunctionType(s, BOOLEAN_OBJECT_FUNCTION_TYPE);
declareNativeFunctionType(s, DATE_FUNCTION_TYPE);
declareNativeFunctionType(s, FUNCTION_FUNCTION_TYPE);
declareNativeFunctionType(s, GENERATOR_FUNCTION_TYPE);
declareNativeFunctionType(s, ITERABLE_FUNCTION_TYPE);
declareNativeFunctionType(s, ITERATOR_FUNCTION_TYPE);
declareNativeFunctionType(s, NUMBER_OBJECT_FUNCTION_TYPE);
declareNativeFunctionType(s, OBJECT_FUNCTION_TYPE);
declareNativeFunctionType(s, REGEXP_FUNCTION_TYPE);
declareNativeFunctionType(s, STRING_OBJECT_FUNCTION_TYPE);
declareNativeValueType(s, "undefined", VOID_TYPE);
return s;
}
private void declareNativeFunctionType(TypedScope scope, JSTypeNative tId) {
FunctionType t = typeRegistry.getNativeFunctionType(tId);
declareNativeType(scope, t.getInstanceType().getReferenceName(), t);
declareNativeType(
scope, t.getPrototype().getReferenceName(), t.getPrototype());
}
private void declareNativeValueType(TypedScope scope, String name,
JSTypeNative tId) {
declareNativeType(scope, name, typeRegistry.getNativeType(tId));
}
private static void declareNativeType(TypedScope scope, String name, JSType t) {
scope.declare(name, null, t, null, false);
}
/** Set the type for a node now, and enqueue it to be updated with a resolved type later. */
void setDeferredType(Node node, JSType type) {
// Other parts of this pass may read the not-yet-resolved type off the node.
// (like when we set the LHS of an assign with a typed RHS function.)
node.setJSType(type);
deferredSetTypes.add(new DeferredSetType(node, type));
}
void resolveTypes() {
// Resolve types and attach them to nodes.
for (DeferredSetType deferred : deferredSetTypes) {
deferred.resolve();
}
// Resolve types and attach them to scope slots.
for (TypedScope scope : getAllMemoizedScopes()) {
for (TypedVar var : scope.getVarIterable()) {
var.resolveType(typeParsingErrorReporter);
}
}
// Tell the type registry that any remaining types are unknown.
typeRegistry.resolveTypes();
}
/**
* Adds all globally-defined enums and typedefs to the registry's list of non-nullable types.
*
* <p>TODO(b/123710194): We should also make locally-defined enums and typedefs non-nullable.
*/
private static class IdentifyGlobalEnumsAndTypedefsAsNonNullable
extends AbstractShallowStatementCallback {
private final JSTypeRegistry registry;
private final CodingConvention codingConvention;
IdentifyGlobalEnumsAndTypedefsAsNonNullable(
JSTypeRegistry registry, CodingConvention codingConvention) {
this.registry = registry;
this.codingConvention = codingConvention;
}
@Override
public void visit(NodeTraversal t, Node node, Node parent) {
switch (node.getToken()) {
case LET:
case CONST:
case VAR:
// Note that this class expects to be invoked on the root node and does not traverse into
// functions.
Scope scope = t.getScope();
if (!(scope.isGlobal() || scope.getClosestHoistScope().isGlobal())) {
return;
}
if (node.isVar() || scope.isGlobal()) {
for (Node child = node.getFirstChild(); child != null; child = child.getNext()) {
// TODO(b/116853368): make this work for destructuring aliases as well.
identifyEnumOrTypedefDeclaration(
child, child.getFirstChild(), NodeUtil.getBestJSDocInfo(child));
}
}
break;
case EXPR_RESULT:
Node firstChild = node.getFirstChild();
if (firstChild.isAssign()) {
Node assign = firstChild;
identifyEnumOrTypedefDeclaration(
assign.getFirstChild(), assign.getSecondChild(), assign.getJSDocInfo());
} else {
identifyEnumOrTypedefDeclaration(
firstChild, /* rvalue= */ null, firstChild.getJSDocInfo());
}
break;
default:
break;
}
}
private void identifyEnumOrTypedefDeclaration(
Node nameNode, @Nullable Node rvalue, JSDocInfo info) {
if (!nameNode.isQualifiedName()) {
return;
}
if (info != null && info.hasEnumParameterType()) {
registry.identifyNonNullableName(nameNode.getQualifiedName());
} else if (info != null && info.hasTypedefType()) {
registry.identifyNonNullableName(nameNode.getQualifiedName());
} else if (rvalue != null
&& rvalue.isQualifiedName()
&& registry.isNonNullableName(rvalue.getQualifiedName())
&& NodeUtil.isConstantDeclaration(codingConvention, info, nameNode)) {
registry.identifyNonNullableName(nameNode.getQualifiedName());
}
}
}
private JSType getNativeType(JSTypeNative nativeType) {
return typeRegistry.getNativeType(nativeType);
}
private abstract class AbstractScopeBuilder implements NodeTraversal.Callback {
/** The scope that we're building. */
final TypedScope currentScope;
/** The current hoist scope. */
final TypedScope currentHoistScope;
/** The current source file that we're in. */
private String sourceName = null;
/** The InputId of the current node. */
private InputId inputId;
/**
* Some actions need to be deferred, such as analyzing object literals with
* lends annotations, or resolving type-less stubs. These actions are added
* to this map, keyed by the node that should be waited for before running.
*/
final Multimap<Node, Runnable> deferredActions = HashMultimap.create();
AbstractScopeBuilder(TypedScope scope) {
this.currentScope = scope;
this.currentHoistScope = scope.getClosestHoistScope();
}
/** Returns the current compiler input. */
CompilerInput getCompilerInput() {
return compiler.getInput(inputId);
}
/** Traverse the scope root and build it. */
void build() {
new NodeTraversal(compiler, this, ScopeCreator.ASSERT_NO_SCOPES_CREATED)
.traverseAtScope(currentScope);
}
@Override
public final boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
inputId = t.getInputId();
if (n.isFunction() || n.isScript() || (parent == null && inputId != null)) {
checkNotNull(inputId);
sourceName = NodeUtil.getSourceName(n);
}
if (parent == null || inCurrentScope(t)) {
visitPreorder(t, n, parent);
return true;
}
return false;
}
private boolean inCurrentScope(NodeTraversal t) {
Node traversalScopeRoot = t.getScopeRoot();
// NOTE: we need special handling for SCRIPT nodes, since Compiler.replaceScript causes a
// traversal rooted at a SCRIPT but with the global scope whose root node is the ROOT.
if (traversalScopeRoot.isScript()) {
return currentScope.isGlobal();
}
// Otherwise we're in the current scope as long as the root nodes match up.
return traversalScopeRoot == currentScope.getRootNode();
}
@Override
public final void visit(NodeTraversal t, Node n, Node parent) {
inputId = t.getInputId();
if (parent != null) {
attachLiteralTypes(n);
visitPostorder(t, n, parent);
if (deferredActions.containsKey(n)) { // streams are expensive, only make if needed
deferredActions.removeAll(n).stream().forEach(Runnable::run);
}
} else if (!deferredActions.isEmpty()) {
// Run *all* remaining deferred actions, in case any were missed.
deferredActions.values().stream().forEach(Runnable::run);
}
}
/** Called by shouldTraverse on nodes after ensuring the inputId is set. */
void visitPreorder(NodeTraversal t, Node n, Node parent) {}
/** Called by visit on nodes after updating the inputId. */
void visitPostorder(NodeTraversal t, Node n, Node parent) {}
void attachLiteralTypes(Node n) {
switch (n.getToken()) {
case NULL:
n.setJSType(getNativeType(NULL_TYPE));
break;
case VOID:
n.setJSType(getNativeType(VOID_TYPE));
break;
case STRING:
case TEMPLATELIT_STRING:
n.setJSType(getNativeType(STRING_TYPE));
break;
case NUMBER:
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case TRUE:
case FALSE:
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case REGEXP:
n.setJSType(getNativeType(REGEXP_TYPE));
break;
case OBJECTLIT:
JSDocInfo info = n.getJSDocInfo();
if (info != null && info.hasLendsName()) {
// Defer analyzing object literals with a @lends annotation until we
// reach the root of the statement they're defined in.
//
// This ensures that if there are any @lends annotations on the object
// literals, the type on the @lends annotation resolves correctly.
//
// For more information, see http://blickly.github.io/closure-compiler-issues/#314
deferredActions.put(NodeUtil.getEnclosingStatement(n), () -> defineObjectLiteral(n));
} else {
defineObjectLiteral(n);
}
break;
case CLASS:
// NOTE(sdh): We can't handle function nodes here because they need special behavior to
// deal with hoisting. But since classes aren't hoisted, and may need to be handled in
// such places as default method initializers (i.e. in a FunctionScope) or class extends
// clauses (technically part of the ClassScope, but visited instead by the NormalScope),
// they can be handled consistently in all scopes.
defineClassLiteral(n);
break;
// NOTE(johnlenz): If we ever support Array tuples,
// we will need to handle them here as we do object literals
// above.
case ARRAYLIT:
n.setJSType(getNativeType(ARRAY_TYPE));
break;
default:
break;
}
}
private void defineObjectLiteral(Node objectLit) {
// Handle the @lends annotation.
JSType type = null;
JSDocInfo info = objectLit.getJSDocInfo();
if (info != null && info.hasLendsName()) {
String lendsName = info.getLendsName().getRoot().getString();
TypedVar lendsVar = currentScope.getVar(lendsName);
if (lendsVar == null) {
report(JSError.make(objectLit, UNKNOWN_LENDS, lendsName));
} else {
type = lendsVar.getType();
if (type == null) {
type = unknownType;
}
if (!type.isSubtypeOf(typeRegistry.getNativeType(OBJECT_TYPE))) {
report(JSError.make(
objectLit, LENDS_ON_NON_OBJECT, lendsName, type.toString()));
type = null;
} else {
objectLit.setJSType(type);
}
}
}
info = NodeUtil.getBestJSDocInfo(objectLit);
boolean createEnumType = info != null && info.hasEnumParameterType();
if (createEnumType) {
Node lValue = NodeUtil.getBestLValue(objectLit);
String lValueName = NodeUtil.getBestLValueName(lValue);
type = createEnumTypeFromNodes(objectLit, lValueName, lValue, info);
}
if (type == null) {
type = typeRegistry.createAnonymousObjectType(info);
}
setDeferredType(objectLit, type);
// If this is an enum, the properties were already taken care of above.
processObjectLitProperties(
objectLit, ObjectType.cast(objectLit.getJSType()), !createEnumType);
}
/**
* Process an object literal and all the types on it.
* @param objLit The OBJECTLIT node.
* @param objLitType The type of the OBJECTLIT node. This might be a named
* type, because of the lends annotation.
* @param declareOnOwner If true, declare properties on the objLitType as
* well. If false, the caller should take care of this.
*/
void processObjectLitProperties(
Node objLit, ObjectType objLitType,
boolean declareOnOwner) {
for (Node keyNode = objLit.getFirstChild(); keyNode != null; keyNode = keyNode.getNext()) {
if (keyNode.isComputedProp() || keyNode.isSpread()) {
// Don't try defining computed or spread properties on an object. Note that for spread
// type inference will try to determine the properties and types. We cannot do it here as
// we don't have all the type information of the spread object.
continue;
}
Node value = keyNode.getFirstChild();
String memberName = NodeUtil.getObjectLitKeyName(keyNode);
JSDocInfo info = keyNode.getJSDocInfo();
JSType valueType = getDeclaredType(info, keyNode, value, null);
JSType keyType =
objLitType.isEnumType()
? objLitType.toMaybeEnumType().getElementsType()
: TypeCheck.getObjectLitKeyTypeFromValueType(keyNode, valueType);
// Try to declare this property in the current scope if it
// has an authoritative name.
String qualifiedName = NodeUtil.getBestLValueName(keyNode);
if (qualifiedName != null) {
new SlotDefiner()
.forDeclarationNode(keyNode)
.forVariableName(qualifiedName)
.inScope(getLValueRootScope(keyNode))
.withType(keyType)
.allowLaterTypeInference(keyType == null)
.defineSlot();
} else if (keyType != null) {
setDeferredType(keyNode, keyType);
}
if (keyType != null && objLitType != null && declareOnOwner) {
// Declare this property on its object literal.
objLitType.defineDeclaredProperty(memberName, keyType, keyNode);
}
}
}
/**
* Returns the type specified in a JSDoc annotation near a GETPROP, NAME, member function, or
* object literal key.
*
* <p>Extracts type information from the {@code @type} tag.
*/
private JSType getDeclaredTypeInAnnotation(Node node, JSDocInfo info) {
checkArgument(info.hasType());
ImmutableList<TemplateType> ownerTypeKeys = ImmutableList.of();
Node ownerNode = NodeUtil.getBestLValueOwner(node);
String ownerName = NodeUtil.getBestLValueName(ownerNode);
ObjectType ownerType = null;
if (ownerName != null) {
TypedVar ownerVar = currentScope.getVar(ownerName);
if (ownerVar != null) {
ownerType = getPrototypeOwnerType(ObjectType.cast(ownerVar.getType()));
if (ownerType != null) {
ownerTypeKeys = ownerType.getTemplateTypeMap().getTemplateKeys();
}
}
}
StaticTypedScope templateScope =
!ownerTypeKeys.isEmpty()
? typeRegistry.createScopeWithTemplates(currentScope, ownerTypeKeys)
: currentScope;
return info.getType().evaluate(templateScope, typeRegistry);
}
/**
* Asserts that it's OK to define this node's name.
* The node should have a source name and be of the specified type.
*/
void assertDefinitionNode(Node n, Token type) {
checkState(sourceName != null);
checkState(n.getToken() == type, n);
}
/**
* Defines a catch parameter.
*/
void defineCatch(Node n) {
assertDefinitionNode(n, Token.CATCH);
// Though almost certainly a terrible idea, it is possible to do destructuring in
// the catch declaration.
// e.g. `} catch ({message, errno}) {`
for (Node catchName : NodeUtil.findLhsNodesInNode(n)) {
JSType type = getDeclaredType(catchName.getJSDocInfo(), catchName, null, null);
new SlotDefiner()
.forDeclarationNode(catchName)
.forVariableName(catchName.getString())
.inScope(currentScope)
.withType(type)
.allowLaterTypeInference(type == null)
.defineSlot();
}
}
/** Defines an assignment to a name as if it were an actual declaration. */
void defineAssignAsIfDeclaration(Node assignment) {
JSDocInfo info = assignment.getJSDocInfo();
Node name = assignment.getFirstChild();
checkArgument(name.isName(), name);
Node rvalue = assignment.getSecondChild();
defineName(name, rvalue, currentScope, info);
}
/** Defines a variable declared with `var`, `let`, or `const`. */
void defineVars(Node n) {
checkState(sourceName != null);
checkState(NodeUtil.isNameDeclaration(n));
JSDocInfo info = n.getJSDocInfo();
// `var` declarations are hoisted, but `let` and `const` are not.
TypedScope scope = n.isVar() ? currentHoistScope : currentScope;
if (n.hasMoreThanOneChild() && info != null) {
report(JSError.make(n, MULTIPLE_VAR_DEF));
}
for (Node child : n.children()) {
defineVarChild(info, child, scope);
}
}
/** Defines a variable declared with `var`, `let`, or `const`. */
void defineVarChild(JSDocInfo declarationInfo, Node child, TypedScope scope) {
if (child.isName()) {
if (declarationInfo == null) {
declarationInfo = child.getJSDocInfo();
// TODO(bradfordcsmith): Report an error if both the declaration node and the name itself
// have JSDoc.
}
defineName(child, child.getFirstChild(), scope, declarationInfo);
} else {
checkState(child.isDestructuringLhs(), child);
Node pattern = child.getFirstChild();
Node value = child.getSecondChild();
defineDestructuringPatternInVarDeclaration(
pattern,
scope,
() ->
// Note that value will be null if we are in an enhanced for loop
// for (const {x, y} of data) {
value != null
? new RValueInfo(
getDeclaredRValueType(/* lValue= */ null, value),
value.getQualifiedNameObject())
: new RValueInfo(unknownType, /* qualifiedName= */ null));
}
}
/**
* Returns information about the qualified name and type of the target, if it exists.
*
* <p>Never returns null, but will return an RValueInfo with null `type` and `qualifiedName`
* slots.
*/
private RValueInfo inferTypeForDestructuredTarget(
DestructuredTarget target, Supplier<RValueInfo> patternTypeSupplier) {