-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
TypeInference.java
2462 lines (2209 loc) · 92 KB
/
TypeInference.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 2008 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.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ITERABLE_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.I_TEMPLATE_ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_VALUE_OR_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_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.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionLookup;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
import com.google.javascript.jscomp.ControlFlowGraph.Branch;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.BooleanLiteralSet;
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.ModificationVisitor;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.StaticTypedSlot;
import com.google.javascript.rhino.jstype.TemplateType;
import com.google.javascript.rhino.jstype.TemplateTypeMap;
import com.google.javascript.rhino.jstype.TemplatizedType;
import com.google.javascript.rhino.jstype.UnionType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* Type inference within a script node or a function body, using the data-flow
* analysis framework.
*
*/
class TypeInference
extends DataFlowAnalysis.BranchedForwardDataFlowAnalysis<Node, FlowScope> {
// TODO(johnlenz): We no longer make this check, but we should.
static final DiagnosticType FUNCTION_LITERAL_UNDEFINED_THIS =
DiagnosticType.warning(
"JSC_FUNCTION_LITERAL_UNDEFINED_THIS",
"Function literal argument refers to undefined this argument");
private final AbstractCompiler compiler;
private final JSTypeRegistry registry;
private final ReverseAbstractInterpreter reverseInterpreter;
private final FlowScope functionScope;
private final FlowScope bottomScope;
private final TypedScope containerScope;
private final TypedScopeCreator scopeCreator;
private final AssertionFunctionLookup assertionFunctionLookup;
// Scopes that have had their unbound untyped vars inferred as undefined.
private final Set<TypedScope> inferredUnboundVars = new HashSet<>();
// For convenience
private final ObjectType unknownType;
TypeInference(
AbstractCompiler compiler,
ControlFlowGraph<Node> cfg,
ReverseAbstractInterpreter reverseInterpreter,
TypedScope syntacticScope,
TypedScopeCreator scopeCreator,
AssertionFunctionLookup assertionFunctionLookup) {
super(cfg, new LinkedFlowScope.FlowScopeJoinOp());
this.compiler = compiler;
this.registry = compiler.getTypeRegistry();
this.reverseInterpreter = reverseInterpreter;
this.unknownType = registry.getNativeObjectType(UNKNOWN_TYPE);
this.containerScope = syntacticScope;
this.scopeCreator = scopeCreator;
this.assertionFunctionLookup = assertionFunctionLookup;
FlowScope entryScope =
inferDeclarativelyUnboundVarsWithoutTypes(
LinkedFlowScope.createEntryLattice(syntacticScope));
this.functionScope = inferParameters(entryScope);
this.bottomScope =
LinkedFlowScope.createEntryLattice(
TypedScope.createLatticeBottom(syntacticScope.getRootNode()));
}
@CheckReturnValue
private FlowScope inferDeclarativelyUnboundVarsWithoutTypes(FlowScope flow) {
TypedScope scope = (TypedScope) flow.getDeclarationScope();
if (!inferredUnboundVars.add(scope)) {
return flow;
}
// For each local variable declared with the VAR keyword, the entry
// type is VOID.
for (TypedVar var : scope.getDeclarativelyUnboundVarsWithoutTypes()) {
if (isUnflowable(var)) {
continue;
}
flow = flow.inferSlotType(var.getName(), getNativeType(VOID_TYPE));
}
return flow;
}
/** Infers all of a function's parameters if their types aren't declared. */
@SuppressWarnings("ReferenceEquality") // unknownType is a singleton
private FlowScope inferParameters(FlowScope entryFlowScope) {
Node functionNode = containerScope.getRootNode();
if (!functionNode.isFunction()) {
return entryFlowScope; // we're in the global scope
}
Node astParameters = functionNode.getSecondChild();
Node iifeArgumentNode = null;
if (NodeUtil.isInvocationTarget(functionNode)) {
iifeArgumentNode = functionNode.getNext();
}
FunctionType functionType = JSType.toMaybeFunctionType(functionNode.getJSType());
Node parameterTypeNode = functionType.getParametersNode().getFirstChild();
// This really iterates over three different things at once:
// - the actual AST parameter nodes (which may be REST, DEFAULT_VALUE, etc.)
// - the argument nodes in an IIFE
// - the parameter type nodes from the FunctionType on the FUNCTION node
// Always visit every AST parameter once, regardless of how many IIFE arguments or
// FunctionType param nodes there are.
for (Node astParameter : astParameters.children()) {
if (iifeArgumentNode != null && iifeArgumentNode.isSpread()) {
// block inference on all parameters that might possibly be set by a spread, e.g. `z` in
// (function f(x, y, z = 1))(...[1, 2], 'foo')
iifeArgumentNode = null;
}
// Running variable for the type of the param within the body of the function. We use the
// existing type on the param node as the default, and then transform it according to the
// declaration syntax.
JSType inferredType = getJSType(astParameter);
if (iifeArgumentNode != null) {
if (iifeArgumentNode.getJSType() != null) {
inferredType = iifeArgumentNode.getJSType();
}
} else if (parameterTypeNode != null) {
if (parameterTypeNode.getJSType() != null) {
inferredType = parameterTypeNode.getJSType();
}
}
Node defaultValue = null;
if (astParameter.isDefaultValue()) {
defaultValue = astParameter.getSecondChild();
// must call `traverse` to correctly type the default value
entryFlowScope = traverse(defaultValue, entryFlowScope);
astParameter = astParameter.getFirstChild();
} else if (astParameter.isRest()) {
// e.g. `function f(p1, ...restParamName) {}`
// set astParameter = restParamName
astParameter = astParameter.getOnlyChild();
// convert 'number' into 'Array<number>' for rest parameters
inferredType =
registry.createTemplatizedType(registry.getNativeObjectType(ARRAY_TYPE), inferredType);
}
if (defaultValue != null) {
// The param could possibly be the default type, and `undefined` args won't propagate in.
inferredType =
registry.createUnionType(
inferredType.restrictByNotUndefined(), getJSType(defaultValue));
}
if (astParameter.isDestructuringPattern()) {
// even if the inferredType is null, we still need to type all the nodes inside the
// destructuring pattern. (e.g. in computed properties or default value expressions)
entryFlowScope = updateDestructuringParameter(astParameter, inferredType, entryFlowScope);
} else {
// for simple named parameters, we only need to update the scope/AST if we have a new
// inferred type.
entryFlowScope =
updateNamedParameter(astParameter, defaultValue != null, inferredType, entryFlowScope);
}
parameterTypeNode = parameterTypeNode != null ? parameterTypeNode.getNext() : null;
iifeArgumentNode = iifeArgumentNode != null ? iifeArgumentNode.getNext() : null;
}
return entryFlowScope;
}
/**
* Sets the types of a un-named/destructuring function parameter to an inferred type.
*
* <p>This method is responsible for typing:
*
* <ul>
* <li>The scope slot
* <li>The pattern nodes
* </ul>
*/
@CheckReturnValue
@SuppressWarnings("ReferenceEquality") // unknownType is a singleton
private FlowScope updateDestructuringParameter(
Node pattern, JSType inferredType, FlowScope entryFlowScope) {
// look through all expressions and lvalues in the pattern.
// given an lvalue, change its type if either a) it's inferred (not declared in
// TypedScopeCreator) or b) it has a default value
entryFlowScope =
traverseDestructuringPatternHelper(
pattern,
entryFlowScope,
inferredType,
(FlowScope scope, Node lvalue, JSType type) -> {
TypedVar var = containerScope.getVar(lvalue.getString());
checkNotNull(var);
// This condition will trigger on cases like
// (function f({x}) {})({x: 3})
// where `x` is of unknown type during the typed scope creation phase, but
// here we can infer that it is of type `number`
if (var.isTypeInferred()) {
var.setType(type);
lvalue.setJSType(type);
}
if (lvalue.getParent().isDefaultValue()) {
// Given
// /** @param {{age: (number|undefined)}} data */
// function f({age = 99}) {}
// infer that `age` is now a `number` and not `number|undefined`
// treat this similarly to if there was an assignment inside the function body
// TODO(b/117162687): allow people to narrow the declared type to
// exclude 'undefined' inside the function body.
scope = updateScopeForAssignment(scope, lvalue, type, AssignmentType.ASSIGN);
}
return scope;
});
return entryFlowScope;
}
/**
* Sets the types of a named/non-destructuring function parameter to an inferred type.
*
* <p>This method is responsible for typing:
*
* <ul>
* <li>The scope slot
* <li>The param node
* </ul>
*/
@CheckReturnValue
@SuppressWarnings("ReferenceEquality") // unknownType is a singleton
private FlowScope updateNamedParameter(
Node paramName, boolean hasDefaultValue, JSType inferredType, FlowScope entryFlowScope) {
TypedVar var = containerScope.getVar(paramName.getString());
checkNotNull(var);
paramName.setJSType(inferredType);
if (var.isTypeInferred()) {
var.setType(inferredType);
} else if (hasDefaultValue) {
// If this is a declared type with a default value, update the LinkedFlowScope slots but not
// the actual TypedVar. This is similar to what would happen if the default value was moved
// into an assignment in the fn body
entryFlowScope = redeclareSimpleVar(entryFlowScope, paramName, inferredType);
}
return entryFlowScope;
}
/** Abstracts logic for declaring an lvalue in a particular scope */
interface TypeDeclaringCallback {
/**
* Updates the given scope upon seeing an assignment or declaration
*
* @param scope the scope we are in
* @param lvalue the value being updated, a NAME, GETPROP, GETELEM, or CAST
* @param type the type we've inferred for the lvalue
* @return the updated flow scope
*/
FlowScope declareTypeInScope(FlowScope scope, Node lvalue, @Nullable JSType type);
}
@Override
FlowScope createInitialEstimateLattice() {
return bottomScope;
}
@Override
FlowScope createEntryLattice() {
return functionScope;
}
@Override
@CheckReturnValue
FlowScope flowThrough(Node n, FlowScope input) {
// If we have not walked a path from <entry> to <n>, then we don't
// want to infer anything about this scope.
if (input == bottomScope) {
return input;
}
Node root = NodeUtil.getEnclosingScopeRoot(n);
FlowScope output = input.withSyntacticScope(scopeCreator.createScope(root));
output = inferDeclarativelyUnboundVarsWithoutTypes(output);
output = traverse(n, output);
return output;
}
@Override
@SuppressWarnings({"fallthrough", "incomplete-switch"})
List<FlowScope> branchedFlowThrough(Node source, FlowScope input) {
// NOTE(nicksantos): Right now, we just treat ON_EX edges like UNCOND
// edges. If we wanted to be perfect, we'd actually JOIN all the out
// lattices of this flow with the in lattice, and then make that the out
// lattice for the ON_EX edge. But it's probably too expensive to be
// worthwhile.
FlowScope output = flowThrough(source, input);
Node condition = null;
FlowScope conditionFlowScope = null;
BooleanOutcomePair conditionOutcomes = null;
List<DiGraphEdge<Node, Branch>> branchEdges = getCfg().getOutEdges(source);
List<FlowScope> result = new ArrayList<>(branchEdges.size());
for (DiGraphEdge<Node, Branch> branchEdge : branchEdges) {
Branch branch = branchEdge.getValue();
FlowScope newScope = output;
switch (branch) {
case ON_TRUE:
if (source.isForIn() || source.isForOf()) {
Node item = source.getFirstChild();
Node obj = item.getNext();
FlowScope informed = traverse(obj, output);
final AssignmentType assignmentType;
if (NodeUtil.isNameDeclaration(item)) {
item = item.getFirstChild();
assignmentType = AssignmentType.DECLARATION;
} else {
assignmentType = AssignmentType.ASSIGN;
}
if (item.isDestructuringLhs()) {
item = item.getFirstChild();
}
if (source.isForIn()) {
// item is assigned a property name, so its type should be string
JSType iterKeyType = getNativeType(STRING_TYPE);
JSType objType = getJSType(obj).autobox();
JSType objIndexType =
objType
.getTemplateTypeMap()
.getResolvedTemplateType(registry.getObjectIndexKey());
if (objIndexType != null && !objIndexType.isUnknownType()) {
JSType narrowedKeyType = iterKeyType.getGreatestSubtype(objIndexType);
if (!narrowedKeyType.isEmptyType()) {
iterKeyType = narrowedKeyType;
}
}
if (item.isName()) {
informed = redeclareSimpleVar(informed, item, iterKeyType);
} else if (item.isDestructuringPattern()) {
informed =
traverseDestructuringPattern(item, informed, iterKeyType, assignmentType);
}
} else {
// for/of. The type of `item` is the type parameter of the Iterable type.
JSType objType = getJSType(obj).autobox();
// NOTE: this returns the UNKNOWN_TYPE if objType does not implement Iterable
JSType newType = objType.getInstantiatedTypeArgument(getNativeType(ITERABLE_TYPE));
// Note that `item` can be an arbitrary LHS expression we need to check.
if (item.isDestructuringPattern()) {
// for (const {x, y} of data) {
informed = traverseDestructuringPattern(item, informed, newType, assignmentType);
} else {
informed = traverse(item, informed);
informed = updateScopeForAssignment(informed, item, newType, assignmentType);
}
}
newScope = informed;
break;
}
// FALL THROUGH
case ON_FALSE:
if (condition == null) {
condition = NodeUtil.getConditionExpression(source);
if (condition == null && source.isCase()) {
condition = source;
// conditionFlowScope is cached from previous iterations
// of the loop.
if (conditionFlowScope == null) {
conditionFlowScope = traverse(condition.getFirstChild(), output);
}
}
}
if (condition != null) {
if (condition.isAnd() || condition.isOr()) {
// When handling the short-circuiting binary operators,
// the outcome scope on true can be different than the outcome
// scope on false.
//
// TODO(nicksantos): The "right" way to do this is to
// carry the known outcome all the way through the
// recursive traversal, so that we can construct a
// different flow scope based on the outcome. However,
// this would require a bunch of code and a bunch of
// extra computation for an edge case. This seems to be
// a "good enough" approximation.
// conditionOutcomes is cached from previous iterations
// of the loop.
if (conditionOutcomes == null) {
conditionOutcomes =
condition.isAnd()
? traverseAnd(condition, output)
: traverseOr(condition, output);
}
newScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
condition,
conditionOutcomes.getOutcomeFlowScope(
condition.getToken(), branch == Branch.ON_TRUE),
branch == Branch.ON_TRUE);
} else {
// conditionFlowScope is cached from previous iterations
// of the loop.
if (conditionFlowScope == null) {
conditionFlowScope = traverse(condition, output);
}
newScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
condition, conditionFlowScope, branch == Branch.ON_TRUE);
}
}
break;
default:
break;
}
result.add(newScope);
}
return result;
}
private FlowScope traverse(Node n, FlowScope scope) {
switch (n.getToken()) {
case ASSIGN:
scope = traverseAssign(n, scope);
break;
case NAME:
scope = traverseName(n, scope);
break;
case GETPROP:
scope = traverseGetProp(n, scope);
break;
case CLASS:
scope = traverseClass(n, scope);
break;
case AND:
scope = traverseAnd(n, scope).getJoinedFlowScope();
break;
case OR:
scope = traverseOr(n, scope).getJoinedFlowScope();
break;
case HOOK:
scope = traverseHook(n, scope);
break;
case OBJECTLIT:
scope = traverseObjectLiteral(n, scope);
break;
case CALL:
scope = traverseFunctionInvocation(n, scope);
scope = tightenTypesAfterAssertions(scope, n);
break;
case NEW:
scope = traverseNew(n, scope);
break;
case NEW_TARGET:
traverseNewTarget(n);
break;
case ASSIGN_ADD:
case ADD:
scope = traverseAdd(n, scope);
break;
case POS:
case NEG:
scope = traverse(n.getFirstChild(), scope); // Find types.
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case ARRAYLIT:
scope = traverseArrayLiteral(n, scope);
break;
case THIS:
n.setJSType(scope.getTypeOfThis());
break;
case ASSIGN_LSH:
case ASSIGN_RSH:
case ASSIGN_URSH:
case ASSIGN_DIV:
case ASSIGN_MOD:
case ASSIGN_BITAND:
case ASSIGN_BITXOR:
case ASSIGN_BITOR:
case ASSIGN_MUL:
case ASSIGN_SUB:
case ASSIGN_EXPONENT:
scope = traverseAssignOp(n, scope, getNativeType(NUMBER_TYPE));
break;
case LSH:
case RSH:
case URSH:
case DIV:
case MOD:
case BITAND:
case BITXOR:
case BITOR:
case MUL:
case SUB:
case DEC:
case INC:
case BITNOT:
case EXPONENT:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case COMMA:
scope = traverseChildren(n, scope);
n.setJSType(getJSType(n.getLastChild()));
break;
case TEMPLATELIT:
case TYPEOF:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(STRING_TYPE));
break;
case TEMPLATELIT_SUB:
// TEMPLATELIT_SUBs are untyped but we do need to traverse their children.
scope = traverseChildren(n, scope);
break;
case TAGGED_TEMPLATELIT:
scope = traverseFunctionInvocation(n, scope);
break;
case DELPROP:
case LT:
case LE:
case GT:
case GE:
case NOT:
case EQ:
case NE:
case SHEQ:
case SHNE:
case INSTANCEOF:
case IN:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case GETELEM:
scope = traverseGetElem(n, scope);
break;
case EXPR_RESULT:
scope = traverseChildren(n, scope);
if (n.getFirstChild().isGetProp()) {
Node getprop = n.getFirstChild();
ObjectType ownerType = ObjectType.cast(
getJSType(getprop.getFirstChild()).restrictByNotNullOrUndefined());
if (ownerType != null) {
ensurePropertyDeclaredHelper(getprop, ownerType, scope);
}
}
break;
case SWITCH:
scope = traverse(n.getFirstChild(), scope);
break;
case RETURN:
scope = traverseReturn(n, scope);
break;
case YIELD:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(UNKNOWN_TYPE));
break;
case VAR:
case LET:
case CONST:
scope = traverseDeclaration(n, scope);
break;
case THROW:
scope = traverseChildren(n, scope);
break;
case CATCH:
scope = traverseCatch(n, scope);
break;
case CAST:
scope = traverseChildren(n, scope);
JSDocInfo info = n.getJSDocInfo();
// TODO(b/123955687): also check that info.hasType() is true
checkNotNull(info, "CAST node should always have JSDocInfo");
if (info.hasType()) {
// NOTE(lharker) - I tried moving CAST type evaluation into the typed scope creation
// phase.
// Since it caused a few new, seemingly spurious, 'Bad type annotation' and
// 'unknown property type' warnings, and having it in TypeInference seems to work, we just
// do the lookup + resolution here.
n.setJSType(
info.getType()
.evaluate(scope.getDeclarationScope(), registry)
.resolve(registry.getErrorReporter()));
} else {
n.setJSType(unknownType);
}
break;
case SUPER:
traverseSuper(n);
break;
case SPREAD:
// The spread itself has no type, but the expression it contains does and may affect
// type inference.
scope = traverseChildren(n, scope);
break;
case AWAIT:
scope = traverseAwait(n, scope);
break;
case VOID:
n.setJSType(getNativeType(VOID_TYPE));
scope = traverseChildren(n, scope);
break;
case ROOT:
case SCRIPT:
case FUNCTION:
case PARAM_LIST:
case BLOCK:
case EMPTY:
case IF:
case WHILE:
case DO:
case FOR:
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
case BREAK:
case CONTINUE:
case TRY:
case CASE:
case DEFAULT_CASE:
case WITH:
case DEBUGGER:
// These don't need to be typed here, since they only affect control flow.
break;
case TRUE:
case FALSE:
case STRING:
case NUMBER:
case NULL:
case REGEXP:
case TEMPLATELIT_STRING:
// Primitives are typed in TypedScopeCreator.AbstractScopeBuilder#attachLiteralTypes
break;
default:
throw new IllegalStateException(
"Type inference doesn't know to handle token " + n.getToken());
}
return scope;
}
private void traverseSuper(Node superNode) {
// Find the closest non-arrow function (TODO(sdh): this could be an AbstractScope method).
TypedScope scope = containerScope;
while (scope != null && !NodeUtil.isVanillaFunction(scope.getRootNode())) {
scope = scope.getParent();
}
if (scope == null) {
superNode.setJSType(unknownType);
return;
}
Node root = scope.getRootNode();
JSType jsType = root.getJSType();
FunctionType functionType = jsType != null ? jsType.toMaybeFunctionType() : null;
ObjectType superNodeType = unknownType;
Node context = superNode.getParent();
// NOTE: we currently transpile subclass constructors to use "super.apply", which is not
// actually valid ES6. For now, provide a special case to support this, but it should be
// removed once class transpilation is after type checking.
if (context.isCall()) {
// Call the superclass constructor.
if (functionType != null && functionType.isConstructor()) {
FunctionType superCtor = functionType.getSuperClassConstructor();
if (superCtor != null) {
superNodeType = superCtor;
}
}
} else if (context.isGetProp() || context.isGetElem()) {
// TODO(sdh): once getTypeOfThis supports statics, we can get rid of this branch, as well as
// the vanilla function search at the top and just return functionScope.getVar("super").
if (root.getParent().isStaticMember()) {
// Since the root is a static member, we're guaranteed that the parent scope is a class.
Node classNode = scope.getParent().getRootNode();
checkState(classNode.isClass());
FunctionType thisCtor = JSType.toMaybeFunctionType(classNode.getJSType());
if (thisCtor != null) {
FunctionType superCtor = thisCtor.getSuperClassConstructor();
if (superCtor != null) {
superNodeType = superCtor;
}
}
} else if (functionType != null) {
// Refer to a superclass instance property.
ObjectType thisInstance = ObjectType.cast(functionType.getTypeOfThis());
if (thisInstance != null) {
FunctionType superCtor = thisInstance.getSuperClassConstructor();
if (superCtor != null) {
ObjectType superInstance = superCtor.getInstanceType();
if (superInstance != null) {
superNodeType = superInstance;
}
}
}
}
}
superNode.setJSType(superNodeType);
}
private void traverseNewTarget(Node newTargetNode) {
// new.target is (undefined|!Function) within a vanilla function and !Function within an ES6
// constructor.
// Find the closest non-arrow function (TODO(sdh): this could be an AbstractScope method).
TypedScope scope = containerScope;
while (scope != null && !NodeUtil.isVanillaFunction(scope.getRootNode())) {
scope = scope.getParent();
}
if (scope == null) {
// NOTE: we already have a parse error for new.target outside a function. The only other case
// where this might happen is a top-level arrow function, which is a parse error in the VM,
// but allowed by our parser.
newTargetNode.setJSType(unknownType);
return;
}
Node root = scope.getRootNode();
Node parent = root.getParent();
if (parent.getGrandparent().isClass()) {
// In an ES6 constuctor, new.target may not be undefined. In any other method, it must be
// undefined, since methods are not constructable.
JSTypeNative type =
NodeUtil.isEs6ConstructorMemberFunctionDef(parent)
? JSTypeNative.U2U_CONSTRUCTOR_TYPE
: VOID_TYPE;
newTargetNode.setJSType(registry.getNativeType(type));
} else {
// Other functions also include undefined, in case they are not called with 'new'.
newTargetNode.setJSType(
registry.createUnionType(
registry.getNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE),
registry.getNativeType(VOID_TYPE)));
}
}
/** Traverse a return value. */
@CheckReturnValue
private FlowScope traverseReturn(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node retValue = n.getFirstChild();
if (retValue != null) {
JSType type = functionScope.getRootNode().getJSType();
if (type != null) {
FunctionType fnType = type.toMaybeFunctionType();
if (fnType != null) {
inferPropertyTypesToMatchConstraint(
retValue.getJSType(), fnType.getReturnType());
}
}
}
return scope;
}
/**
* Any value can be thrown, so it's really impossible to determine the type of a CATCH param.
* Treat it as the UNKNOWN type.
*/
@CheckReturnValue
private FlowScope traverseCatch(Node catchNode, FlowScope scope) {
Node catchTarget = catchNode.getFirstChild();
if (catchTarget.isName()) {
// TODO(lharker): is this case even necessary? seems like TypedScopeCreator handles it
Node name = catchNode.getFirstChild();
JSType type;
// If the catch expression name was declared in the catch use that type,
// otherwise use "unknown".
JSDocInfo info = name.getJSDocInfo();
if (info != null && info.hasType()) {
type = info.getType().evaluate(scope.getDeclarationScope(), registry);
} else {
type = getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
name.setJSType(type);
return redeclareSimpleVar(scope, name, type);
} else if (catchTarget.isDestructuringPattern()) {
Node pattern = catchNode.getFirstChild();
return traverseDestructuringPattern(pattern, scope, unknownType, AssignmentType.DECLARATION);
} else {
checkState(catchTarget.isEmpty(), catchTarget);
// ES2019 allows `try {} catch {}` with no catch expression
return scope;
}
}
@CheckReturnValue
private FlowScope traverseAssign(Node n, FlowScope scope) {
Node target = n.getFirstChild();
Node value = n.getLastChild();
if (target.isDestructuringPattern()) {
scope = traverse(value, scope);
JSType valueType = getJSType(value);
n.setJSType(valueType);
return traverseDestructuringPattern(target, scope, valueType, AssignmentType.ASSIGN);
} else {
scope = traverseChildren(n, scope);
JSType valueType = getJSType(value);
n.setJSType(valueType);
return updateScopeForAssignment(scope, target, valueType, AssignmentType.ASSIGN);
}
}
@CheckReturnValue
private FlowScope traverseAssignOp(Node n, FlowScope scope, JSType resultType) {
Node left = n.getFirstChild();
scope = traverseChildren(n, scope);
n.setJSType(resultType);
// The lhs is both an input and an output, so don't update the input type here.
return updateScopeForAssignment(
scope, left, resultType, /* updateNode= */ null, AssignmentType.ASSIGN);
}
private static boolean isInExternFile(Node n) {
return NodeUtil.getSourceFile(n).isExtern();
}
private static boolean isPossibleMixinApplication(Node lvalue, Node rvalue) {
if (isInExternFile(lvalue)) {
return true;
}
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(lvalue);
return jsdoc != null
&& jsdoc.isConstructor()
&& jsdoc.getImplementedInterfaceCount() > 0
&& lvalue.isQualifiedName()
&& rvalue.isCall();
}
/**
* @param constructor A constructor function defined by a call, which may be a mixin application.
* The constructor implements at least one interface. If the constructor is missing some
* properties of the inherited interfaces, this method declares these properties.
*/
private static void addMissingInterfaceProperties(JSType constructor) {
if (constructor != null && constructor.isConstructor()) {
FunctionType f = constructor.toMaybeFunctionType();
ObjectType proto = f.getPrototype();
for (ObjectType interf : f.getImplementedInterfaces()) {
for (String pname : interf.getPropertyNames()) {
if (!proto.hasProperty(pname)) {
proto.defineDeclaredProperty(pname, interf.getPropertyType(pname), null);
}
}
}
}
}
// Either a combined declaration/initialization or a regular assignment
private enum AssignmentType {
DECLARATION, // var x = 3;
ASSIGN // `a.b.c = d;` or `x = 4;`
}
@CheckReturnValue
private FlowScope updateScopeForAssignment(
FlowScope scope, Node target, JSType resultType, AssignmentType type) {
return updateScopeForAssignment(scope, target, resultType, target, type);
}
/** Updates the scope according to the result of an assignment. */
@CheckReturnValue
private FlowScope updateScopeForAssignment(
FlowScope scope, Node target, JSType resultType, Node updateNode, AssignmentType type) {
checkNotNull(resultType);
checkState(updateNode == null || updateNode == target);
JSType targetType = target.getJSType(); // may be null
Node right = NodeUtil.getRValueOfLValue(target);
if (isPossibleMixinApplication(target, right)) {
addMissingInterfaceProperties(targetType);
}
switch (target.getToken()) {
case NAME:
String varName = target.getString();
TypedVar var = getDeclaredVar(scope, varName);
JSType varType = var == null ? null : var.getType();
boolean isVarDeclaration =
type == AssignmentType.DECLARATION
&& varType != null
&& !var.isTypeInferred()
&& var.getNameNode() != null;
// Whether this variable is declared not because it has JSDoc with a declaration, but
// because it is const and the right-hand-side is easily inferrable.
// e.g. these are 'typeless const declarations':
// const x = 0;
// /** @const */