-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
codeFlowEngine.ts
1597 lines (1399 loc) · 74.7 KB
/
codeFlowEngine.ts
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
/*
* codeFlowEngine.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* Code that traverses the code flow graph to determine the (narrowed)
* type of a variable or expression or the reachability of a statement.
*
* This is largely based on the code flow engine in the
* TypeScript compiler.
*/
import { assert, fail } from '../common/debug';
import { CallNode, ExpressionNode, ParseNode, ParseNodeType } from '../parser/parseNodes';
import { getImportInfo } from './analyzerNodeInfo';
import {
CodeFlowReferenceExpressionNode,
createKeyForReference,
createKeysForReferenceSubexpressions,
FlowAssignment,
FlowBranchLabel,
FlowCall,
FlowCondition,
FlowExhaustedMatch,
FlowFlags,
FlowLabel,
FlowNarrowForPattern,
FlowNode,
FlowPostContextManagerLabel,
FlowPostFinally,
FlowPreFinallyGate,
FlowVariableAnnotation,
FlowWildcardImport,
} from './codeFlowTypes';
import { DeclarationType } from './declaration';
import { isMatchingExpression, isPartialMatchingExpression } from './parseTreeUtils';
import { Symbol } from './symbol';
import {
CachedType,
IncompleteSubtypeInfo,
IncompleteType,
isIncompleteType,
SpeculativeTypeTracker,
TypeCache,
} from './typeCache';
import { EvaluatorFlags, TypeEvaluator, TypeResult } from './typeEvaluatorTypes';
import { getTypeNarrowingCallback } from './typeGuards';
import {
ClassType,
combineTypes,
FunctionType,
isClass,
isClassInstance,
isFunction,
isInstantiableClass,
isModule,
isNever,
isOverloadedFunction,
isTypeSame,
isTypeVar,
ModuleType,
removeUnknownFromUnion,
Type,
TypeVarType,
UnboundType,
UnknownType,
} from './types';
import {
ClassMemberLookupFlags,
convertToInstance,
doForEachSubtype,
isTypeAliasPlaceholder,
lookUpClassMember,
mapSubtypes,
} from './typeUtils';
export interface FlowNodeTypeResult {
type: Type | undefined;
isIncomplete: boolean;
generationCount?: number | undefined;
incompleteType?: Type | undefined;
incompleteSubtypes?: IncompleteSubtypeInfo[] | undefined;
recursiveVisitCount?: number;
}
export interface CodeFlowAnalyzer {
getTypeFromCodeFlow: (
flowNode: FlowNode,
reference: CodeFlowReferenceExpressionNode | undefined,
targetSymbolId: number | undefined,
initialType: Type | undefined,
isInitialTypeIncomplete: boolean
) => FlowNodeTypeResult;
}
export interface CodeFlowEngine {
createCodeFlowAnalyzer: () => CodeFlowAnalyzer;
isFlowNodeReachable: (flowNode: FlowNode, sourceFlowNode?: FlowNode) => boolean;
narrowConstrainedTypeVar: (flowNode: FlowNode, typeVar: TypeVarType) => Type | undefined;
}
// Maximum number of times a loop flow node will be evaluated
// with incomplete results before we give up.
const maxFlowNodeLoopVisitCount = 64;
// Maximum number of times getTypeFromFlowNode can be called
// recursively within loop or branch processing before we give up.
const maxCodeFlowInvocationsPerLoop = 16 * 1024;
export function getCodeFlowEngine(
evaluator: TypeEvaluator,
speculativeTypeTracker: SpeculativeTypeTracker
): CodeFlowEngine {
const isReachableRecursionMap = new Map<number, true>();
const callIsNoReturnCache = new Map<number, boolean>();
const isExceptionContextManagerCache = new Map<number, boolean>();
let codeFlowInvocations = 0;
let flowIncompleteGeneration = 1;
// Creates a new code flow analyzer that can be used to narrow the types
// of the expressions within an execution context. Each code flow analyzer
// instance maintains a cache of types it has already determined.
function createCodeFlowAnalyzer(): CodeFlowAnalyzer {
const flowNodeTypeCacheSet = new Map<string, TypeCache>();
function getTypeFromCodeFlow(
flowNode: FlowNode,
reference: CodeFlowReferenceExpressionNode | undefined,
targetSymbolId: number | undefined,
initialType: Type | undefined,
isInitialTypeIncomplete: boolean
): FlowNodeTypeResult {
const referenceKey = reference !== undefined ? createKeyForReference(reference) : undefined;
let subexpressionReferenceKeys: string[] | undefined;
const referenceKeyWithSymbolId =
referenceKey !== undefined && targetSymbolId !== undefined
? referenceKey + `.${targetSymbolId.toString()}`
: '.';
let flowNodeTypeCache = flowNodeTypeCacheSet.get(referenceKeyWithSymbolId);
if (!flowNodeTypeCache) {
flowNodeTypeCache = new Map<number, CachedType | undefined>();
flowNodeTypeCacheSet.set(referenceKeyWithSymbolId, flowNodeTypeCache);
}
// Caches the type of the flow node in our local cache, keyed by the flow node ID.
function setCacheEntry(
flowNode: FlowNode,
type: Type | undefined,
isIncomplete: boolean
): FlowNodeTypeResult {
if (!isIncomplete) {
flowIncompleteGeneration++;
} else {
const prevEntry = flowNodeTypeCache!.get(flowNode.id);
if (prevEntry === undefined) {
flowIncompleteGeneration++;
} else if (type && (prevEntry as IncompleteType).isIncompleteType) {
const prevIncompleteType = prevEntry as IncompleteType;
if (prevIncompleteType.type && !isTypeSame(prevIncompleteType.type, type)) {
flowIncompleteGeneration++;
}
}
}
// For speculative or incomplete types, we'll create a separate
// object. For non-speculative and complete types, we'll store
// the type directly.
const entry: CachedType | undefined = isIncomplete
? {
isIncompleteType: true,
type,
incompleteSubtypes: [],
generationCount: flowIncompleteGeneration,
}
: type;
flowNodeTypeCache!.set(flowNode.id, entry);
speculativeTypeTracker.trackEntry(flowNodeTypeCache!, flowNode.id);
return {
type,
isIncomplete,
generationCount: flowIncompleteGeneration,
incompleteSubtypes: isIncomplete ? [] : undefined,
};
}
function setIncompleteSubtype(
flowNode: FlowNode,
index: number,
type: Type | undefined,
isIncomplete: boolean,
isPending: boolean
) {
const cachedEntry = flowNodeTypeCache!.get(flowNode.id);
if (cachedEntry === undefined || !isIncompleteType(cachedEntry)) {
fail('setIncompleteSubtype can be called only on a valid incomplete cache entry');
}
const incompleteEntries = cachedEntry.incompleteSubtypes;
if (index < incompleteEntries.length) {
const oldEntry = incompleteEntries[index];
if (
oldEntry.isIncomplete !== isIncomplete ||
oldEntry.type === undefined ||
type === undefined ||
!isTypeSame(oldEntry.type, type)
) {
incompleteEntries[index] = { type, isIncomplete, isPending };
flowIncompleteGeneration++;
} else if (oldEntry.isPending !== isPending) {
incompleteEntries[index] = { type, isIncomplete, isPending };
}
} else {
assert(incompleteEntries.length === index);
incompleteEntries.push({ type, isIncomplete, isPending });
flowIncompleteGeneration++;
}
return getCacheEntry(flowNode);
}
function incrementFlowNodeVisitCount(flowNode: FlowNode) {
const cachedEntry = flowNodeTypeCache!.get(flowNode.id);
if (cachedEntry === undefined || !isIncompleteType(cachedEntry)) {
fail('incrementFlowNodeVisitCount can be called only on a valid incomplete cache entry');
}
cachedEntry.recursiveVisitCount = (cachedEntry.recursiveVisitCount ?? 0) + 1;
return cachedEntry.recursiveVisitCount;
}
function incrementFlowNodeConvergenceCount(flowNode: FlowNode, reset = false) {
const cachedEntry = flowNodeTypeCache!.get(flowNode.id);
if (cachedEntry === undefined || !isIncompleteType(cachedEntry)) {
return 0;
}
if (reset) {
cachedEntry.recursiveConvergenceCount = 0;
} else {
cachedEntry.recursiveConvergenceCount = (cachedEntry.recursiveConvergenceCount ?? 0) + 1;
}
return cachedEntry.recursiveConvergenceCount;
}
function getCacheEntry(flowNode: FlowNode): FlowNodeTypeResult | undefined {
if (!flowNodeTypeCache!.has(flowNode.id)) {
return undefined;
}
const cachedEntry = flowNodeTypeCache!.get(flowNode.id);
if (cachedEntry === undefined) {
return {
type: cachedEntry,
isIncomplete: false,
};
}
if (!isIncompleteType(cachedEntry)) {
return {
type: cachedEntry,
isIncomplete: false,
};
}
let type = cachedEntry.type;
if (cachedEntry.incompleteSubtypes.length > 0) {
// Recompute the effective type based on all of the incomplete
// types we've accumulated so far.
const typesToCombine: Type[] = [];
cachedEntry.incompleteSubtypes.forEach((t) => {
if (t.type) {
typesToCombine.push(t.type);
}
});
type = typesToCombine.length > 0 ? combineTypes(typesToCombine) : undefined;
}
return {
type,
isIncomplete: true,
incompleteSubtypes: cachedEntry.incompleteSubtypes,
generationCount: cachedEntry.generationCount,
};
}
function deleteCacheEntry(flowNode: FlowNode) {
flowNodeTypeCache!.delete(flowNode.id);
}
function evaluateAssignmentFlowNode(flowNode: FlowAssignment): TypeResult | undefined {
// For function and class nodes, the reference node is the name
// node, but we need to use the parent node (the FunctionNode or ClassNode)
// to access the decorated type in the type cache.
let nodeForCacheLookup: ParseNode = flowNode.node;
const parentNode = flowNode.node.parent;
if (parentNode) {
if (parentNode.nodeType === ParseNodeType.Function || parentNode.nodeType === ParseNodeType.Class) {
nodeForCacheLookup = parentNode;
}
}
return evaluator.evaluateTypeForSubnode(nodeForCacheLookup, () => {
evaluator.evaluateTypesForStatement(flowNode.node);
});
}
// If this flow has no knowledge of the target expression, it returns undefined.
// If the start flow node for this scope is reachable, the typeAtStart value is
// returned.
function getTypeFromFlowNode(
flowNode: FlowNode,
reference: CodeFlowReferenceExpressionNode | undefined,
targetSymbolId: number | undefined,
initialType: Type | undefined,
isInitialTypeIncomplete: boolean
): FlowNodeTypeResult {
let curFlowNode = flowNode;
// Record how many times this function has been called.
const codeFlowInvocationsAtStart = codeFlowInvocations;
codeFlowInvocations++;
// This is a frequently-called routine, so it's a good place to call
// the cancellation check. If the operation is canceled, an exception
// will be thrown at this point.
evaluator.checkForCancellation();
while (true) {
// Have we already been here? If so, use the cached value.
const cachedEntry = getCacheEntry(curFlowNode);
if (cachedEntry) {
if (!cachedEntry.isIncomplete) {
return cachedEntry;
}
// If the cached entry is incomplete, we can use it only if nothing
// has changed that may cause the previously-reported incomplete type to change.
if (cachedEntry.generationCount === flowIncompleteGeneration) {
return {
type: cachedEntry?.type ? removeUnknownFromUnion(cachedEntry.type) : undefined,
isIncomplete: true,
};
}
}
if (curFlowNode.flags & FlowFlags.Unreachable) {
// We can get here if there are nodes in a compound logical expression
// (e.g. "False and x") that are never executed but are evaluated.
// The type doesn't matter in this case.
return setCacheEntry(curFlowNode, undefined, /* isIncomplete */ false);
}
if (curFlowNode.flags & FlowFlags.VariableAnnotation) {
const varAnnotationNode = curFlowNode as FlowVariableAnnotation;
curFlowNode = varAnnotationNode.antecedent;
continue;
}
if (curFlowNode.flags & FlowFlags.Call) {
const callFlowNode = curFlowNode as FlowCall;
// If this function returns a "NoReturn" type, that means
// it always raises an exception or otherwise doesn't return,
// so we can assume that the code before this is unreachable.
if (isCallNoReturn(callFlowNode.node)) {
return setCacheEntry(curFlowNode, undefined, /* isIncomplete */ false);
}
curFlowNode = callFlowNode.antecedent;
continue;
}
if (curFlowNode.flags & FlowFlags.Assignment) {
const assignmentFlowNode = curFlowNode as FlowAssignment;
// Are we targeting the same symbol? We need to do this extra check because the same
// symbol name might refer to different symbols in different scopes (e.g. a list
// comprehension introduces a new scope).
if (reference) {
if (
targetSymbolId === assignmentFlowNode.targetSymbolId &&
isMatchingExpression(reference, assignmentFlowNode.node)
) {
// Is this a special "unbind" assignment? If so,
// we can handle it immediately without any further evaluation.
if (curFlowNode.flags & FlowFlags.Unbind) {
return setCacheEntry(curFlowNode, UnboundType.create(), /* isIncomplete */ false);
}
// If there was a cache entry already, that means we hit a recursive
// case (something like "int: int = 4"). Avoid infinite recursion
// by returning an undefined type.
if (cachedEntry && cachedEntry.type === undefined) {
return { type: undefined, isIncomplete: true };
}
// Set the cache entry to undefined before evaluating the
// expression in case it depends on itself.
setCacheEntry(
curFlowNode,
reference ? undefined : initialType,
/* isIncomplete */ true
);
let flowTypeResult = evaluateAssignmentFlowNode(assignmentFlowNode);
if (flowTypeResult) {
if (isTypeAliasPlaceholder(flowTypeResult.type)) {
flowTypeResult = undefined;
} else if (
reference.nodeType === ParseNodeType.MemberAccess &&
evaluator.isAsymmetricDescriptorAssignment(assignmentFlowNode.node)
) {
flowTypeResult = undefined;
}
}
return setCacheEntry(curFlowNode, flowTypeResult?.type, !!flowTypeResult?.isIncomplete);
} else if (isPartialMatchingExpression(reference, assignmentFlowNode.node)) {
// If the node partially matches the reference, we need to "kill" any narrowed
// types further above this point. For example, if we see the sequence
// a.b = 3
// a = Foo()
// x = a.b
// The type of "a.b" can no longer be assumed to be Literal[3].
return {
type: initialType,
isIncomplete: isInitialTypeIncomplete,
};
}
}
curFlowNode = assignmentFlowNode.antecedent;
continue;
}
if (curFlowNode.flags & FlowFlags.BranchLabel) {
const branchFlowNode = curFlowNode as FlowBranchLabel;
if (curFlowNode.flags & FlowFlags.PostContextManager) {
// Determine whether any of the context managers support exception
// suppression. If not, none of its antecedents are reachable.
const contextMgrNode = curFlowNode as FlowPostContextManagerLabel;
if (
!contextMgrNode.expressions.some((expr) =>
isExceptionContextManager(expr, contextMgrNode.isAsync)
)
) {
return setCacheEntry(curFlowNode, undefined, /* isIncomplete */ false);
}
}
// Is the current symbol modified in any way within the scope of the branch?
// If not, we can skip all processing within the branch scope.
if (reference && branchFlowNode.preBranchAntecedent && branchFlowNode.affectedExpressions) {
if (!subexpressionReferenceKeys) {
subexpressionReferenceKeys = createKeysForReferenceSubexpressions(reference);
}
if (
!subexpressionReferenceKeys.some((key) =>
branchFlowNode.affectedExpressions!.has(key)
) &&
isFlowNodeReachable(curFlowNode, branchFlowNode.preBranchAntecedent)
) {
curFlowNode = branchFlowNode.preBranchAntecedent;
continue;
}
}
const labelNode = curFlowNode as FlowLabel;
const typesToCombine: Type[] = [];
let sawIncomplete = false;
// Set the cache entry to undefined before evaluating the
// expression in case it depends on itself.
setCacheEntry(curFlowNode, reference ? undefined : initialType, /* isIncomplete */ true);
labelNode.antecedents.forEach((antecedent) => {
const flowTypeResult = getTypeFromFlowNode(
antecedent,
reference,
targetSymbolId,
initialType,
isInitialTypeIncomplete
);
if (flowTypeResult.isIncomplete) {
sawIncomplete = true;
}
if (flowTypeResult.type) {
typesToCombine.push(flowTypeResult.type);
}
});
const effectiveType =
!!reference || typesToCombine.length > 0 ? combineTypes(typesToCombine) : undefined;
// Limit the number of recursive calls before we give up and call the type
// complete. This can theoretically result in incorrect type information in
// very complex code flows, but it's preferable to extremely long analysis times.
if (codeFlowInvocations - codeFlowInvocationsAtStart > maxCodeFlowInvocationsPerLoop) {
sawIncomplete = false;
}
return setCacheEntry(curFlowNode, effectiveType, sawIncomplete);
}
if (curFlowNode.flags & FlowFlags.LoopLabel) {
const loopNode = curFlowNode as FlowLabel;
// Is the current symbol modified in any way within the loop? If not, we can skip all
// processing within the loop and assume that the type comes from the first antecedent,
// which feeds the loop.
if (reference) {
if (!subexpressionReferenceKeys) {
subexpressionReferenceKeys = createKeysForReferenceSubexpressions(reference);
}
if (!subexpressionReferenceKeys.some((key) => loopNode.affectedExpressions!.has(key))) {
curFlowNode = loopNode.antecedents[0];
continue;
}
}
let sawIncomplete = false;
// See if we've been here before. If so, there will be an incomplete cache entry.
let cacheEntry = getCacheEntry(curFlowNode);
let typeAtStart: Type | undefined;
if (cacheEntry === undefined) {
// We haven't been here before, so create a new incomplete cache entry.
cacheEntry = setCacheEntry(
curFlowNode,
reference ? undefined : initialType,
/* isIncomplete */ true
);
} else {
typeAtStart = cacheEntry.type;
}
const isRecursive =
cacheEntry.incompleteSubtypes !== undefined &&
cacheEntry.incompleteSubtypes.some((subtype) => subtype.isPending);
const visitCount = incrementFlowNodeVisitCount(curFlowNode);
loopNode.antecedents.forEach((antecedent, index) => {
cacheEntry = getCacheEntry(curFlowNode)!;
// Have we already been here (i.e. does the entry exist and is
// not marked "pending")? If so, we can use the type that was already
// computed if it is complete.
const subtypeEntry =
cacheEntry.incompleteSubtypes !== undefined &&
index < cacheEntry.incompleteSubtypes.length
? cacheEntry.incompleteSubtypes[index]
: undefined;
if (
subtypeEntry === undefined ||
(!subtypeEntry?.isPending && subtypeEntry?.isIncomplete)
) {
// Set this entry to "pending" to prevent infinite recursion.
// We'll mark it "not pending" below.
cacheEntry = setIncompleteSubtype(
curFlowNode,
index,
subtypeEntry?.type ?? (reference ? undefined : initialType),
/* isIncomplete */ true,
/* isPending */ true
);
try {
const flowTypeResult = getTypeFromFlowNode(
antecedent,
reference,
targetSymbolId,
initialType,
isInitialTypeIncomplete
);
if (flowTypeResult.isIncomplete) {
sawIncomplete = true;
}
cacheEntry = setIncompleteSubtype(
curFlowNode,
index,
flowTypeResult.type,
flowTypeResult.isIncomplete,
/* isPending */ false
);
} catch (e) {
setIncompleteSubtype(
curFlowNode,
index,
undefined,
/* isIncomplete */ true,
/* isPending */ false
);
throw e;
}
}
});
if (isRecursive) {
// This was not the first time through the loop, so we are recursively trying
// to resolve other parts of the incomplete type. It will be marked complete
// once the stack pops back up to the first caller.
// If we have visited the loop node maxFlowNodeLoopVisitCount times already
// and some of the subtypes are still incomplete, bail and base the
// isIncomplete flag on the first subtype, which is the one that feeds
// the top of the loop.
let isIncomplete =
visitCount >= maxFlowNodeLoopVisitCount
? cacheEntry.incompleteSubtypes![0].isIncomplete
: reference !== undefined;
// Limit the number of recursive calls before we give up and call the type
// complete. This can theoretically result in incorrect type information in
// very complex code flows, but it's preferable to extremely long analysis times.
if (codeFlowInvocations - codeFlowInvocationsAtStart > maxCodeFlowInvocationsPerLoop) {
isIncomplete = false;
}
return {
type: cacheEntry.type,
isIncomplete,
};
}
// If we've been here more than once and the type has converged (didn't change
// since last time), assume that the type is complete.
if (sawIncomplete && typeAtStart && cacheEntry.type) {
if (isTypeSame(typeAtStart, cacheEntry.type)) {
// The type was the same more than two times, so it is not oscillating
// or changing. It's safe to conclude that additional times through
// the loop won't cause it to change further.
if (incrementFlowNodeConvergenceCount(flowNode) > 2) {
sawIncomplete = false;
}
} else {
// The type changed since last time, so reset the convergence count.
incrementFlowNodeConvergenceCount(flowNode, /* reset */ true);
}
}
// The result is incomplete if one or more entries were incomplete.
if (sawIncomplete) {
// If there is an "Unknown" type within a union type, remove
// it. Otherwise we might end up resolving the cycle with a type
// that includes an undesirable unknown.
// Note that we return isIncomplete = false here but do not
// save the cached entry for next time. This is because the
return {
type: cacheEntry?.type ? removeUnknownFromUnion(cacheEntry.type) : undefined,
isIncomplete: false,
};
}
// We have made it all the way through all the antecedents, and we can
// mark the type as complete.
return setCacheEntry(curFlowNode, cacheEntry!.type, /* isIncomplete */ false);
}
if (curFlowNode.flags & (FlowFlags.TrueCondition | FlowFlags.FalseCondition)) {
const conditionalFlowNode = curFlowNode as FlowCondition;
if (reference) {
// Before calling getTypeNarrowingCallback, set the type
// of this flow node in the cache to prevent recursion.
setCacheEntry(curFlowNode, reference ? undefined : initialType, /* isIncomplete */ true);
try {
const typeNarrowingCallback = getTypeNarrowingCallback(
evaluator,
reference,
conditionalFlowNode.expression,
!!(
conditionalFlowNode.flags &
(FlowFlags.TrueCondition | FlowFlags.TrueNeverCondition)
)
);
if (typeNarrowingCallback) {
const flowTypeResult = getTypeFromFlowNode(
conditionalFlowNode.antecedent,
reference,
targetSymbolId,
initialType,
isInitialTypeIncomplete
);
let flowType = flowTypeResult.type;
if (flowType) {
flowType = typeNarrowingCallback(flowType);
}
return setCacheEntry(curFlowNode, flowType, flowTypeResult.isIncomplete);
}
deleteCacheEntry(curFlowNode);
} catch (e) {
// We don't use finally here because the debugger
// doesn't handle it well during single stepping.
deleteCacheEntry(curFlowNode);
throw e;
}
}
curFlowNode = conditionalFlowNode.antecedent;
continue;
}
if (curFlowNode.flags & (FlowFlags.TrueNeverCondition | FlowFlags.FalseNeverCondition)) {
const conditionalFlowNode = curFlowNode as FlowCondition;
if (conditionalFlowNode.reference) {
// Make sure the reference type has a declared type. If not,
// don't bother trying to infer its type because that would be
// too expensive.
const symbolWithScope = evaluator.lookUpSymbolRecursive(
conditionalFlowNode.reference,
conditionalFlowNode.reference.value,
/* honorCodeFlow */ false
);
if (symbolWithScope && symbolWithScope.symbol.getTypedDeclarations().length > 0) {
// Before calling getTypeNarrowingCallback, set the type
// of this flow node in the cache to prevent recursion.
setCacheEntry(
curFlowNode,
reference ? undefined : initialType,
/* isIncomplete */ true
);
try {
const typeNarrowingCallback = getTypeNarrowingCallback(
evaluator,
conditionalFlowNode.reference,
conditionalFlowNode.expression,
!!(
conditionalFlowNode.flags &
(FlowFlags.TrueCondition | FlowFlags.TrueNeverCondition)
)
);
if (typeNarrowingCallback) {
const refTypeInfo = evaluator.getTypeOfExpression(
conditionalFlowNode.reference!
);
const narrowedType =
typeNarrowingCallback(refTypeInfo.type) || refTypeInfo.type;
// If the narrowed type is "never", don't allow further exploration.
if (isNever(narrowedType)) {
return setCacheEntry(curFlowNode, undefined, !!refTypeInfo.isIncomplete);
}
}
deleteCacheEntry(curFlowNode);
} catch (e) {
// We don't use finally here because the debugger
// doesn't handle it well during single stepping.
deleteCacheEntry(curFlowNode);
throw e;
}
}
}
curFlowNode = conditionalFlowNode.antecedent;
continue;
}
if (curFlowNode.flags & FlowFlags.ExhaustedMatch) {
const exhaustedMatchFlowNode = curFlowNode as FlowExhaustedMatch;
const narrowedTypeResult = evaluator.evaluateTypeForSubnode(exhaustedMatchFlowNode.node, () => {
evaluator.evaluateTypesForMatchNode(exhaustedMatchFlowNode.node);
});
// If the narrowed type is "never", don't allow further exploration.
if (narrowedTypeResult && isNever(narrowedTypeResult.type)) {
return setCacheEntry(curFlowNode, undefined, !!narrowedTypeResult.isIncomplete);
}
curFlowNode = exhaustedMatchFlowNode.antecedent;
continue;
}
if (curFlowNode.flags & FlowFlags.NarrowForPattern) {
const patternFlowNode = curFlowNode as FlowNarrowForPattern;
if (!reference || isMatchingExpression(reference, patternFlowNode.subjectExpression)) {
const typeResult = evaluator.evaluateTypeForSubnode(patternFlowNode.statement, () => {
if (patternFlowNode.statement.nodeType === ParseNodeType.Case) {
evaluator.evaluateTypesForCaseNode(patternFlowNode.statement);
} else {
evaluator.evaluateTypesForMatchNode(patternFlowNode.statement);
}
});
if (typeResult) {
if (!reference) {
if (isNever(typeResult.type)) {
return setCacheEntry(curFlowNode, undefined, !!typeResult.isIncomplete);
}
} else {
return setCacheEntry(curFlowNode, typeResult.type, !!typeResult.isIncomplete);
}
}
}
curFlowNode = patternFlowNode.antecedent;
continue;
}
if (curFlowNode.flags & FlowFlags.PreFinallyGate) {
const preFinallyFlowNode = curFlowNode as FlowPreFinallyGate;
if (preFinallyFlowNode.isGateClosed) {
return { type: undefined, isIncomplete: false };
}
// Before recursively calling, set the cache entry to prevent infinite recursion.
setCacheEntry(curFlowNode, reference ? undefined : initialType, /* isIncomplete */ true);
try {
const flowTypeResult = getTypeFromFlowNode(
preFinallyFlowNode.antecedent,
reference,
targetSymbolId,
initialType,
isInitialTypeIncomplete
);
// Mark the result as incomplete even if the result of the recursive
// call indicated it was complete. This will prevent the type from
// being permanently cached. We want to cache the type only if
// we're evaluating the "gate closed" path.
return setCacheEntry(curFlowNode, flowTypeResult.type, /* isIncomplete */ true);
} catch (e) {
deleteCacheEntry(curFlowNode);
throw e;
}
}
if (curFlowNode.flags & FlowFlags.PostFinally) {
const postFinallyFlowNode = curFlowNode as FlowPostFinally;
const wasGateClosed = postFinallyFlowNode.preFinallyGate.isGateClosed;
try {
postFinallyFlowNode.preFinallyGate.isGateClosed = true;
let flowTypeResult: FlowNodeTypeResult | undefined;
// Use speculative mode for the remainder of the finally suite
// because the final types within this parse node block should be
// evaluated when the gate is open.
evaluator.useSpeculativeMode(postFinallyFlowNode.finallyNode, () => {
flowTypeResult = getTypeFromFlowNode(
postFinallyFlowNode.antecedent,
reference,
targetSymbolId,
initialType,
isInitialTypeIncomplete
);
});
// If the type is incomplete, don't write back to the cache.
return flowTypeResult!.isIncomplete
? flowTypeResult!
: setCacheEntry(curFlowNode, flowTypeResult!.type, /* isIncomplete */ false);
} finally {
postFinallyFlowNode.preFinallyGate.isGateClosed = wasGateClosed;
}
}
if (curFlowNode.flags & FlowFlags.Start) {
return setCacheEntry(curFlowNode, initialType, isInitialTypeIncomplete);
}
if (curFlowNode.flags & FlowFlags.WildcardImport) {
const wildcardImportFlowNode = curFlowNode as FlowWildcardImport;
if (reference && reference.nodeType === ParseNodeType.Name) {
const nameValue = reference.value;
if (wildcardImportFlowNode.names.some((name) => name === nameValue)) {
// Before calling getTypeFromWildcardImport, set the cache entry to prevent infinite recursion.
setCacheEntry(
curFlowNode,
reference ? undefined : initialType,
/* isIncomplete */ true
);
try {
const type = getTypeFromWildcardImport(wildcardImportFlowNode, nameValue);
return setCacheEntry(curFlowNode, type, /* isIncomplete */ false);
} catch (e) {
deleteCacheEntry(curFlowNode);
throw e;
}
}
}
curFlowNode = wildcardImportFlowNode.antecedent;
continue;
}
// We shouldn't get here.
fail('Unexpected flow node flags');
return setCacheEntry(curFlowNode, undefined, /* isIncomplete */ false);
}
}
if (!flowNode) {
// This should happen only in cases where we're evaluating
// parse nodes that are created after the initial parse
// (namely, string literals that are used for forward
// referenced types).
return {
type: initialType,
isIncomplete: isInitialTypeIncomplete,
};
}
return getTypeFromFlowNode(flowNode, reference, targetSymbolId, initialType, isInitialTypeIncomplete);
}
return {
getTypeFromCodeFlow,
};
}
// Determines whether the specified flowNode can be reached by any
// control flow path within the execution context. If sourceFlowNode
// is specified, it returns true only if at least one control flow
// path passes through sourceFlowNode.
function isFlowNodeReachable(flowNode: FlowNode, sourceFlowNode?: FlowNode): boolean {
const visitedFlowNodeMap = new Set<number>();
function isFlowNodeReachableRecursive(
flowNode: FlowNode,
sourceFlowNode: FlowNode | undefined,
recursionCount = 0
): boolean {
// Cut off the recursion at some point to prevent a stack overflow.
const maxFlowNodeReachableRecursionCount = 64;
if (recursionCount > maxFlowNodeReachableRecursionCount) {
return true;
}
recursionCount++;
let curFlowNode = flowNode;
while (true) {
// If we've already visited this node, we can assume
// it wasn't reachable.
if (visitedFlowNodeMap.has(curFlowNode.id)) {
return false;
}
// Note that we've been here before.
visitedFlowNodeMap.add(curFlowNode.id);
if (curFlowNode.flags & FlowFlags.Unreachable) {
return false;
}
if (curFlowNode === sourceFlowNode) {
return true;
}
if (
curFlowNode.flags &
(FlowFlags.VariableAnnotation |
FlowFlags.Assignment |
FlowFlags.TrueCondition |
FlowFlags.FalseCondition |
FlowFlags.WildcardImport |
FlowFlags.TrueNeverCondition |
FlowFlags.FalseNeverCondition |
FlowFlags.NarrowForPattern |
FlowFlags.ExhaustedMatch)
) {
const typedFlowNode = curFlowNode as
| FlowVariableAnnotation
| FlowAssignment
| FlowCondition
| FlowWildcardImport
| FlowCondition
| FlowExhaustedMatch;
curFlowNode = typedFlowNode.antecedent;
continue;
}
if (curFlowNode.flags & FlowFlags.Call) {
const callFlowNode = curFlowNode as FlowCall;
// If this function returns a "NoReturn" type, that means
// it always raises an exception or otherwise doesn't return,
// so we can assume that the code before this is unreachable.
if (isCallNoReturn(callFlowNode.node)) {
return false;
}
curFlowNode = callFlowNode.antecedent;
continue;