@zzzen/pyright-internal 1.2.0-dev.20221225 → 1.2.0-dev.20230108

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/analyzer/binder.js +5 -3
  2. package/dist/analyzer/binder.js.map +1 -1
  3. package/dist/analyzer/checker.js +17 -11
  4. package/dist/analyzer/checker.js.map +1 -1
  5. package/dist/analyzer/codeFlowEngine.d.ts +16 -1
  6. package/dist/analyzer/codeFlowEngine.js +36 -13
  7. package/dist/analyzer/codeFlowEngine.js.map +1 -1
  8. package/dist/analyzer/constraintSolver.js +30 -31
  9. package/dist/analyzer/constraintSolver.js.map +1 -1
  10. package/dist/analyzer/importResolver.d.ts +2 -1
  11. package/dist/analyzer/importResolver.js +18 -3
  12. package/dist/analyzer/importResolver.js.map +1 -1
  13. package/dist/analyzer/patternMatching.js +5 -4
  14. package/dist/analyzer/patternMatching.js.map +1 -1
  15. package/dist/analyzer/program.d.ts +1 -0
  16. package/dist/analyzer/program.js +52 -25
  17. package/dist/analyzer/program.js.map +1 -1
  18. package/dist/analyzer/regions.js +14 -5
  19. package/dist/analyzer/regions.js.map +1 -1
  20. package/dist/analyzer/sourceFile.d.ts +1 -1
  21. package/dist/analyzer/sourceFile.js +1 -0
  22. package/dist/analyzer/sourceFile.js.map +1 -1
  23. package/dist/analyzer/sourceMapper.d.ts +2 -2
  24. package/dist/analyzer/sourceMapper.js +14 -5
  25. package/dist/analyzer/sourceMapper.js.map +1 -1
  26. package/dist/analyzer/typeCacheUtils.d.ts +26 -0
  27. package/dist/analyzer/{typeCache.js → typeCacheUtils.js} +9 -19
  28. package/dist/analyzer/typeCacheUtils.js.map +1 -0
  29. package/dist/analyzer/typeDocStringUtils.d.ts +2 -1
  30. package/dist/analyzer/typeDocStringUtils.js +18 -7
  31. package/dist/analyzer/typeDocStringUtils.js.map +1 -1
  32. package/dist/analyzer/typeEvaluator.js +551 -379
  33. package/dist/analyzer/typeEvaluator.js.map +1 -1
  34. package/dist/analyzer/typeEvaluatorTypes.d.ts +2 -1
  35. package/dist/analyzer/typeGuards.d.ts +5 -1
  36. package/dist/analyzer/typeGuards.js +181 -45
  37. package/dist/analyzer/typeGuards.js.map +1 -1
  38. package/dist/analyzer/typeUtils.d.ts +13 -3
  39. package/dist/analyzer/typeUtils.js +288 -135
  40. package/dist/analyzer/typeUtils.js.map +1 -1
  41. package/dist/analyzer/typeVarContext.d.ts +2 -10
  42. package/dist/analyzer/typeVarContext.js +12 -31
  43. package/dist/analyzer/typeVarContext.js.map +1 -1
  44. package/dist/analyzer/types.d.ts +4 -12
  45. package/dist/analyzer/types.js +22 -22
  46. package/dist/analyzer/types.js.map +1 -1
  47. package/dist/commands/dumpFileDebugInfoCommand.js +2 -2
  48. package/dist/commands/dumpFileDebugInfoCommand.js.map +1 -1
  49. package/dist/commands/quickActionCommand.js +1 -1
  50. package/dist/commands/quickActionCommand.js.map +1 -1
  51. package/dist/common/collectionUtils.d.ts +1 -0
  52. package/dist/common/collectionUtils.js +9 -1
  53. package/dist/common/collectionUtils.js.map +1 -1
  54. package/dist/common/textEditUtils.d.ts +3 -2
  55. package/dist/common/textEditUtils.js +11 -10
  56. package/dist/common/textEditUtils.js.map +1 -1
  57. package/dist/languageServerBase.d.ts +1 -1
  58. package/dist/languageService/completionProvider.d.ts +3 -0
  59. package/dist/languageService/completionProvider.js +212 -159
  60. package/dist/languageService/completionProvider.js.map +1 -1
  61. package/dist/languageService/hoverProvider.d.ts +0 -1
  62. package/dist/languageService/hoverProvider.js +7 -20
  63. package/dist/languageService/hoverProvider.js.map +1 -1
  64. package/dist/languageService/indentationUtils.js +1 -1
  65. package/dist/languageService/indentationUtils.js.map +1 -1
  66. package/dist/languageService/tooltipUtils.d.ts +5 -1
  67. package/dist/languageService/tooltipUtils.js +28 -4
  68. package/dist/languageService/tooltipUtils.js.map +1 -1
  69. package/dist/localization/localize.d.ts +18 -3
  70. package/dist/localization/localize.js +7 -1
  71. package/dist/localization/localize.js.map +1 -1
  72. package/dist/localization/package.nls.en-us.json +7 -1
  73. package/dist/parser/parser.js +3 -1
  74. package/dist/parser/parser.js.map +1 -1
  75. package/dist/tests/completions.test.d.ts +1 -0
  76. package/dist/tests/completions.test.js +331 -0
  77. package/dist/tests/completions.test.js.map +1 -0
  78. package/dist/tests/filesystem.test.js +11 -0
  79. package/dist/tests/filesystem.test.js.map +1 -1
  80. package/dist/tests/harness/fourslash/testState.js +1 -1
  81. package/dist/tests/harness/fourslash/testState.js.map +1 -1
  82. package/dist/tests/harness/vfs/filesystem.d.ts +2 -2
  83. package/dist/tests/harness/vfs/filesystem.js +5 -1
  84. package/dist/tests/harness/vfs/filesystem.js.map +1 -1
  85. package/dist/tests/hoverProvider.test.d.ts +1 -0
  86. package/dist/tests/hoverProvider.test.js +247 -0
  87. package/dist/tests/hoverProvider.test.js.map +1 -0
  88. package/dist/tests/indentationUtils.ptvs.test.js +1 -1
  89. package/dist/tests/indentationUtils.test.js +4 -4
  90. package/dist/tests/typeEvaluator1.test.js +16 -0
  91. package/dist/tests/typeEvaluator1.test.js.map +1 -1
  92. package/dist/tests/typeEvaluator2.test.js +6 -2
  93. package/dist/tests/typeEvaluator2.test.js.map +1 -1
  94. package/dist/tests/typeEvaluator3.test.js +9 -1
  95. package/dist/tests/typeEvaluator3.test.js.map +1 -1
  96. package/dist/tests/typeEvaluator4.test.js +8 -0
  97. package/dist/tests/typeEvaluator4.test.js.map +1 -1
  98. package/dist/tests/typeEvaluator5.test.js +54 -6
  99. package/dist/tests/typeEvaluator5.test.js.map +1 -1
  100. package/dist/workspaceMap.js +1 -3
  101. package/dist/workspaceMap.js.map +1 -1
  102. package/package.json +6 -6
  103. package/dist/analyzer/typeCache.d.ts +0 -40
  104. package/dist/analyzer/typeCache.js.map +0 -1
@@ -67,7 +67,7 @@ const staticExpressions_1 = require("./staticExpressions");
67
67
  const symbol_1 = require("./symbol");
68
68
  const symbolNameUtils_1 = require("./symbolNameUtils");
69
69
  const symbolUtils_1 = require("./symbolUtils");
70
- const typeCache_1 = require("./typeCache");
70
+ const typeCacheUtils_1 = require("./typeCacheUtils");
71
71
  const typedDicts_1 = require("./typedDicts");
72
72
  const typeEvaluatorTypes_1 = require("./typeEvaluatorTypes");
73
73
  const TypePrinter = __importStar(require("./typePrinter"));
@@ -227,9 +227,8 @@ const maxLiteralMathSubtypeCount = 64;
227
227
  exports.maxCodeComplexity = 768;
228
228
  function createTypeEvaluator(importLookup, evaluatorOptions) {
229
229
  const symbolResolutionStack = [];
230
- const typeCacheFlags = new Map();
231
230
  const asymmetricDescriptorAssignmentCache = new Set();
232
- const speculativeTypeTracker = new typeCache_1.SpeculativeTypeTracker();
231
+ const speculativeTypeTracker = new typeCacheUtils_1.SpeculativeTypeTracker();
233
232
  const suppressedNodeStack = [];
234
233
  let functionRecursionMap = new Set();
235
234
  let codeFlowAnalyzerCache = new Map();
@@ -250,7 +249,6 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
250
249
  let strClassType;
251
250
  let dictClassType;
252
251
  let typedDictClassType;
253
- let incompleteTypeCache;
254
252
  let printExpressionSpaceCount = 0;
255
253
  const returnTypeInferenceContextStack = [];
256
254
  let returnTypeInferenceTypeCache;
@@ -284,33 +282,29 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
284
282
  effectiveTypeCache = new Map();
285
283
  expectedTypeCache = new Map();
286
284
  }
287
- function isTypeCached(node) {
288
- let cachedType;
285
+ function readTypeCacheEntry(node) {
286
+ // Should we use a temporary cache associated with a contextual
287
+ // analysis of a function, contextualized based on call-site argument types?
289
288
  if (returnTypeInferenceTypeCache && isNodeInReturnTypeInferenceContext(node)) {
290
- cachedType = returnTypeInferenceTypeCache.get(node.id);
289
+ return returnTypeInferenceTypeCache.get(node.id);
291
290
  }
292
291
  else {
293
- cachedType = typeCache.get(node.id);
292
+ return typeCache.get(node.id);
294
293
  }
295
- return cachedType !== undefined;
294
+ }
295
+ function isTypeCached(node) {
296
+ const cachedEntry = readTypeCacheEntry(node);
297
+ return cachedEntry !== undefined && !cachedEntry.typeResult.isIncomplete;
296
298
  }
297
299
  function readTypeCache(node, flags) {
298
300
  var _a, _b;
299
- let cachedType;
300
- // Should we use a temporary cache associated with a contextual
301
- // analysis of a function, contextualized based on call-site argument types?
302
- if (returnTypeInferenceTypeCache && isNodeInReturnTypeInferenceContext(node)) {
303
- cachedType = returnTypeInferenceTypeCache.get(node.id);
304
- }
305
- else {
306
- cachedType = typeCache.get(node.id);
307
- }
308
- if (cachedType === undefined) {
301
+ const cacheEntry = readTypeCacheEntry(node);
302
+ if (!cacheEntry || cacheEntry.typeResult.isIncomplete) {
309
303
  return undefined;
310
304
  }
311
305
  if (evaluatorOptions.verifyTypeCacheEvaluatorFlags || verifyTypeCacheEvaluatorFlags) {
312
306
  if (flags !== undefined) {
313
- const expectedFlags = typeCacheFlags.get(node.id);
307
+ const expectedFlags = cacheEntry.flags;
314
308
  if (expectedFlags !== undefined && flags !== expectedFlags) {
315
309
  const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
316
310
  const position = (0, positionUtils_1.convertOffsetToPosition)(node.start, fileInfo.lines);
@@ -327,34 +321,22 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
327
321
  }
328
322
  }
329
323
  }
330
- (0, debug_1.assert)(!(0, typeCache_1.isIncompleteType)(cachedType));
331
- return cachedType;
324
+ return cacheEntry.typeResult.type;
332
325
  }
333
- function writeTypeCache(node, type, flags, isIncomplete, expectedType, allowSpeculativeCaching = false) {
334
- if (isIncomplete) {
335
- if (incompleteTypeCache) {
336
- incompleteTypeCache.set(node.id, type);
337
- }
338
- return;
339
- }
326
+ function writeTypeCache(node, typeResult, flags, expectedType, allowSpeculativeCaching = false) {
340
327
  // Should we use a temporary cache associated with a contextual
341
328
  // analysis of a function, contextualized based on call-site argument types?
342
329
  const typeCacheToUse = returnTypeInferenceTypeCache && isNodeInReturnTypeInferenceContext(node)
343
330
  ? returnTypeInferenceTypeCache
344
331
  : typeCache;
345
- typeCacheToUse.set(node.id, type);
346
- if (evaluatorOptions.verifyTypeCacheEvaluatorFlags || verifyTypeCacheEvaluatorFlags) {
347
- if (typeCacheToUse === typeCache && flags !== undefined) {
348
- typeCacheFlags.set(node.id, flags);
349
- }
350
- }
332
+ typeCacheToUse.set(node.id, { typeResult, flags });
351
333
  // If the entry is located within a part of the parse tree that is currently being
352
334
  // "speculatively" evaluated, track it so we delete the cached entry when we leave
353
335
  // this speculative context.
354
336
  if (speculativeTypeTracker.isSpeculative(node)) {
355
337
  speculativeTypeTracker.trackEntry(typeCacheToUse, node.id);
356
- if (allowSpeculativeCaching) {
357
- speculativeTypeTracker.addSpeculativeType(node, type, expectedType);
338
+ if (allowSpeculativeCaching && !typeResult.isIncomplete) {
339
+ speculativeTypeTracker.addSpeculativeType(node, typeResult, expectedType);
358
340
  }
359
341
  }
360
342
  }
@@ -365,7 +347,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
365
347
  typeCacheToUse.delete(node.id);
366
348
  }
367
349
  function setTypeForNode(node, type = types_1.UnknownType.create(), flags = 0 /* None */) {
368
- writeTypeCache(node, type, flags, /* isIncomplete */ false);
350
+ writeTypeCache(node, { type }, flags);
369
351
  }
370
352
  function setAsymmetricDescriptorAssignment(node) {
371
353
  if (speculativeTypeTracker.isSpeculative(/* node */ undefined)) {
@@ -447,6 +429,11 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
447
429
  evaluateTypesForExpressionInContext(node);
448
430
  })) === null || _a === void 0 ? void 0 : _a.type;
449
431
  }
432
+ function getTypeResult(node) {
433
+ return evaluateTypeForSubnode(node, () => {
434
+ evaluateTypesForExpressionInContext(node);
435
+ });
436
+ }
450
437
  // Reads the type of the node from the cache.
451
438
  function getCachedType(node) {
452
439
  return readTypeCache(node, 0 /* None */);
@@ -508,21 +495,21 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
508
495
  function getTypeOfExpression(node, flags = 0 /* None */, expectedType) {
509
496
  var _a;
510
497
  // Is this type already cached?
511
- const cachedType = readTypeCache(node, flags);
512
- if (cachedType) {
498
+ const cacheEntry = readTypeCacheEntry(node);
499
+ if (cacheEntry && !cacheEntry.typeResult.isIncomplete) {
513
500
  if (printExpressionTypes) {
514
- console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Cached ${printType(cachedType)}`);
501
+ console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Cached ${printType(cacheEntry.typeResult.type)} ${cacheEntry.typeResult.typeErrors ? ' Errors' : ''}`);
515
502
  }
516
- return { type: cachedType };
503
+ return cacheEntry.typeResult;
517
504
  }
518
505
  else {
519
506
  // Is it cached in the speculative type cache?
520
- const speculativeCachedType = speculativeTypeTracker.getSpeculativeType(node, expectedType);
521
- if (speculativeCachedType) {
507
+ const cachedTypeResult = speculativeTypeTracker.getSpeculativeType(node, expectedType);
508
+ if (cachedTypeResult) {
522
509
  if (printExpressionTypes) {
523
- console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Speculative ${printType(speculativeCachedType)}`);
510
+ console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Speculative ${printType(cachedTypeResult.type)}`);
524
511
  }
525
- return { type: speculativeCachedType };
512
+ return cachedTypeResult;
526
513
  }
527
514
  }
528
515
  if (printExpressionTypes) {
@@ -707,8 +694,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
707
694
  typeResult.type.details.illegalRecursionDetected = true;
708
695
  }
709
696
  }
710
- writeTypeCache(node, typeResult.type, flags, !!typeResult.isIncomplete, expectedType,
711
- /* allowSpeculativeCaching */ true);
697
+ writeTypeCache(node, typeResult, flags, expectedType, /* allowSpeculativeCaching */ true);
712
698
  if (expectedType && !(0, types_1.isAnyOrUnknown)(expectedType) && !(0, types_1.isNever)(expectedType)) {
713
699
  expectedTypeCache.set(node.id, expectedType);
714
700
  if (!typeResult.isIncomplete && !typeResult.expectedTypeDiagAddendum) {
@@ -2099,7 +2085,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2099
2085
  if (!isTypeIncomplete) {
2100
2086
  reportPossibleUnknownAssignment(fileInfo.diagnosticRuleSet.reportUnknownVariableType, diagnosticRules_1.DiagnosticRule.reportUnknownVariableType, nameNode, destType, nameNode, ignoreEmptyContainers);
2101
2087
  }
2102
- writeTypeCache(nameNode, destType, 0 /* None */, isTypeIncomplete);
2088
+ writeTypeCache(nameNode, { type: destType, isIncomplete: isTypeIncomplete }, 0 /* None */);
2103
2089
  }
2104
2090
  function assignTypeToMemberAccessNode(target, type, isTypeIncomplete, srcExpr, expectedTypeDiagAddendum) {
2105
2091
  const baseTypeResult = getTypeOfExpression(target.leftExpression, 2 /* DoNotSpecialize */);
@@ -2143,8 +2129,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2143
2129
  if (setTypeResult.isAsymmetricDescriptor) {
2144
2130
  setAsymmetricDescriptorAssignment(target);
2145
2131
  }
2146
- writeTypeCache(target.memberName, type, 0 /* None */, isTypeIncomplete);
2147
- writeTypeCache(target, type, 0 /* None */, isTypeIncomplete);
2132
+ writeTypeCache(target.memberName, { type, isIncomplete: isTypeIncomplete }, 0 /* None */);
2133
+ writeTypeCache(target, { type, isIncomplete: isTypeIncomplete }, 0 /* None */);
2148
2134
  }
2149
2135
  function assignTypeToMemberVariable(node, srcType, isTypeIncomplete, isInstanceMember, srcExprNode) {
2150
2136
  const memberName = node.memberName.value;
@@ -2319,7 +2305,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2319
2305
  const targetType = typeList.length === 0 ? types_1.UnknownType.create() : (0, types_1.combineTypes)(typeList);
2320
2306
  assignTypeToExpression(expr, targetType, isTypeIncomplete, srcExpr, /* ignoreEmptyContainers */ true);
2321
2307
  });
2322
- writeTypeCache(target, type, 0 /* None */, isTypeIncomplete);
2308
+ writeTypeCache(target, { type, isIncomplete: isTypeIncomplete }, 0 /* None */);
2323
2309
  }
2324
2310
  // Replaces all of the top-level TypeVars (as opposed to TypeVars
2325
2311
  // used as type arguments in other types) with their concrete form.
@@ -2546,7 +2532,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2546
2532
  setErrorNode: srcExpr,
2547
2533
  setExpectedTypeDiag: expectedTypeDiagAddendum,
2548
2534
  }, 0 /* None */);
2549
- writeTypeCache(target, type, 0 /* None */, isTypeIncomplete);
2535
+ writeTypeCache(target, { type, isIncomplete: isTypeIncomplete }, 0 /* None */);
2550
2536
  break;
2551
2537
  }
2552
2538
  case 31 /* List */:
@@ -2669,14 +2655,14 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2669
2655
  case 35 /* MemberAccess */: {
2670
2656
  const baseTypeResult = getTypeOfExpression(node.leftExpression, 2 /* DoNotSpecialize */);
2671
2657
  const memberType = getTypeOfMemberAccessWithBaseType(node, baseTypeResult, { method: 'del' }, 0 /* None */);
2672
- writeTypeCache(node.memberName, memberType.type, 0 /* None */, /* isIncomplete */ false);
2673
- writeTypeCache(node, memberType.type, 0 /* None */, /* isIncomplete */ false);
2658
+ writeTypeCache(node.memberName, { type: memberType.type }, 0 /* None */);
2659
+ writeTypeCache(node, { type: memberType.type }, 0 /* None */);
2674
2660
  break;
2675
2661
  }
2676
2662
  case 24 /* Index */: {
2677
2663
  const baseTypeResult = getTypeOfExpression(node.baseExpression, 2 /* DoNotSpecialize */);
2678
2664
  getTypeOfIndexWithBaseType(node, baseTypeResult, { method: 'del' }, 0 /* None */);
2679
- writeTypeCache(node, types_1.UnboundType.create(), 0 /* None */, /* isIncomplete */ false);
2665
+ writeTypeCache(node, { type: types_1.UnboundType.create() }, 0 /* None */);
2680
2666
  break;
2681
2667
  }
2682
2668
  case 52 /* Tuple */: {
@@ -2758,7 +2744,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2758
2744
  return undefined;
2759
2745
  }
2760
2746
  function getTypeOfName(node, flags) {
2761
- var _a, _b;
2747
+ var _a;
2762
2748
  const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
2763
2749
  const name = node.value;
2764
2750
  let symbol;
@@ -2769,7 +2755,10 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2769
2755
  const typeParamSymbol = AnalyzerNodeInfo.getTypeParameterSymbol(node);
2770
2756
  if (typeParamSymbol) {
2771
2757
  symbol = typeParamSymbol;
2772
- type = (_a = getDeclaredTypeOfSymbol(typeParamSymbol)) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
2758
+ (0, debug_1.assert)(symbol.getDeclarations().length === 1);
2759
+ const decl = (0, symbolUtils_1.getLastTypedDeclaredForSymbol)(symbol);
2760
+ (0, debug_1.assert)((decl === null || decl === void 0 ? void 0 : decl.type) === 3 /* TypeParameter */);
2761
+ type = getTypeOfTypeParameter(decl.node);
2773
2762
  setSymbolAccessed(fileInfo, symbol, node);
2774
2763
  }
2775
2764
  else {
@@ -2910,7 +2899,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
2910
2899
  type.details.name === name) {
2911
2900
  // Handle the special case of a PEP 604 union. These can appear within
2912
2901
  // an implied type alias where we are not expecting a type.
2913
- const isPep604Union = ((_b = node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 7 /* BinaryOperation */ &&
2902
+ const isPep604Union = ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 7 /* BinaryOperation */ &&
2914
2903
  node.parent.operator === 6 /* BitwiseOr */;
2915
2904
  if (!isPep604Union) {
2916
2905
  // A TypeVar in contexts where we're not expecting a type is
@@ -3026,7 +3015,15 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3026
3015
  if (memberName === 'args' || memberName === 'kwargs') {
3027
3016
  const outerFunctionScope = ParseTreeUtils.getEnclosingClassOrFunction(enclosingScope);
3028
3017
  if ((outerFunctionScope === null || outerFunctionScope === void 0 ? void 0 : outerFunctionScope.nodeType) === 28 /* Function */) {
3029
- enclosingScope = outerFunctionScope;
3018
+ if (scopedTypeVarInfo.isRescoped) {
3019
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet
3020
+ .reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.paramSpecScopedToReturnType().format({
3021
+ name: type.details.name,
3022
+ }), node);
3023
+ }
3024
+ else {
3025
+ enclosingScope = outerFunctionScope;
3026
+ }
3030
3027
  }
3031
3028
  else if (!scopedTypeVarInfo.type.scopeId) {
3032
3029
  addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.paramSpecNotUsedByOuterScope().format({
@@ -3038,7 +3035,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3038
3035
  if (enclosingScope) {
3039
3036
  // If the enclosing scope is using type parameter syntax, traditional
3040
3037
  // type variables can't be used in this context.
3041
- if (enclosingScope.typeParameters) {
3038
+ if (enclosingScope.typeParameters &&
3039
+ !enclosingScope.typeParameters.parameters.some((param) => param.name.value === type.details.name)) {
3042
3040
  addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeParameterNotDeclared().format({
3043
3041
  name: type.details.name,
3044
3042
  container: enclosingScope.name.value,
@@ -3060,9 +3058,17 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3060
3058
  else if ((flags & 4096 /* DisallowTypeVarsWithoutScopeId */) !== 0) {
3061
3059
  if ((type.scopeId === undefined || scopedTypeVarInfo.foundInterveningClass) &&
3062
3060
  !type.details.isSynthesized) {
3063
- const message = (0, types_1.isParamSpec)(type)
3064
- ? localize_1.Localizer.Diagnostic.paramSpecNotUsedByOuterScope()
3065
- : localize_1.Localizer.Diagnostic.typeVarNotUsedByOuterScope();
3061
+ let message;
3062
+ if (scopedTypeVarInfo.isRescoped) {
3063
+ message = (0, types_1.isParamSpec)(type)
3064
+ ? localize_1.Localizer.Diagnostic.paramSpecScopedToReturnType()
3065
+ : localize_1.Localizer.Diagnostic.typeVarScopedToReturnType();
3066
+ }
3067
+ else {
3068
+ message = (0, types_1.isParamSpec)(type)
3069
+ ? localize_1.Localizer.Diagnostic.paramSpecNotUsedByOuterScope()
3070
+ : localize_1.Localizer.Diagnostic.typeVarNotUsedByOuterScope();
3071
+ }
3066
3072
  addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, message.format({ name: type.details.name }), node);
3067
3073
  }
3068
3074
  }
@@ -3078,43 +3084,51 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3078
3084
  // type arguments. If so, it fills in these type arguments with Unknown
3079
3085
  // and optionally reports an error.
3080
3086
  function reportMissingTypeArguments(node, type, flags) {
3081
- if ((flags & 2 /* DoNotSpecialize */) === 0) {
3082
- if ((0, types_1.isInstantiableClass)(type)) {
3083
- if ((flags & 64 /* ExpectingType */) !== 0) {
3084
- if ((0, typeUtils_1.requiresTypeArguments)(type) && !type.typeArguments) {
3085
- addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportMissingTypeArgument, diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument, localize_1.Localizer.Diagnostic.typeArgsMissingForClass().format({
3086
- name: type.aliasName || type.details.name,
3087
- }), node);
3088
- }
3089
- }
3090
- if (!type.typeArguments) {
3091
- type = createSpecializedClassType(type, /* typeArgs */ undefined, flags, node);
3087
+ if ((flags & 2 /* DoNotSpecialize */) !== 0) {
3088
+ return type;
3089
+ }
3090
+ // Is this a generic class that needs to be specialized?
3091
+ if ((0, types_1.isInstantiableClass)(type)) {
3092
+ if ((flags & 64 /* ExpectingType */) !== 0) {
3093
+ if ((0, typeUtils_1.requiresTypeArguments)(type) && !type.typeArguments) {
3094
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportMissingTypeArgument, diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument, localize_1.Localizer.Diagnostic.typeArgsMissingForClass().format({
3095
+ name: type.aliasName || type.details.name,
3096
+ }), node);
3092
3097
  }
3093
3098
  }
3094
- if ((flags & 64 /* ExpectingType */) !== 0 &&
3095
- type.typeAliasInfo &&
3096
- type.typeAliasInfo.typeParameters &&
3097
- type.typeAliasInfo.typeParameters.length > 0 &&
3098
- !type.typeAliasInfo.typeArguments) {
3099
- let reportMissingTypeArguments = false;
3100
- const defaultTypeArgs = [];
3101
- type.typeAliasInfo.typeParameters.forEach((param) => {
3102
- if (param.details.defaultType) {
3103
- defaultTypeArgs.push(param.details.defaultType);
3104
- }
3105
- else {
3106
- defaultTypeArgs.push(types_1.UnknownType.create());
3107
- reportMissingTypeArguments = true;
3108
- }
3109
- });
3110
- const typeVarContext = (0, typeUtils_1.buildTypeVarContext)(type.typeAliasInfo.typeParameters, defaultTypeArgs, type.typeAliasInfo.typeVarScopeId);
3111
- if (reportMissingTypeArguments) {
3112
- addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportMissingTypeArgument, diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument, localize_1.Localizer.Diagnostic.typeArgsMissingForAlias().format({
3113
- name: type.typeAliasInfo.name,
3114
- }), node);
3099
+ if (!type.typeArguments) {
3100
+ type = createSpecializedClassType(type, /* typeArgs */ undefined, flags, node);
3101
+ }
3102
+ }
3103
+ // Is this a generic type alias that needs to be specialized?
3104
+ if ((flags & 64 /* ExpectingType */) !== 0 &&
3105
+ type.typeAliasInfo &&
3106
+ type.typeAliasInfo.typeParameters &&
3107
+ type.typeAliasInfo.typeParameters.length > 0 &&
3108
+ !type.typeAliasInfo.typeArguments) {
3109
+ let reportMissingTypeArguments = false;
3110
+ const defaultTypeArgs = [];
3111
+ const typeVarContext = new typeVarContext_1.TypeVarContext(type.typeAliasInfo.typeVarScopeId);
3112
+ type.typeAliasInfo.typeParameters.forEach((param) => {
3113
+ if (!param.details.defaultType) {
3114
+ reportMissingTypeArguments = true;
3115
+ }
3116
+ let defaultType;
3117
+ if (param.details.defaultType || param.details.isParamSpec) {
3118
+ defaultType = (0, typeUtils_1.applySolvedTypeVars)(param, typeVarContext, { unknownIfNotFound: true });
3119
+ }
3120
+ else {
3121
+ defaultType = types_1.UnknownType.create();
3115
3122
  }
3116
- type = types_1.TypeBase.cloneForTypeAlias((0, typeUtils_1.applySolvedTypeVars)(type, typeVarContext, /* unknownIfNotFound */ true), type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.typeParameters, defaultTypeArgs);
3123
+ defaultTypeArgs.push(defaultType);
3124
+ typeVarContext.setTypeVarType(param, defaultType);
3125
+ });
3126
+ if (reportMissingTypeArguments) {
3127
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportMissingTypeArgument, diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument, localize_1.Localizer.Diagnostic.typeArgsMissingForAlias().format({
3128
+ name: type.typeAliasInfo.name,
3129
+ }), node);
3117
3130
  }
3131
+ type = types_1.TypeBase.cloneForTypeAlias((0, typeUtils_1.applySolvedTypeVars)(type, typeVarContext, { unknownIfNotFound: true }), type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.typeParameters, defaultTypeArgs);
3118
3132
  }
3119
3133
  return type;
3120
3134
  }
@@ -3148,8 +3162,9 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3148
3162
  return scopeIds;
3149
3163
  }
3150
3164
  // Walks up the parse tree to find a function, class, or type alias
3151
- // assignment that provides the context for a type variable.
3165
+ // declaration that provides the context for a type variable.
3152
3166
  function findScopedTypeVar(node, type) {
3167
+ var _a;
3153
3168
  let curNode = node;
3154
3169
  let nestedClassCount = 0;
3155
3170
  (0, debug_1.assert)(types_1.TypeBase.isInstantiable(type));
@@ -3171,14 +3186,13 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3171
3186
  else if (curNode.nodeType === 28 /* Function */) {
3172
3187
  const functionTypeInfo = getTypeOfFunction(curNode);
3173
3188
  if (functionTypeInfo) {
3174
- typeParametersForScope = [];
3175
- functionTypeInfo.functionType.details.parameters.forEach((param) => {
3176
- if (param.hasDeclaredType) {
3177
- (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParametersForScope, (0, typeUtils_1.getTypeVarArgumentsRecursive)(param.type));
3178
- }
3179
- });
3180
- if (functionTypeInfo.functionType.details.declaredReturnType) {
3181
- (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParametersForScope, (0, typeUtils_1.getTypeVarArgumentsRecursive)(functionTypeInfo.functionType.details.declaredReturnType));
3189
+ const functionDetails = functionTypeInfo.functionType.details;
3190
+ typeParametersForScope = functionDetails.typeParameters;
3191
+ // Was this type parameter "rescoped" to a callable found within the
3192
+ // return type annotation? If so, it is not available for use within
3193
+ // the function body.
3194
+ if ((_a = functionDetails.rescopedTypeParameters) === null || _a === void 0 ? void 0 : _a.some((tp) => tp.details.name === type.details.name)) {
3195
+ return { type, isRescoped: true, foundInterveningClass: false };
3182
3196
  }
3183
3197
  }
3184
3198
  scopeUsesTypeParameterSyntax = !!curNode.typeParameters;
@@ -3191,7 +3205,11 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3191
3205
  if (match === null || match === void 0 ? void 0 : match.scopeId) {
3192
3206
  // Use the scoped version of the TypeVar rather than the (unscoped) original type.
3193
3207
  type = types_1.TypeVarType.cloneForScopeId(type, match.scopeId, match.scopeName, match.scopeType);
3194
- return { type, foundInterveningClass: nestedClassCount > 1 && !scopeUsesTypeParameterSyntax };
3208
+ return {
3209
+ type,
3210
+ isRescoped: false,
3211
+ foundInterveningClass: nestedClassCount > 1 && !scopeUsesTypeParameterSyntax,
3212
+ };
3195
3213
  }
3196
3214
  }
3197
3215
  curNode = curNode.parent;
@@ -3224,6 +3242,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3224
3242
  }
3225
3243
  return {
3226
3244
  type: types_1.TypeVarType.cloneForScopeId(type, leftType.details.recursiveTypeAliasScopeId, leftType.details.recursiveTypeAliasName, 2 /* TypeAlias */),
3245
+ isRescoped: false,
3227
3246
  foundInterveningClass: false,
3228
3247
  };
3229
3248
  }
@@ -3231,7 +3250,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3231
3250
  curNode = curNode.parent;
3232
3251
  }
3233
3252
  // Return the original type.
3234
- return { type, foundInterveningClass: false };
3253
+ return { type, isRescoped: false, foundInterveningClass: false };
3235
3254
  }
3236
3255
  function getTypeOfMemberAccess(node, flags) {
3237
3256
  const baseTypeFlags = 2 /* DoNotSpecialize */ |
@@ -3253,8 +3272,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3253
3272
  const typeResult = getTypeOfMemberAccessWithBaseType(node, baseTypeResult, { method: 'get' }, flags | 2 /* DoNotSpecialize */);
3254
3273
  if ((0, codeFlowTypes_1.isCodeFlowSupportedForReference)(node)) {
3255
3274
  // Before performing code flow analysis, update the cache to prevent recursion.
3256
- writeTypeCache(node, typeResult.type, flags, /* isIncomplete */ true);
3257
- writeTypeCache(node.memberName, typeResult.type, flags, /* isIncomplete */ true);
3275
+ writeTypeCache(node, { ...typeResult, isIncomplete: true }, flags);
3276
+ writeTypeCache(node.memberName, { ...typeResult, isIncomplete: true }, flags);
3258
3277
  // If the type is initially unbound, see if there's a parent class that
3259
3278
  // potentially initialized the value.
3260
3279
  let typeAtStart = typeResult.type;
@@ -3294,7 +3313,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3294
3313
  typeResult.isIncomplete = true;
3295
3314
  }
3296
3315
  // Cache the type information in the member name node.
3297
- writeTypeCache(node.memberName, typeResult.type, flags, !!typeResult.isIncomplete);
3316
+ writeTypeCache(node.memberName, typeResult, flags);
3298
3317
  return typeResult;
3299
3318
  }
3300
3319
  function getTypeOfMemberAccessWithBaseType(node, baseTypeResult, usage, flags) {
@@ -3667,7 +3686,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
3667
3686
  }
3668
3687
  }
3669
3688
  // Don't include variables within typed dict classes.
3670
- if (types_1.ClassType.isTypedDictClass(classType)) {
3689
+ if ((0, types_1.isClass)(memberInfo.classType) && types_1.ClassType.isTypedDictClass(memberInfo.classType)) {
3671
3690
  const typedDecls = memberInfo.symbol.getTypedDeclarations();
3672
3691
  if (typedDecls.length > 0 && typedDecls[0].type === 1 /* Variable */) {
3673
3692
  diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.Localizer.DiagnosticAddendum.memberUnknown().format({ name: memberName }));
@@ -4173,7 +4192,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4173
4192
  });
4174
4193
  if (baseTypeSupportsIndexNarrowing) {
4175
4194
  // Before performing code flow analysis, update the cache to prevent recursion.
4176
- writeTypeCache(node, indexTypeResult.type, flags, /* isIncomplete */ false);
4195
+ writeTypeCache(node, indexTypeResult, flags);
4177
4196
  // See if we can refine the type based on code flow analysis.
4178
4197
  const codeFlowTypeResult = getFlowTypeOfReference(node, symbol_1.indeterminateSymbolId, indexTypeResult.type,
4179
4198
  /* startNode */ undefined, {
@@ -4205,12 +4224,12 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4205
4224
  }
4206
4225
  return indexTypeResult;
4207
4226
  }
4208
- function adjustTypeArgumentsForVariadicTypeVar(typeArgs, typeParameters, errorNode) {
4209
- var _a;
4227
+ function adjustTypeArgumentsForVariadicTypeVar(typeArgs, typeParameters, typeVarScopeId, errorNode) {
4210
4228
  const variadicIndex = typeParameters.findIndex((param) => (0, types_1.isVariadicTypeVar)(param));
4211
4229
  // Do we need to adjust the type arguments to map to a variadic type
4212
4230
  // param at the end of the list?
4213
4231
  if (variadicIndex >= 0) {
4232
+ const variadicTypeVar = typeParameters[variadicIndex];
4214
4233
  if (tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
4215
4234
  if (variadicIndex < typeArgs.length) {
4216
4235
  const variadicTypeResults = typeArgs.slice(variadicIndex, variadicIndex + 1 + typeArgs.length - typeParameters.length);
@@ -4250,11 +4269,11 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4250
4269
  ];
4251
4270
  }
4252
4271
  }
4253
- else {
4272
+ else if (!variadicTypeVar.details.defaultType) {
4254
4273
  // Add an empty tuple that maps to the TypeVarTuple type parameter.
4255
4274
  typeArgs.push({
4256
4275
  node: errorNode,
4257
- type: (_a = typeParameters[variadicIndex].details.defaultType) !== null && _a !== void 0 ? _a : (0, typeUtils_1.convertToInstance)((0, typeUtils_1.specializeTupleClass)(tupleClassType, [],
4276
+ type: (0, typeUtils_1.convertToInstance)((0, typeUtils_1.specializeTupleClass)(tupleClassType, [],
4258
4277
  /* isTypeArgumentExplicit */ true,
4259
4278
  /* isUnpackedTuple */ true)),
4260
4279
  });
@@ -4291,7 +4310,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4291
4310
  return undefined;
4292
4311
  }
4293
4312
  const typeParameters = baseType.typeAliasInfo.typeParameters;
4294
- let typeArgs = adjustTypeArgumentsForVariadicTypeVar(getTypeArgs(node, flags), typeParameters, node);
4313
+ let typeArgs = adjustTypeArgumentsForVariadicTypeVar(getTypeArgs(node, flags), typeParameters, baseType.typeAliasInfo.typeVarScopeId, node);
4295
4314
  // PEP 612 says that if the class has only one type parameter consisting
4296
4315
  // of a ParamSpec, the list of arguments does not need to be enclosed in
4297
4316
  // a list. We'll handle that case specially here. Presumably this applies to
@@ -4324,7 +4343,6 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4324
4343
  const typeVarContext = new typeVarContext_1.TypeVarContext(baseType.typeAliasInfo.typeVarScopeId);
4325
4344
  const diag = new diagnostic_1.DiagnosticAddendum();
4326
4345
  typeParameters.forEach((param, index) => {
4327
- var _a;
4328
4346
  if (param.details.isParamSpec && index < typeArgs.length) {
4329
4347
  const typeArgType = typeArgs[index].type;
4330
4348
  if (typeArgs[index].typeList) {
@@ -4387,9 +4405,16 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4387
4405
  if (index < typeArgs.length && typeArgs[index].typeList) {
4388
4406
  addError(localize_1.Localizer.Diagnostic.typeArgListNotAllowed(), typeArgs[index].node);
4389
4407
  }
4390
- const typeArgType = index < typeArgs.length
4391
- ? (0, typeUtils_1.convertToInstance)(typeArgs[index].type)
4392
- : (_a = param.details.defaultType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
4408
+ let typeArgType;
4409
+ if (index < typeArgs.length) {
4410
+ typeArgType = (0, typeUtils_1.convertToInstance)(typeArgs[index].type);
4411
+ }
4412
+ else if (param.details.defaultType) {
4413
+ typeArgType = (0, typeUtils_1.applySolvedTypeVars)(param, typeVarContext, { unknownIfNotFound: true });
4414
+ }
4415
+ else {
4416
+ typeArgType = types_1.UnknownType.create();
4417
+ }
4393
4418
  (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, param, typeArgType, diag, typeVarContext, 128 /* RetainLiteralsForTypeVar */);
4394
4419
  }
4395
4420
  });
@@ -4400,8 +4425,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4400
4425
  (_b = baseType.typeAliasInfo.typeParameters) === null || _b === void 0 ? void 0 : _b.forEach((typeParam) => {
4401
4426
  let typeVarType;
4402
4427
  if ((0, types_1.isParamSpec)(typeParam)) {
4403
- const paramSpecValue = typeVarContext.getParamSpec(typeParam);
4404
- typeVarType = paramSpecValue ? (0, typeUtils_1.convertParamSpecValueToType)(paramSpecValue) : types_1.UnknownType.create();
4428
+ const paramSpecType = typeVarContext.getParamSpecType(typeParam);
4429
+ typeVarType = paramSpecType ? (0, typeUtils_1.convertParamSpecValueToType)(paramSpecType) : types_1.UnknownType.create();
4405
4430
  }
4406
4431
  else {
4407
4432
  typeVarType = typeVarContext.getTypeVarType(typeParam);
@@ -4425,7 +4450,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4425
4450
  let isIncomplete = baseTypeResult.isIncomplete;
4426
4451
  const type = mapSubtypesExpandTypeVars(baseTypeResult.type,
4427
4452
  /* conditionFilter */ undefined, (concreteSubtype, unexpandedSubtype) => {
4428
- var _a;
4453
+ var _a, _b;
4429
4454
  if ((0, types_1.isAnyOrUnknown)(concreteSubtype)) {
4430
4455
  return concreteSubtype;
4431
4456
  }
@@ -4492,7 +4517,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4492
4517
  const isClassVarAnnotation = (0, types_1.isInstantiableClass)(concreteSubtype) && types_1.ClassType.isBuiltIn(concreteSubtype, 'ClassVar');
4493
4518
  let typeArgs = getTypeArgs(node, flags, isAnnotatedClass, hasCustomClassGetItem || !isGenericClass, isFinalAnnotation, isClassVarAnnotation);
4494
4519
  if (!isAnnotatedClass) {
4495
- typeArgs = adjustTypeArgumentsForVariadicTypeVar(typeArgs, concreteSubtype.details.typeParameters, node);
4520
+ typeArgs = adjustTypeArgumentsForVariadicTypeVar(typeArgs, concreteSubtype.details.typeParameters, (_b = (0, typeUtils_1.getTypeVarScopeId)(concreteSubtype)) !== null && _b !== void 0 ? _b : '', node);
4496
4521
  }
4497
4522
  // If this is a custom __class_getitem__, there's no need to specialize the class.
4498
4523
  // Just return it as is.
@@ -4950,6 +4975,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4950
4975
  }
4951
4976
  const entryTypeResults = node.expressions.map((expr, index) => getTypeOfExpression(expr,
4952
4977
  /* flags */ undefined, index < expectedTypes.length ? expectedTypes[index] : undefined));
4978
+ const isIncomplete = entryTypeResults.some((result) => result.isIncomplete);
4953
4979
  const type = (0, typeUtils_1.convertToInstance)((0, typeUtils_1.specializeTupleClass)(tupleClassType, buildTupleTypesList(entryTypeResults),
4954
4980
  /* isTypeArgumentExplicit */ true));
4955
4981
  // Copy any expected type diag addenda for precision error reporting.
@@ -4962,7 +4988,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
4962
4988
  }
4963
4989
  });
4964
4990
  }
4965
- return { type, expectedTypeDiagAddendum };
4991
+ return { type, expectedTypeDiagAddendum, isIncomplete };
4966
4992
  }
4967
4993
  function getTypeOfTupleInferred(node) {
4968
4994
  const entryTypeResults = node.expressions.map((expr) => getTypeOfExpression(expr));
@@ -5478,7 +5504,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
5478
5504
  isTypeIncomplete = true;
5479
5505
  }
5480
5506
  return {
5481
- argumentErrors: false,
5507
+ argumentErrors: finalCallResult.argumentErrors,
5482
5508
  isArgumentAnyOrUnknown: finalCallResult.isArgumentAnyOrUnknown,
5483
5509
  returnType: (0, types_1.combineTypes)(returnTypes),
5484
5510
  isTypeIncomplete,
@@ -5622,7 +5648,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
5622
5648
  // Replace the result with an unknown type since we don't know
5623
5649
  // what overload should have been used.
5624
5650
  result.returnType = types_1.UnknownType.create();
5625
- return result;
5651
+ return { ...result, argumentErrors: true };
5626
5652
  }
5627
5653
  return { argumentErrors: true, isTypeIncomplete: false };
5628
5654
  }
@@ -5900,10 +5926,10 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
5900
5926
  useSpeculativeMode(errorNode, () => {
5901
5927
  callResult = validateCallArguments(errorNode, argList, { type: constructorMethodType }, typeVarContext.clone(), skipUnknownArgCheck);
5902
5928
  });
5903
- if (!(callResult === null || callResult === void 0 ? void 0 : callResult.argumentErrors)) {
5929
+ if (!callResult.argumentErrors) {
5904
5930
  // Call validateCallArguments again, this time without speculative
5905
5931
  // mode, so any errors are reported.
5906
- const callResult = validateCallArguments(errorNode, argList, { type: constructorMethodType }, typeVarContext, skipUnknownArgCheck);
5932
+ callResult = validateCallArguments(errorNode, argList, { type: constructorMethodType }, typeVarContext, skipUnknownArgCheck);
5907
5933
  if (callResult.isTypeIncomplete) {
5908
5934
  isTypeIncomplete = true;
5909
5935
  }
@@ -5949,7 +5975,9 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
5949
5975
  unsolvedTypeVarsAreUnknown = false;
5950
5976
  }
5951
5977
  }
5952
- const specializedType = (0, typeUtils_1.applySolvedTypeVars)(type, typeVarContext, unsolvedTypeVarsAreUnknown);
5978
+ const specializedType = (0, typeUtils_1.applySolvedTypeVars)(type, typeVarContext, {
5979
+ unknownIfNotFound: unsolvedTypeVarsAreUnknown,
5980
+ });
5953
5981
  return types_1.ClassType.cloneAsInstance(specializedType);
5954
5982
  }
5955
5983
  // Similar to applyExpectedTypeForConstructor, this function handles the
@@ -7334,15 +7362,18 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
7334
7362
  // the call below to adjustCallableReturnType will "detach" these
7335
7363
  // TypeVars from the scope of this function and "attach" them to
7336
7364
  // the scope of the callable.
7337
- let unknownIfUnsolved = !(0, types_1.isFunction)(returnType);
7365
+ let unknownIfNotFound = !(0, types_1.isFunction)(returnType);
7338
7366
  // We'll also leave TypeVars unsolved if the call is a recursive
7339
7367
  // call to a generic function.
7340
7368
  const typeVarScopes = getTypeVarScopesForNode(errorNode);
7341
7369
  if (typeVarScopes.some((typeVarScope) => typeVarContext.hasSolveForScope(typeVarScope))) {
7342
- unknownIfUnsolved = false;
7370
+ unknownIfNotFound = false;
7343
7371
  }
7344
- let specializedReturnType = (0, typeUtils_1.addConditionToType)((0, typeUtils_1.applySolvedTypeVars)(returnType, typeVarContext, unknownIfUnsolved,
7345
- /* useNarrowBoundOnly */ false, eliminateUnsolvedInUnions), typeCondition);
7372
+ let specializedReturnType = (0, typeUtils_1.addConditionToType)((0, typeUtils_1.applySolvedTypeVars)(returnType, typeVarContext, {
7373
+ unknownIfNotFound,
7374
+ useUnknownOverDefault: skipUnknownArgCheck,
7375
+ eliminateUnsolvedInUnions,
7376
+ }), typeCondition);
7346
7377
  // If the final return type is an unpacked tuple, turn it into a normal (unpacked) tuple.
7347
7378
  if ((0, types_1.isUnpackedClass)(specializedReturnType)) {
7348
7379
  specializedReturnType = types_1.ClassType.cloneForUnpacked(specializedReturnType, /* isUnpackedTuple */ false);
@@ -7409,16 +7440,16 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
7409
7440
  // signature bound to the specified ParamSpec. Return value indicates success.
7410
7441
  function validateFunctionArgumentsForParamSpec(errorNode, argList, paramSpec, destTypeVarContext, conditionFilter) {
7411
7442
  var _a;
7412
- const paramSpecValue = destTypeVarContext.getParamSpec(paramSpec);
7413
- const srcTypeVarContext = new typeVarContext_1.TypeVarContext(paramSpecValue === null || paramSpecValue === void 0 ? void 0 : paramSpecValue.typeVarScopeId);
7414
- if (!paramSpecValue) {
7443
+ const paramSpecType = destTypeVarContext.getParamSpecType(paramSpec);
7444
+ if (!paramSpecType) {
7415
7445
  addDiagnostic(AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.paramSpecNotBound().format({ type: printType(paramSpec) }), ((_a = argList[0]) === null || _a === void 0 ? void 0 : _a.valueExpression) || errorNode);
7416
7446
  return false;
7417
7447
  }
7448
+ const srcTypeVarContext = new typeVarContext_1.TypeVarContext(paramSpecType.details.typeVarScopeId);
7418
7449
  let reportedArgError = false;
7419
7450
  // Build a map of all named parameters.
7420
7451
  const paramMap = new Map();
7421
- const paramSpecParams = paramSpecValue.parameters;
7452
+ const paramSpecParams = paramSpecType.details.parameters;
7422
7453
  paramSpecParams.forEach((param) => {
7423
7454
  if (param.name) {
7424
7455
  paramMap.set(param.name, param);
@@ -7499,7 +7530,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
7499
7530
  const paramInfo = paramMap.get(name);
7500
7531
  return paramInfo.category === 0 /* Simple */ && !paramInfo.hasDefault;
7501
7532
  });
7502
- if (unassignedParams.length > 0 && !paramSpecValue.paramSpec) {
7533
+ if (unassignedParams.length > 0 && !paramSpecType.details.paramSpec) {
7503
7534
  const missingParamNames = unassignedParams.map((p) => `"${p}"`).join(', ');
7504
7535
  addDiagnostic(AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, unassignedParams.length === 1
7505
7536
  ? localize_1.Localizer.Diagnostic.argMissingForParam().format({ name: missingParamNames })
@@ -7531,8 +7562,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
7531
7562
  functionType !== undefined &&
7532
7563
  argParam.paramType.scopeId === functionType.details.typeVarScopeId
7533
7564
  ? undefined
7534
- : (0, typeUtils_1.applySolvedTypeVars)(argParam.paramType, typeVarContext,
7535
- /* unknownIfNotFound */ false, useNarrowBoundOnly);
7565
+ : (0, typeUtils_1.applySolvedTypeVars)(argParam.paramType, typeVarContext, { useNarrowBoundOnly });
7536
7566
  // If the expected type is unknown, don't use an expected type. Instead,
7537
7567
  // use default rules for evaluating the expression type.
7538
7568
  if (expectedType && (0, types_1.isUnknown)(expectedType)) {
@@ -7561,7 +7591,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
7561
7591
  if (argParam.argument &&
7562
7592
  argParam.argument.name &&
7563
7593
  !speculativeTypeTracker.isSpeculative(argParam.errorNode)) {
7564
- writeTypeCache(argParam.argument.name, expectedType || argType, 0 /* None */, isTypeIncomplete);
7594
+ writeTypeCache(argParam.argument.name, { type: expectedType || argType, isIncomplete: isTypeIncomplete }, 0 /* None */);
7565
7595
  }
7566
7596
  }
7567
7597
  else {
@@ -7851,8 +7881,9 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
7851
7881
  // or constraint.
7852
7882
  if (typeVar.details.defaultType && defaultValueNode) {
7853
7883
  const typeVarContext = new typeVarContext_1.TypeVarContext(types_1.WildcardTypeVarScopeId);
7854
- const concreteDefaultType = (0, typeUtils_1.applySolvedTypeVars)(typeVar.details.defaultType, typeVarContext,
7855
- /* unknownIfNotFound */ true);
7884
+ const concreteDefaultType = makeTopLevelTypeVarsConcrete((0, typeUtils_1.applySolvedTypeVars)(typeVar.details.defaultType, typeVarContext, {
7885
+ unknownIfNotFound: true,
7886
+ }));
7856
7887
  if (typeVar.details.boundType) {
7857
7888
  if (!assignType(typeVar.details.boundType, concreteDefaultType)) {
7858
7889
  addDiagnostic(AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeVarDefaultBoundMismatch(), defaultValueNode);
@@ -7966,7 +7997,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
7966
7997
  });
7967
7998
  // Update the type cache so we don't attempt to re-evaluate this node.
7968
7999
  // The type doesn't matter, so use Any.
7969
- writeTypeCache(node, types_1.AnyType.create(), /* flags */ undefined, /* isIncomplete */ false);
8000
+ writeTypeCache(node, { type: types_1.AnyType.create() }, /* flags */ undefined);
7970
8001
  return functionType;
7971
8002
  }
7972
8003
  else {
@@ -8011,62 +8042,67 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
8011
8042
  // in the Python specification: The static type checker will treat
8012
8043
  // the new type as if it were a subclass of the original type.
8013
8044
  function createNewType(errorNode, argList) {
8045
+ var _a;
8014
8046
  const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
8015
- let className = '_';
8016
- if (argList.length >= 1) {
8017
- const nameArg = argList[0];
8018
- if (nameArg.argumentCategory === 0 /* Simple */) {
8019
- if (nameArg.valueExpression && nameArg.valueExpression.nodeType === 48 /* StringList */) {
8020
- className = nameArg.valueExpression.strings.map((s) => s.value).join('');
8021
- }
8022
- }
8023
- }
8024
- if (argList.length >= 2) {
8025
- const baseClass = getTypeOfArgumentExpectingType(argList[1]).type;
8026
- if ((0, types_1.isInstantiableClass)(baseClass)) {
8027
- if (types_1.ClassType.isProtocolClass(baseClass)) {
8028
- addError(localize_1.Localizer.Diagnostic.newTypeProtocolClass(), argList[1].node || errorNode);
8029
- }
8030
- else if (baseClass.literalValue !== undefined) {
8031
- addError(localize_1.Localizer.Diagnostic.newTypeLiteral(), argList[1].node || errorNode);
8032
- }
8033
- const classFlags = baseClass.details.flags & ~(1 /* BuiltInClass */ | 2 /* SpecialBuiltIn */);
8034
- const classType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.filePath, classFlags, ParseTreeUtils.getTypeSourceId(errorNode),
8035
- /* declaredMetaclass */ undefined, baseClass.details.effectiveMetaclass);
8036
- classType.details.baseClasses.push(baseClass);
8037
- (0, typeUtils_1.computeMroLinearization)(classType);
8038
- // Synthesize an __init__ method that accepts only the specified type.
8039
- const initType = types_1.FunctionType.createSynthesizedInstance('__init__');
8040
- types_1.FunctionType.addParameter(initType, {
8041
- category: 0 /* Simple */,
8042
- name: 'self',
8043
- type: types_1.ClassType.cloneAsInstance(classType),
8044
- hasDeclaredType: true,
8045
- });
8046
- types_1.FunctionType.addParameter(initType, {
8047
- category: 0 /* Simple */,
8048
- name: '_x',
8049
- type: types_1.ClassType.cloneAsInstance(baseClass),
8050
- hasDeclaredType: true,
8051
- });
8052
- initType.details.declaredReturnType = types_1.NoneType.createInstance();
8053
- classType.details.fields.set('__init__', symbol_1.Symbol.createWithType(4 /* ClassMember */, initType));
8054
- // Synthesize a trivial __new__ method.
8055
- const newType = types_1.FunctionType.createSynthesizedInstance('__new__', 1 /* ConstructorMethod */);
8056
- types_1.FunctionType.addParameter(newType, {
8057
- category: 0 /* Simple */,
8058
- name: 'cls',
8059
- type: classType,
8060
- hasDeclaredType: true,
8061
- });
8062
- types_1.FunctionType.addDefaultParameters(newType);
8063
- newType.details.declaredReturnType = types_1.ClassType.cloneAsInstance(classType);
8064
- classType.details.fields.set('__new__', symbol_1.Symbol.createWithType(4 /* ClassMember */, newType));
8065
- return classType;
8066
- }
8067
- else if (!(0, types_1.isAnyOrUnknown)(baseClass)) {
8068
- addError(localize_1.Localizer.Diagnostic.newTypeNotAClass(), argList[1].node || errorNode);
8069
- }
8047
+ let className = '';
8048
+ if (argList.length !== 2) {
8049
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.newTypeParamCount(), errorNode);
8050
+ return undefined;
8051
+ }
8052
+ const nameArg = argList[0];
8053
+ if (nameArg.argumentCategory === 0 /* Simple */ &&
8054
+ nameArg.valueExpression &&
8055
+ nameArg.valueExpression.nodeType === 48 /* StringList */) {
8056
+ className = nameArg.valueExpression.strings.map((s) => s.value).join('');
8057
+ }
8058
+ if (!className) {
8059
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.newTypeBadName(), (_a = argList[0].node) !== null && _a !== void 0 ? _a : errorNode);
8060
+ return undefined;
8061
+ }
8062
+ const baseClass = getTypeOfArgumentExpectingType(argList[1]).type;
8063
+ if ((0, types_1.isInstantiableClass)(baseClass)) {
8064
+ if (types_1.ClassType.isProtocolClass(baseClass)) {
8065
+ addError(localize_1.Localizer.Diagnostic.newTypeProtocolClass(), argList[1].node || errorNode);
8066
+ }
8067
+ else if (baseClass.literalValue !== undefined) {
8068
+ addError(localize_1.Localizer.Diagnostic.newTypeLiteral(), argList[1].node || errorNode);
8069
+ }
8070
+ const classFlags = baseClass.details.flags & ~(1 /* BuiltInClass */ | 2 /* SpecialBuiltIn */);
8071
+ const classType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.filePath, classFlags, ParseTreeUtils.getTypeSourceId(errorNode),
8072
+ /* declaredMetaclass */ undefined, baseClass.details.effectiveMetaclass);
8073
+ classType.details.baseClasses.push(baseClass);
8074
+ (0, typeUtils_1.computeMroLinearization)(classType);
8075
+ // Synthesize an __init__ method that accepts only the specified type.
8076
+ const initType = types_1.FunctionType.createSynthesizedInstance('__init__');
8077
+ types_1.FunctionType.addParameter(initType, {
8078
+ category: 0 /* Simple */,
8079
+ name: 'self',
8080
+ type: types_1.ClassType.cloneAsInstance(classType),
8081
+ hasDeclaredType: true,
8082
+ });
8083
+ types_1.FunctionType.addParameter(initType, {
8084
+ category: 0 /* Simple */,
8085
+ name: '_x',
8086
+ type: types_1.ClassType.cloneAsInstance(baseClass),
8087
+ hasDeclaredType: true,
8088
+ });
8089
+ initType.details.declaredReturnType = types_1.NoneType.createInstance();
8090
+ classType.details.fields.set('__init__', symbol_1.Symbol.createWithType(4 /* ClassMember */, initType));
8091
+ // Synthesize a trivial __new__ method.
8092
+ const newType = types_1.FunctionType.createSynthesizedInstance('__new__', 1 /* ConstructorMethod */);
8093
+ types_1.FunctionType.addParameter(newType, {
8094
+ category: 0 /* Simple */,
8095
+ name: 'cls',
8096
+ type: classType,
8097
+ hasDeclaredType: true,
8098
+ });
8099
+ types_1.FunctionType.addDefaultParameters(newType);
8100
+ newType.details.declaredReturnType = types_1.ClassType.cloneAsInstance(classType);
8101
+ classType.details.fields.set('__new__', symbol_1.Symbol.createWithType(4 /* ClassMember */, newType));
8102
+ return classType;
8103
+ }
8104
+ if (!(0, types_1.isAnyOrUnknown)(baseClass)) {
8105
+ addError(localize_1.Localizer.Diagnostic.newTypeNotAClass(), argList[1].node || errorNode);
8070
8106
  }
8071
8107
  return undefined;
8072
8108
  }
@@ -8261,7 +8297,9 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
8261
8297
  else if (node.operator === 6 /* BitwiseOr */) {
8262
8298
  // If this is a bitwise or ("|"), use the type of the left operand. This allows
8263
8299
  // us to support the case where a TypedDict is being updated with a dict expression.
8264
- expectedOperandType = leftType;
8300
+ if ((0, types_1.isClassInstance)(leftType) && types_1.ClassType.isTypedDictClass(leftType)) {
8301
+ expectedOperandType = leftType;
8302
+ }
8265
8303
  }
8266
8304
  }
8267
8305
  const rightTypeResult = getTypeOfExpression(rightExpression, flags, expectedOperandType);
@@ -9395,7 +9433,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
9395
9433
  functionType.details.typeVarScopeId = getScopeIdForNode(node);
9396
9434
  // Pre-cache the incomplete function type in case the evaluation of the
9397
9435
  // lambda depends on itself.
9398
- writeTypeCache(node, functionType, 0 /* None */, /* isIncomplete */ true);
9436
+ writeTypeCache(node, { type: functionType, isIncomplete: true }, 0 /* None */);
9399
9437
  let expectedFunctionTypes = [];
9400
9438
  if (expectedType) {
9401
9439
  (0, typeUtils_1.mapSubtypes)(expectedType, (subtype) => {
@@ -9432,8 +9470,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
9432
9470
  paramType = types_1.FunctionType.getEffectiveParameterType(expectedFunctionType, index);
9433
9471
  }
9434
9472
  if (param.name) {
9435
- writeTypeCache(param.name, transformVariadicParamType(node, param.category, paramType), 0 /* None */,
9436
- /* isIncomplete */ false);
9473
+ writeTypeCache(param.name, { type: transformVariadicParamType(node, param.category, paramType) }, 0 /* None */);
9437
9474
  }
9438
9475
  if (param.defaultValue) {
9439
9476
  // Evaluate the default value if it's present.
@@ -9498,8 +9535,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
9498
9535
  if (speculativeTypeTracker.isSpeculative(node)) {
9499
9536
  useSpeculativeMode(node.expression, () => {
9500
9537
  inferLambdaReturnType();
9501
- },
9502
- /* allowCacheRetention */ false);
9538
+ });
9503
9539
  }
9504
9540
  else {
9505
9541
  inferLambdaReturnType();
@@ -10371,7 +10407,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10371
10407
  }
10372
10408
  return createSpecialType(classType, typeArgs, /* paramLimit */ undefined, /* allowParamSpec */ true);
10373
10409
  }
10374
- function transformTypeForTypeAlias(type, name, errorNode, typeParameters) {
10410
+ function transformTypeForTypeAlias(type, name, errorNode, typeParameters, typeParamNodes) {
10375
10411
  if (!types_1.TypeBase.isInstantiable(type)) {
10376
10412
  return type;
10377
10413
  }
@@ -10400,6 +10436,15 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10400
10436
  }
10401
10437
  return (0, typeUtils_1.convertToInstance)(typeVar);
10402
10438
  });
10439
+ // Validate the default types for all type parameters.
10440
+ typeParameters.forEach((typeParam, index) => {
10441
+ var _a;
10442
+ let bestErrorNode = errorNode;
10443
+ if (typeParamNodes && index < typeParamNodes.length) {
10444
+ bestErrorNode = (_a = typeParamNodes[index].defaultExpression) !== null && _a !== void 0 ? _a : typeParamNodes[index].name;
10445
+ }
10446
+ validateTypeParameterDefault(bestErrorNode, typeParam, typeParameters.slice(0, index));
10447
+ });
10403
10448
  // Verify that we have at most one variadic type variable.
10404
10449
  const variadics = typeParameters.filter((param) => (0, types_1.isVariadicTypeVar)(param));
10405
10450
  if (variadics.length > 1) {
@@ -10514,7 +10559,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10514
10559
  specialType.details.baseClasses.push(strClassType !== null && strClassType !== void 0 ? strClassType : types_1.AnyType.create());
10515
10560
  (0, typeUtils_1.computeMroLinearization)(specialType);
10516
10561
  }
10517
- writeTypeCache(node, specialType, 0 /* None */, /* isIncomplete */ false);
10562
+ writeTypeCache(node, { type: specialType }, 0 /* None */);
10518
10563
  return specialType;
10519
10564
  }
10520
10565
  return undefined;
@@ -10594,7 +10639,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10594
10639
  if (fileInfo.isTypingStubFile || fileInfo.isTypingExtensionsStubFile) {
10595
10640
  rightHandType = handleTypingStubAssignment(node);
10596
10641
  if (rightHandType) {
10597
- writeTypeCache(node.rightExpression, rightHandType, 0 /* None */, /* isIncomplete */ false);
10642
+ writeTypeCache(node.rightExpression, { type: rightHandType }, 0 /* None */);
10598
10643
  }
10599
10644
  }
10600
10645
  if (!rightHandType) {
@@ -10632,14 +10677,11 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10632
10677
  typeAliasTypeVar.details.recursiveTypeAliasScopeId = scopeId;
10633
10678
  typeAliasTypeVar.scopeId = scopeId;
10634
10679
  // Write the type back to the type cache. It will be replaced below.
10635
- writeTypeCache(node, typeAliasTypeVar, /* flags */ undefined, /* isIncomplete */ false);
10636
- writeTypeCache(node.leftExpression, typeAliasTypeVar,
10637
- /* flags */ undefined,
10638
- /* isIncomplete */ false);
10680
+ writeTypeCache(node, { type: typeAliasTypeVar }, /* flags */ undefined);
10681
+ writeTypeCache(node.leftExpression, { type: typeAliasTypeVar }, /* flags */ undefined);
10639
10682
  if (node.leftExpression.nodeType === 54 /* TypeAnnotation */) {
10640
- writeTypeCache(node.leftExpression.valueExpression, typeAliasTypeVar,
10641
- /* flags */ undefined,
10642
- /* isIncomplete */ false);
10683
+ writeTypeCache(node.leftExpression.valueExpression, { type: typeAliasTypeVar },
10684
+ /* flags */ undefined);
10643
10685
  }
10644
10686
  }
10645
10687
  const srcTypeResult = getTypeOfExpression(node.rightExpression, flags, declaredType);
@@ -10708,7 +10750,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10708
10750
  assignTypeToExpression(node.leftExpression, rightHandType, isIncomplete, node.rightExpression,
10709
10751
  /* ignoreEmptyContainers */ true,
10710
10752
  /* allowAssignmentToFinalVar */ true, expectedTypeDiagAddendum);
10711
- writeTypeCache(node, rightHandType, 0 /* None */, isIncomplete);
10753
+ writeTypeCache(node, { type: rightHandType, isIncomplete }, 0 /* None */);
10712
10754
  }
10713
10755
  function isPossibleTypeAliasOrTypedDict(decl) {
10714
10756
  var _a;
@@ -10741,6 +10783,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10741
10783
  // path does not handle traditional type aliases, which are treated as
10742
10784
  // variables since they use normal variable assignment syntax.
10743
10785
  function getTypeOfTypeAlias(node) {
10786
+ var _a;
10744
10787
  const cachedType = readTypeCache(node.name, 0 /* None */);
10745
10788
  if (cachedType) {
10746
10789
  return cachedType;
@@ -10754,7 +10797,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10754
10797
  typeAliasTypeVar.details.recursiveTypeAliasScopeId = scopeId;
10755
10798
  typeAliasTypeVar.scopeId = scopeId;
10756
10799
  // Write the type to the type cache. It will be replaced below.
10757
- writeTypeCache(node.name, typeAliasTypeVar, /* flags */ undefined, /* isIncomplete */ false);
10800
+ writeTypeCache(node.name, { type: typeAliasTypeVar }, /* flags */ undefined);
10758
10801
  // Set a partial type to handle recursive (self-referential) type aliases.
10759
10802
  const scope = ScopeUtils.getScopeForNode(node);
10760
10803
  const typeAliasSymbol = scope === null || scope === void 0 ? void 0 : scope.lookUpSymbolRecursive(node.name.value);
@@ -10778,7 +10821,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10778
10821
  }
10779
10822
  // Clear the temporary type we wrote above.
10780
10823
  deleteTypeCacheEntry(node.name);
10781
- aliasType = transformTypeForTypeAlias(aliasType, node.name, node.expression, typeParameters);
10824
+ aliasType = transformTypeForTypeAlias(aliasType, node.name, node.expression, typeParameters, (_a = node.typeParameters) === null || _a === void 0 ? void 0 : _a.parameters);
10782
10825
  if ((0, typeUtils_1.isTypeAliasRecursive)(typeAliasTypeVar, aliasType)) {
10783
10826
  addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeAliasIsRecursiveDirect().format({
10784
10827
  name: node.name.value,
@@ -10793,7 +10836,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10793
10836
  name: node.name.value,
10794
10837
  }), node.name);
10795
10838
  }
10796
- writeTypeCache(node.name, aliasType, 0 /* None */, isIncomplete);
10839
+ writeTypeCache(node.name, { type: aliasType, isIncomplete }, 0 /* None */);
10797
10840
  return aliasType;
10798
10841
  }
10799
10842
  function evaluateTypesForAugmentedAssignment(node) {
@@ -10801,7 +10844,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10801
10844
  return;
10802
10845
  }
10803
10846
  const destTypeResult = getTypeOfAugmentedAssignment(node, /* expectedType */ undefined);
10804
- writeTypeCache(node, destTypeResult.type, 0 /* None */, !!destTypeResult.isIncomplete);
10847
+ writeTypeCache(node, destTypeResult, 0 /* None */);
10805
10848
  }
10806
10849
  function getPseudoGenericTypeVarName(paramName) {
10807
10850
  return `__type_of_${paramName}`;
@@ -10860,8 +10903,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
10860
10903
  setSymbolResolutionPartialType(classSymbol, classDecl, classType);
10861
10904
  }
10862
10905
  classType.details.flags |= 131072 /* PartiallyEvaluated */;
10863
- writeTypeCache(node, classType, /* flags */ undefined, /* isIncomplete */ false);
10864
- writeTypeCache(node.name, classType, /* flags */ undefined, /* isIncomplete */ false);
10906
+ writeTypeCache(node, { type: classType }, /* flags */ undefined);
10907
+ writeTypeCache(node.name, { type: classType }, /* flags */ undefined);
10865
10908
  // Keep a list of unique type parameters that are used in the
10866
10909
  // base class arguments.
10867
10910
  let typeParameters = [];
@@ -11096,6 +11139,16 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11096
11139
  names: variadics.map((v) => `"${v.details.name}"`).join(', '),
11097
11140
  }), node.name, textRange_1.TextRange.combine(node.arguments) || node.name);
11098
11141
  }
11142
+ // Validate the default types for all type parameters.
11143
+ classType.details.typeParameters.forEach((typeParam, index) => {
11144
+ var _a;
11145
+ let bestErrorNode = node.name;
11146
+ if (node.typeParameters && index < node.typeParameters.parameters.length) {
11147
+ const typeParamNode = node.typeParameters.parameters[index];
11148
+ bestErrorNode = (_a = typeParamNode.defaultExpression) !== null && _a !== void 0 ? _a : typeParamNode.name;
11149
+ }
11150
+ validateTypeParameterDefault(bestErrorNode, typeParam, classType.details.typeParameters.slice(0, index));
11151
+ });
11099
11152
  if (!(0, typeUtils_1.computeMroLinearization)(classType)) {
11100
11153
  addError(localize_1.Localizer.Diagnostic.methodOrdering(), node.name);
11101
11154
  }
@@ -11274,9 +11327,9 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11274
11327
  }
11275
11328
  }
11276
11329
  // Update the undecorated class type.
11277
- writeTypeCache(node.name, classType, 0 /* None */, /* isIncomplete */ false);
11330
+ writeTypeCache(node.name, { type: classType }, 0 /* None */);
11278
11331
  // Update the decorated class type.
11279
- writeTypeCache(node, decoratedType, 0 /* None */, /* isIncomplete */ false);
11332
+ writeTypeCache(node, { type: decoratedType }, 0 /* None */);
11280
11333
  // Stash away a reference to the UnionType class if we encounter it.
11281
11334
  // There's no easy way to otherwise reference it.
11282
11335
  if (types_1.ClassType.isBuiltIn(classType, 'UnionType')) {
@@ -11284,6 +11337,36 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11284
11337
  }
11285
11338
  return { classType, decoratedType };
11286
11339
  }
11340
+ // Determines whether the type parameters has a default that refers to another
11341
+ // type parameter. If so, validates that it is in the list of "live" type
11342
+ // parameters and updates the scope of the type parameter referred to in the
11343
+ // default type expression.
11344
+ function validateTypeParameterDefault(errorNode, typeParam, otherLiveTypeParams) {
11345
+ if (!typeParam.details.defaultType &&
11346
+ !typeParam.details.isSynthesized &&
11347
+ !typeParam.details.isSynthesizedSelf) {
11348
+ const typeVarWithDefault = otherLiveTypeParams.find((param) => param.details.defaultType);
11349
+ if (typeVarWithDefault) {
11350
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeVarWithoutDefault().format({
11351
+ name: typeParam.details.name,
11352
+ other: typeVarWithDefault.details.name,
11353
+ }), errorNode);
11354
+ }
11355
+ return;
11356
+ }
11357
+ const invalidTypeVars = new Set();
11358
+ (0, typeUtils_1.validateTypeVarDefault)(typeParam, otherLiveTypeParams, invalidTypeVars);
11359
+ // If we found one or more unapplied type variable, report an error.
11360
+ if (invalidTypeVars.size > 0) {
11361
+ const diag = new diagnostic_1.DiagnosticAddendum();
11362
+ invalidTypeVars.forEach((name) => {
11363
+ diag.addMessage(localize_1.Localizer.DiagnosticAddendum.typeVarDefaultOutOfScope().format({ name }));
11364
+ });
11365
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeVarDefaultInvalidTypeVar().format({
11366
+ name: typeParam.details.name,
11367
+ }) + diag.getString(), errorNode);
11368
+ }
11369
+ }
11287
11370
  function inferTypeParameterVarianceForClass(classType) {
11288
11371
  if (!classType.details.requiresVarianceInference) {
11289
11372
  return;
@@ -11360,7 +11443,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11360
11443
  if (!typeOfParam || !(0, types_1.isTypeVar)(typeOfParam)) {
11361
11444
  return;
11362
11445
  }
11363
- writeTypeCache(param.name, typeOfParam, 0 /* None */, /* isIncomplete */ false);
11446
+ writeTypeCache(param.name, { type: typeOfParam }, 0 /* None */);
11364
11447
  paramTypes.push(typeOfParam);
11365
11448
  });
11366
11449
  return paramTypes;
@@ -11590,6 +11673,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11590
11673
  });
11591
11674
  }
11592
11675
  function getTypeOfFunction(node) {
11676
+ var _a, _b;
11593
11677
  const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
11594
11678
  // Is this type already cached?
11595
11679
  const cachedFunctionType = readTypeCache(node.name, 0 /* None */);
@@ -11658,8 +11742,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11658
11742
  if (functionDecl && functionSymbol) {
11659
11743
  setSymbolResolutionPartialType(functionSymbol.symbol, functionDecl, functionType);
11660
11744
  }
11661
- writeTypeCache(node, functionType, /* flags */ undefined, /* isIncomplete */ false);
11662
- writeTypeCache(node.name, functionType, /* flags */ undefined, /* isIncomplete */ false);
11745
+ writeTypeCache(node, { type: functionType }, /* flags */ undefined);
11746
+ writeTypeCache(node.name, { type: functionType }, /* flags */ undefined);
11663
11747
  // Is this an "__init__" method within a pseudo-generic class? If so,
11664
11748
  // we'll add generic types to the constructor's parameters.
11665
11749
  const addGenericParamTypes = containingClassType &&
@@ -11689,8 +11773,14 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11689
11773
  }), node.functionAnnotationComment);
11690
11774
  }
11691
11775
  }
11776
+ // If this function uses PEP 695 syntax for type parameters,
11777
+ // accumulate the list of type parameters upfront.
11778
+ const typeParametersSeen = [];
11692
11779
  if (node.typeParameters) {
11693
- evaluateTypeParameterList(node.typeParameters);
11780
+ functionType.details.typeParameters = evaluateTypeParameterList(node.typeParameters);
11781
+ }
11782
+ else {
11783
+ functionType.details.typeParameters = typeParametersSeen;
11694
11784
  }
11695
11785
  const markParamAccessed = (param) => {
11696
11786
  if (param.name) {
@@ -11838,6 +11928,9 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11838
11928
  isTypeInferred,
11839
11929
  };
11840
11930
  types_1.FunctionType.addParameter(functionType, functionParam);
11931
+ if (functionParam.hasDeclaredType) {
11932
+ (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParametersSeen, (0, typeUtils_1.getTypeVarArgumentsRecursive)(functionParam.type));
11933
+ }
11841
11934
  if (param.name) {
11842
11935
  const variadicParamType = transformVariadicParamType(node, param.category, functionParam.type);
11843
11936
  paramTypes.push(variadicParamType);
@@ -11860,7 +11953,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11860
11953
  if ((0, types_1.isUnknown)(paramType)) {
11861
11954
  functionType.details.flags |= 16384 /* UnannotatedParams */;
11862
11955
  }
11863
- writeTypeCache(paramNameNode, paramType, 0 /* None */, /* isIncomplete */ false);
11956
+ writeTypeCache(paramNameNode, { type: paramType }, 0 /* None */);
11864
11957
  }
11865
11958
  });
11866
11959
  // If the function ends in P.args and P.kwargs parameters, make it exempt from
@@ -11878,19 +11971,11 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11878
11971
  // If there was a defined return type, analyze that first so when we
11879
11972
  // walk the contents of the function, return statements can be
11880
11973
  // validated against this type.
11881
- if (node.returnTypeAnnotation) {
11882
- // Temporarily set the return type to unknown in case of recursion.
11883
- functionType.details.declaredReturnType = types_1.UnknownType.create();
11884
- const returnType = getTypeOfAnnotation(node.returnTypeAnnotation, {
11885
- associateTypeVarsWithScope: true,
11886
- disallowRecursiveTypeAlias: true,
11887
- });
11888
- functionType.details.declaredReturnType = returnType;
11889
- }
11890
- else if (node.functionAnnotationComment) {
11974
+ const returnTypeAnnotationNode = (_a = node.returnTypeAnnotation) !== null && _a !== void 0 ? _a : (_b = node.functionAnnotationComment) === null || _b === void 0 ? void 0 : _b.returnTypeAnnotation;
11975
+ if (returnTypeAnnotationNode) {
11891
11976
  // Temporarily set the return type to unknown in case of recursion.
11892
11977
  functionType.details.declaredReturnType = types_1.UnknownType.create();
11893
- const returnType = getTypeOfAnnotation(node.functionAnnotationComment.returnTypeAnnotation, {
11978
+ const returnType = getTypeOfAnnotation(returnTypeAnnotationNode, {
11894
11979
  associateTypeVarsWithScope: true,
11895
11980
  disallowRecursiveTypeAlias: true,
11896
11981
  });
@@ -11911,6 +11996,10 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11911
11996
  }
11912
11997
  }
11913
11998
  }
11999
+ // Accumulate any type parameters used in the return type.
12000
+ if (functionType.details.declaredReturnType && returnTypeAnnotationNode) {
12001
+ rescopeTypeVarsForCallableReturnType(functionType.details.declaredReturnType, functionType, typeParametersSeen);
12002
+ }
11914
12003
  // If the return type is explicitly annotated as a generator, mark the
11915
12004
  // function as a generator even though it may not contain a "yield" statement.
11916
12005
  // This is important for generator functions declared in stub files, abstract
@@ -11926,6 +12015,16 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11926
12015
  functionType.details.flags |= 16 /* Generator */;
11927
12016
  }
11928
12017
  }
12018
+ // Validate the default types for all type parameters.
12019
+ functionType.details.typeParameters.forEach((typeParam, index) => {
12020
+ var _a;
12021
+ let bestErrorNode = node.name;
12022
+ if (node.typeParameters && index < node.typeParameters.parameters.length) {
12023
+ const typeParamNode = node.typeParameters.parameters[index];
12024
+ bestErrorNode = (_a = typeParamNode.defaultExpression) !== null && _a !== void 0 ? _a : typeParamNode.name;
12025
+ }
12026
+ validateTypeParameterDefault(bestErrorNode, typeParam, functionType.details.typeParameters.slice(0, index));
12027
+ });
11929
12028
  // Clear the "partially evaluated" flag to indicate that the functionType
11930
12029
  // is fully evaluated.
11931
12030
  functionType.details.flags &= ~131072 /* PartiallyEvaluated */;
@@ -11959,10 +12058,41 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
11959
12058
  }
11960
12059
  decoratedType = addOverloadsToFunctionType(node, decoratedType);
11961
12060
  }
11962
- writeTypeCache(node.name, functionType, 0 /* None */, /* isIncomplete */ false);
11963
- writeTypeCache(node, decoratedType, 0 /* None */, /* isIncomplete */ false);
12061
+ writeTypeCache(node.name, { type: functionType }, 0 /* None */);
12062
+ writeTypeCache(node, { type: decoratedType }, 0 /* None */);
11964
12063
  return { functionType, decoratedType };
11965
12064
  }
12065
+ // If the declared return type of a function contains type variables that
12066
+ // are found nowhere else in the signature and are contained within a
12067
+ // Callable, these type variables are "rescoped" from the function to
12068
+ // the Callable.
12069
+ function rescopeTypeVarsForCallableReturnType(returnType, functionType, typeParametersSeen) {
12070
+ const typeVarsInReturnType = (0, typeUtils_1.getTypeVarArgumentsRecursive)(returnType);
12071
+ const rescopedTypeVars = [];
12072
+ typeVarsInReturnType.forEach((typeVar) => {
12073
+ if (types_1.TypeBase.isInstantiable(typeVar)) {
12074
+ typeVar = types_1.TypeVarType.cloneAsInstance(typeVar);
12075
+ }
12076
+ // If this type variable isn't scoped to this function, it is probably
12077
+ // associated with an outer scope.
12078
+ if (typeVar.scopeId !== functionType.details.typeVarScopeId) {
12079
+ return;
12080
+ }
12081
+ // If this type variable was already seen in one or more input parameters,
12082
+ // don't attempt to rescope it.
12083
+ if (typeParametersSeen.some((tp) => (0, types_1.isTypeSame)((0, typeUtils_1.convertToInstance)(tp), typeVar))) {
12084
+ return;
12085
+ }
12086
+ // Is this type variable seen outside of a single callable?
12087
+ if ((0, typeUtils_1.isTypeVarLimitedToCallable)(returnType, typeVar)) {
12088
+ rescopedTypeVars.push(typeVar);
12089
+ }
12090
+ });
12091
+ (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParametersSeen, typeVarsInReturnType);
12092
+ // Note that the type parameters have been rescoped so they are not
12093
+ // considered valid for the body of this function.
12094
+ functionType.details.rescopedTypeParameters = rescopedTypeVars;
12095
+ }
11966
12096
  function adjustParameterAnnotatedType(param, type) {
11967
12097
  var _a;
11968
12098
  // PEP 484 indicates that if a parameter has a default value of 'None'
@@ -12509,7 +12639,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12509
12639
  }
12510
12640
  }
12511
12641
  }
12512
- writeTypeCache(node.suite, inferredReturnType, 0 /* None */, isIncomplete);
12642
+ writeTypeCache(node.suite, { type: inferredReturnType, isIncomplete }, 0 /* None */);
12513
12643
  }
12514
12644
  finally {
12515
12645
  functionRecursionMap.delete(node.id);
@@ -12552,7 +12682,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12552
12682
  const iteratorTypeResult = getTypeOfExpression(node.iterableExpression);
12553
12683
  const iteratedType = (_b = (_a = getTypeOfIterator(iteratorTypeResult, !!node.isAsync, node.iterableExpression)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
12554
12684
  assignTypeToExpression(node.targetExpression, iteratedType, !!iteratorTypeResult.isIncomplete, node.targetExpression);
12555
- writeTypeCache(node, iteratedType, 0 /* None */, !!iteratorTypeResult.isIncomplete);
12685
+ writeTypeCache(node, { type: iteratedType, isIncomplete: !!iteratorTypeResult.isIncomplete }, 0 /* None */);
12556
12686
  }
12557
12687
  function evaluateTypesForExceptStatement(node) {
12558
12688
  // This should be called only if the except node has a target exception.
@@ -12602,7 +12732,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12602
12732
  if (node.name) {
12603
12733
  assignTypeToExpression(node.name, targetType, /* isIncomplete */ false, node.name);
12604
12734
  }
12605
- writeTypeCache(node, targetType, 0 /* None */, /* isIncomplete */ false);
12735
+ writeTypeCache(node, { type: targetType }, 0 /* None */);
12606
12736
  }
12607
12737
  function evaluateTypesForWithStatement(node) {
12608
12738
  if (readTypeCache(node, 0 /* None */)) {
@@ -12667,7 +12797,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12667
12797
  if (node.target) {
12668
12798
  assignTypeToExpression(node.target, scopedType, !!exprTypeResult.isIncomplete, node.target);
12669
12799
  }
12670
- writeTypeCache(node, scopedType, 0 /* None */, !!exprTypeResult.isIncomplete);
12800
+ writeTypeCache(node, { type: scopedType, isIncomplete: !!exprTypeResult.isIncomplete }, 0 /* None */);
12671
12801
  }
12672
12802
  function evaluateTypesForImportAs(node) {
12673
12803
  var _a;
@@ -12699,7 +12829,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12699
12829
  }
12700
12830
  }
12701
12831
  assignTypeToNameNode(symbolNameNode, symbolType, /* isIncomplete */ false, /* ignoreEmptyContainers */ false);
12702
- writeTypeCache(node, symbolType, 0 /* None */, /* isIncomplete */ false);
12832
+ writeTypeCache(node, { type: symbolType }, 0 /* None */);
12703
12833
  }
12704
12834
  function evaluateTypesForImportFromAs(node) {
12705
12835
  var _a;
@@ -12756,7 +12886,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12756
12886
  }
12757
12887
  }
12758
12888
  assignTypeToNameNode(aliasNode, symbolType, /* isIncomplete */ false, /* ignoreEmptyContainers */ false);
12759
- writeTypeCache(node, symbolType, 0 /* None */, /* isIncomplete */ false);
12889
+ writeTypeCache(node, { type: symbolType }, 0 /* None */);
12760
12890
  }
12761
12891
  function evaluateTypesForMatchStatement(node) {
12762
12892
  if (readTypeCache(node, 0 /* None */)) {
@@ -12771,7 +12901,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12771
12901
  /* isPositiveTest */ false);
12772
12902
  }
12773
12903
  }
12774
- writeTypeCache(node, subjectType, 0 /* None */, !!subjectTypeResult.isIncomplete);
12904
+ writeTypeCache(node, { type: subjectType, isIncomplete: !!subjectTypeResult.isIncomplete }, 0 /* None */);
12775
12905
  }
12776
12906
  function evaluateTypesForCaseStatement(node) {
12777
12907
  if (readTypeCache(node, 0 /* None */)) {
@@ -12805,7 +12935,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12805
12935
  subjectType = (0, patternMatching_1.narrowTypeBasedOnPattern)(evaluatorInterface, subjectType, node.pattern,
12806
12936
  /* isPositiveTest */ true);
12807
12937
  (0, patternMatching_1.assignTypeToPatternTargets)(evaluatorInterface, subjectType, !!subjectTypeResult.isIncomplete, subjectIsObject, node.pattern);
12808
- writeTypeCache(node, subjectType, 0 /* None */, !!subjectTypeResult.isIncomplete);
12938
+ writeTypeCache(node, { type: subjectType, isIncomplete: !!subjectTypeResult.isIncomplete }, 0 /* None */);
12809
12939
  }
12810
12940
  function evaluateTypesForImportFrom(node) {
12811
12941
  if (readTypeCache(node, 0 /* None */)) {
@@ -12827,7 +12957,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12827
12957
  }
12828
12958
  }
12829
12959
  assignTypeToNameNode(symbolNameNode, symbolType, /* isIncomplete */ false, /* ignoreEmptyContainers */ false);
12830
- writeTypeCache(node, symbolType, 0 /* None */, /* isIncomplete */ false);
12960
+ writeTypeCache(node, { type: symbolType }, 0 /* None */);
12831
12961
  }
12832
12962
  function evaluateTypesForTypeAnnotationNode(node) {
12833
12963
  var _a;
@@ -12843,7 +12973,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
12843
12973
  allowFinal: ParseTreeUtils.isFinalAllowedForAssignmentTarget(node.valueExpression),
12844
12974
  allowClassVar: ParseTreeUtils.isClassVarAllowedForAssignmentTarget(node.valueExpression),
12845
12975
  });
12846
- writeTypeCache(node.valueExpression, annotationType, 0 /* None */, /* isIncomplete */ false);
12976
+ writeTypeCache(node.valueExpression, { type: annotationType }, 0 /* None */);
12847
12977
  }
12848
12978
  }
12849
12979
  function getAliasedSymbolTypeForName(node, name) {
@@ -13180,7 +13310,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13180
13310
  const param = functionNode.parameters[paramIndex];
13181
13311
  const annotatedType = getTypeOfParameterAnnotation(typeAnnotation, functionNode.parameters[paramIndex].category);
13182
13312
  const adjType = transformVariadicParamType(node, node.category, adjustParameterAnnotatedType(param, annotatedType));
13183
- writeTypeCache(node.name, adjType, 0 /* None */, /* isIncomplete */ false);
13313
+ writeTypeCache(node.name, { type: adjType }, 0 /* None */);
13184
13314
  return;
13185
13315
  }
13186
13316
  const containingClassNode = ParseTreeUtils.getEnclosingClass(functionNode, /* stopAtFunction */ true);
@@ -13191,7 +13321,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13191
13321
  const typeParamName = getPseudoGenericTypeVarName(node.name.value);
13192
13322
  const paramType = classInfo.classType.details.typeParameters.find((param) => param.details.name === typeParamName);
13193
13323
  if (paramType) {
13194
- writeTypeCache(node.name, paramType, 0 /* None */, /* isIncomplete */ false);
13324
+ writeTypeCache(node.name, { type: paramType }, 0 /* None */);
13195
13325
  return;
13196
13326
  }
13197
13327
  }
@@ -13200,8 +13330,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13200
13330
  // a parent class if it has an annotated type.
13201
13331
  const functionFlags = getFunctionFlagsFromDecorators(functionNode, /* isInClass */ true);
13202
13332
  const inferredParamType = inferParameterType(functionNode, functionFlags, paramIndex, classInfo === null || classInfo === void 0 ? void 0 : classInfo.classType);
13203
- writeTypeCache(node.name, transformVariadicParamType(node, node.category, inferredParamType !== null && inferredParamType !== void 0 ? inferredParamType : types_1.UnknownType.create()), 0 /* None */,
13204
- /* isIncomplete */ false);
13333
+ writeTypeCache(node.name, { type: transformVariadicParamType(node, node.category, inferredParamType !== null && inferredParamType !== void 0 ? inferredParamType : types_1.UnknownType.create()) }, 0 /* None */);
13205
13334
  }
13206
13335
  // Evaluates the types that are assigned within the statement that contains
13207
13336
  // the specified parse node. In some cases, a broader statement may need to
@@ -13311,36 +13440,20 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13311
13440
  // within that tree. If the type cannot be determined (because it's part
13312
13441
  // of a cyclical dependency), the function returns undefined.
13313
13442
  function evaluateTypeForSubnode(subnode, callback) {
13314
- // If the type cache is already populated, don't bother
13315
- // doing additional work.
13316
- let subnodeType = readTypeCache(subnode, /* flags */ undefined);
13317
- if (subnodeType) {
13318
- return { type: subnodeType };
13319
- }
13320
- const oldIncompleteCache = incompleteTypeCache;
13321
- try {
13322
- // If there isn't already an incompleteTypeCache allocated, allocate
13323
- // one now. We'll use this same cache for nested calls, but we'll
13324
- // abandon it once the last nested call completes.
13325
- if (!incompleteTypeCache) {
13326
- incompleteTypeCache = new Map();
13327
- }
13328
- callback();
13329
- subnodeType = readTypeCache(subnode, /* flags */ undefined);
13330
- if (subnodeType) {
13331
- return { type: subnodeType };
13332
- }
13333
- subnodeType = incompleteTypeCache.get(subnode.id);
13334
- if (subnodeType) {
13335
- return { type: subnodeType, isIncomplete: true };
13336
- }
13337
- incompleteTypeCache = oldIncompleteCache;
13338
- }
13339
- catch (e) {
13340
- // We don't use a finally clause here because the debugger doesn't
13341
- // handle it well when stepping through code.
13342
- incompleteTypeCache = oldIncompleteCache;
13343
- throw e;
13443
+ // If the type cache is already populated with a complete type,
13444
+ // don't bother doing additional work.
13445
+ let cacheEntry = readTypeCacheEntry(subnode);
13446
+ if (cacheEntry && !cacheEntry.typeResult.isIncomplete) {
13447
+ return { type: cacheEntry.typeResult.type };
13448
+ }
13449
+ callback();
13450
+ cacheEntry = readTypeCacheEntry(subnode);
13451
+ if (cacheEntry) {
13452
+ return {
13453
+ type: cacheEntry.typeResult.type,
13454
+ isIncomplete: cacheEntry.typeResult.isIncomplete,
13455
+ expectedTypeDiagAddendum: cacheEntry.typeResult.expectedTypeDiagAddendum,
13456
+ };
13344
13457
  }
13345
13458
  return undefined;
13346
13459
  }
@@ -13605,8 +13718,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13605
13718
  }
13606
13719
  }
13607
13720
  }
13721
+ const typeVarContext = new typeVarContext_1.TypeVarContext(classType.details.typeVarScopeId);
13608
13722
  fullTypeParams.forEach((typeParam, index) => {
13609
- var _a;
13610
13723
  if (typeArgs && index < typeArgs.length) {
13611
13724
  if (typeParam.details.isParamSpec) {
13612
13725
  const typeArg = typeArgs[index];
@@ -13616,6 +13729,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13616
13729
  types_1.FunctionType.addDefaultParameters(functionType);
13617
13730
  functionType.details.flags |= 32768 /* SkipArgsKwargsCompatibilityCheck */;
13618
13731
  typeArgTypes.push(functionType);
13732
+ typeVarContext.setTypeVarType(typeParam, (0, typeUtils_1.convertTypeToParamSpecValue)(functionType));
13619
13733
  return;
13620
13734
  }
13621
13735
  if (typeArg.typeList) {
@@ -13629,6 +13743,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13629
13743
  });
13630
13744
  });
13631
13745
  typeArgTypes.push(functionType);
13746
+ typeVarContext.setTypeVarType(typeParam, (0, typeUtils_1.convertTypeToParamSpecValue)(functionType));
13632
13747
  return;
13633
13748
  }
13634
13749
  if ((0, types_1.isInstantiableClass)(typeArg.type) && types_1.ClassType.isBuiltIn(typeArg.type, 'Concatenate')) {
@@ -13655,10 +13770,19 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13655
13770
  return;
13656
13771
  }
13657
13772
  }
13658
- typeArgTypes.push((0, typeUtils_1.convertToInstance)(typeArgs[index].type));
13773
+ const typeArgType = (0, typeUtils_1.convertToInstance)(typeArgs[index].type);
13774
+ typeArgTypes.push(typeArgType);
13775
+ typeVarContext.setTypeVarType(typeParam, typeArgType);
13659
13776
  return;
13660
13777
  }
13661
- typeArgTypes.push((_a = typeParam.details.defaultType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create());
13778
+ const solvedDefaultType = (0, typeUtils_1.applySolvedTypeVars)(typeParam, typeVarContext, { unknownIfNotFound: true });
13779
+ typeArgTypes.push(solvedDefaultType);
13780
+ if ((0, types_1.isParamSpec)(typeParam)) {
13781
+ typeVarContext.setTypeVarType(typeParam, (0, typeUtils_1.convertTypeToParamSpecValue)(solvedDefaultType));
13782
+ }
13783
+ else {
13784
+ typeVarContext.setTypeVarType(typeParam, solvedDefaultType);
13785
+ }
13662
13786
  });
13663
13787
  typeArgTypes = typeArgTypes.map((typeArgType, index) => {
13664
13788
  if (index < typeArgCount) {
@@ -13880,8 +14004,8 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
13880
14004
  // Disables recording of errors and warnings and disables
13881
14005
  // any caching of types, under the assumption that we're
13882
14006
  // performing speculative evaluations.
13883
- function useSpeculativeMode(speculativeNode, callback, allowCacheRetention = true) {
13884
- speculativeTypeTracker.enterSpeculativeContext(speculativeNode, allowCacheRetention);
14007
+ function useSpeculativeMode(speculativeNode, callback) {
14008
+ speculativeTypeTracker.enterSpeculativeContext(speculativeNode);
13885
14009
  try {
13886
14010
  const result = callback();
13887
14011
  speculativeTypeTracker.leaveSpeculativeContext();
@@ -14198,65 +14322,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14198
14322
  return undefined;
14199
14323
  }
14200
14324
  case 3 /* TypeParameter */: {
14201
- let typeVar = types_1.TypeVarType.createInstantiable(declaration.node.name.value);
14202
- if (declaration.node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple) {
14203
- typeVar.details.isVariadic = true;
14204
- }
14205
- else if (declaration.node.typeParamCategory === parseNodes_1.TypeParameterCategory.ParamSpec) {
14206
- typeVar.details.isParamSpec = true;
14207
- }
14208
- if (declaration.node.boundExpression) {
14209
- if (declaration.node.boundExpression.nodeType === 52 /* Tuple */) {
14210
- const constraints = declaration.node.boundExpression.expressions.map((constraint) => {
14211
- const constraintType = getTypeOfExpressionExpectingType(constraint).type;
14212
- if ((0, typeUtils_1.requiresSpecialization)(constraintType, /* ignorePseudoGeneric */ true)) {
14213
- addError(localize_1.Localizer.Diagnostic.typeVarBoundGeneric(), constraint);
14214
- }
14215
- return (0, typeUtils_1.convertToInstance)(constraintType);
14216
- });
14217
- if (constraints.length < 2) {
14218
- addDiagnostic(AnalyzerNodeInfo.getFileInfo(declaration.node.boundExpression).diagnosticRuleSet
14219
- .reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeVarSingleConstraint(), declaration.node.boundExpression);
14220
- }
14221
- else if (declaration.node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVar) {
14222
- typeVar.details.constraints = constraints;
14223
- }
14224
- }
14225
- else {
14226
- const boundType = getTypeOfExpressionExpectingType(declaration.node.boundExpression).type;
14227
- if ((0, typeUtils_1.requiresSpecialization)(boundType, /* ignorePseudoGeneric */ true)) {
14228
- addError(localize_1.Localizer.Diagnostic.typeVarConstraintGeneric(), declaration.node.boundExpression);
14229
- }
14230
- if (declaration.node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVar) {
14231
- typeVar.details.boundType = (0, typeUtils_1.convertToInstance)(boundType);
14232
- }
14233
- }
14234
- }
14235
- if (declaration.node.defaultExpression) {
14236
- // TODO - need to finish. For now, just evaluate the expression
14237
- // to generate any errors.
14238
- getTypeOfExpression(declaration.node.defaultExpression, 2097152 /* AllowUnpackedTupleOrTypeVarTuple */);
14239
- }
14240
- typeVar.details.isTypeParamSyntax = true;
14241
- // Associate the type variable with the owning scope.
14242
- const scopeNode = ParseTreeUtils.getTypeVarScopeNode(declaration.node);
14243
- if (scopeNode) {
14244
- let scopeType;
14245
- if (scopeNode.nodeType === 10 /* Class */) {
14246
- scopeType = 0 /* Class */;
14247
- // Set the variance to "auto" for class-scoped TypeVars.
14248
- typeVar.details.declaredVariance = 0 /* Auto */;
14249
- }
14250
- else if (scopeNode.nodeType === 28 /* Function */) {
14251
- scopeType = 1 /* Function */;
14252
- }
14253
- else {
14254
- (0, debug_1.assert)(scopeNode.nodeType === 77 /* TypeAlias */);
14255
- scopeType = 2 /* TypeAlias */;
14256
- }
14257
- typeVar = types_1.TypeVarType.cloneForScopeId(typeVar, getScopeIdForNode(scopeNode.nodeType === 77 /* TypeAlias */ ? scopeNode.name : scopeNode), scopeNode.name.value, scopeType);
14258
- }
14259
- return typeVar;
14325
+ return getTypeOfTypeParameter(declaration.node);
14260
14326
  }
14261
14327
  case 1 /* Variable */: {
14262
14328
  const typeAnnotationNode = declaration.typeAnnotationNode;
@@ -14301,6 +14367,99 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14301
14367
  }
14302
14368
  }
14303
14369
  }
14370
+ function getTypeOfTypeParameter(node) {
14371
+ // Is this type already cached?
14372
+ const cachedTypeVarType = readTypeCache(node.name, 0 /* None */);
14373
+ if (cachedTypeVarType && (0, types_1.isTypeVar)(cachedTypeVarType)) {
14374
+ return cachedTypeVarType;
14375
+ }
14376
+ let typeVar = types_1.TypeVarType.createInstantiable(node.name.value);
14377
+ typeVar.details.isTypeParamSyntax = true;
14378
+ if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple) {
14379
+ typeVar.details.isVariadic = true;
14380
+ }
14381
+ else if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.ParamSpec) {
14382
+ typeVar.details.isParamSpec = true;
14383
+ }
14384
+ // Cache the value before we evaluate the bound or the default type in
14385
+ // case it refers to itself in a circular manner.
14386
+ writeTypeCache(node, { type: typeVar }, /* flags */ undefined);
14387
+ writeTypeCache(node.name, { type: typeVar }, /* flags */ undefined);
14388
+ if (node.boundExpression) {
14389
+ if (node.boundExpression.nodeType === 52 /* Tuple */) {
14390
+ const constraints = node.boundExpression.expressions.map((constraint) => {
14391
+ const constraintType = getTypeOfExpressionExpectingType(constraint).type;
14392
+ if ((0, typeUtils_1.requiresSpecialization)(constraintType, /* ignorePseudoGeneric */ true)) {
14393
+ addError(localize_1.Localizer.Diagnostic.typeVarBoundGeneric(), constraint);
14394
+ }
14395
+ return (0, typeUtils_1.convertToInstance)(constraintType);
14396
+ });
14397
+ if (constraints.length < 2) {
14398
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(node.boundExpression).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeVarSingleConstraint(), node.boundExpression);
14399
+ }
14400
+ else if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVar) {
14401
+ typeVar.details.constraints = constraints;
14402
+ }
14403
+ }
14404
+ else {
14405
+ const boundType = getTypeOfExpressionExpectingType(node.boundExpression).type;
14406
+ if ((0, typeUtils_1.requiresSpecialization)(boundType, /* ignorePseudoGeneric */ true)) {
14407
+ addError(localize_1.Localizer.Diagnostic.typeVarConstraintGeneric(), node.boundExpression);
14408
+ }
14409
+ if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVar) {
14410
+ typeVar.details.boundType = (0, typeUtils_1.convertToInstance)(boundType);
14411
+ }
14412
+ }
14413
+ }
14414
+ if (node.defaultExpression) {
14415
+ if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.ParamSpec) {
14416
+ typeVar.details.defaultType = getParamSpecDefaultType(node.defaultExpression);
14417
+ }
14418
+ else if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple) {
14419
+ typeVar.details.defaultType = getTypeVarTupleDefaultType(node.defaultExpression);
14420
+ }
14421
+ else {
14422
+ typeVar.details.defaultType = (0, typeUtils_1.convertToInstance)(getTypeOfExpressionExpectingType(node.defaultExpression).type);
14423
+ }
14424
+ }
14425
+ // If a default is provided, make sure it is compatible with the bound
14426
+ // or constraint.
14427
+ if (typeVar.details.defaultType && node.defaultExpression) {
14428
+ const typeVarContext = new typeVarContext_1.TypeVarContext(types_1.WildcardTypeVarScopeId);
14429
+ const concreteDefaultType = (0, typeUtils_1.applySolvedTypeVars)(typeVar.details.defaultType, typeVarContext, {
14430
+ unknownIfNotFound: true,
14431
+ });
14432
+ if (typeVar.details.boundType) {
14433
+ if (!assignType(typeVar.details.boundType, concreteDefaultType)) {
14434
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeVarDefaultBoundMismatch(), node.defaultExpression);
14435
+ }
14436
+ }
14437
+ else if (typeVar.details.constraints.length > 0) {
14438
+ if (!typeVar.details.constraints.some((constraint) => (0, types_1.isTypeSame)(constraint, concreteDefaultType))) {
14439
+ addDiagnostic(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.Localizer.Diagnostic.typeVarDefaultConstraintMismatch(), node.defaultExpression);
14440
+ }
14441
+ }
14442
+ }
14443
+ // Associate the type variable with the owning scope.
14444
+ const scopeNode = ParseTreeUtils.getTypeVarScopeNode(node);
14445
+ if (scopeNode) {
14446
+ let scopeType;
14447
+ if (scopeNode.nodeType === 10 /* Class */) {
14448
+ scopeType = 0 /* Class */;
14449
+ // Set the variance to "auto" for class-scoped TypeVars.
14450
+ typeVar.details.declaredVariance = 0 /* Auto */;
14451
+ }
14452
+ else if (scopeNode.nodeType === 28 /* Function */) {
14453
+ scopeType = 1 /* Function */;
14454
+ }
14455
+ else {
14456
+ (0, debug_1.assert)(scopeNode.nodeType === 77 /* TypeAlias */);
14457
+ scopeType = 2 /* TypeAlias */;
14458
+ }
14459
+ typeVar = types_1.TypeVarType.cloneForScopeId(typeVar, getScopeIdForNode(scopeNode.nodeType === 77 /* TypeAlias */ ? scopeNode.name : scopeNode), scopeNode.name.value, scopeType);
14460
+ }
14461
+ return typeVar;
14462
+ }
14304
14463
  function getInferredTypeOfDeclaration(symbol, decl) {
14305
14464
  var _a, _b;
14306
14465
  const resolvedDecl = resolveAliasDeclaration(decl,
@@ -14527,7 +14686,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14527
14686
  return getEffectiveTypeOfSymbolForUsage(symbol).type;
14528
14687
  }
14529
14688
  function getEffectiveTypeOfSymbolForUsage(symbol, usageNode, useLastDecl = false) {
14530
- var _a;
14689
+ var _a, _b;
14531
14690
  // If there's a declared type, it takes precedence over inferred types.
14532
14691
  if (symbol.hasTypedDeclarations()) {
14533
14692
  const declaredType = getDeclaredTypeOfSymbol(symbol, usageNode);
@@ -14551,7 +14710,6 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14551
14710
  }
14552
14711
  // Look in the cache to see if we've computed this already.
14553
14712
  let cacheEntries = effectiveTypeCache.get(symbol.id);
14554
- let evaluationAttempts = 0;
14555
14713
  const usageNodeId = usageNode ? usageNode.id : undefined;
14556
14714
  const effectiveTypeCacheKey = `${usageNodeId === undefined ? '.' : usageNodeId.toString()}${useLastDecl ? '*' : ''}`;
14557
14715
  if (cacheEntries) {
@@ -14560,7 +14718,6 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14560
14718
  if (!result.isIncomplete) {
14561
14719
  return result;
14562
14720
  }
14563
- evaluationAttempts = ((_a = result.evaluationAttempts) !== null && _a !== void 0 ? _a : 0) + 1;
14564
14721
  }
14565
14722
  }
14566
14723
  // Infer the type.
@@ -14688,20 +14845,21 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14688
14845
  }
14689
14846
  isIncomplete = true;
14690
14847
  // Note that at least one decl could not be evaluated because
14691
- // it was already in the process of being evaluated. Don't set
14692
- // this flag if we've already attempted the type evaluation
14693
- // many times because this probably means there's a cyclical
14694
- // dependency that cannot be broken.
14695
- if (evaluationAttempts < maxEffectiveTypeEvaluationAttempts) {
14696
- sawPendingEvaluation = true;
14697
- }
14848
+ // it was already in the process of being evaluated.
14849
+ sawPendingEvaluation = true;
14698
14850
  }
14699
14851
  }
14700
14852
  });
14701
14853
  if (typesToCombine.length > 0) {
14854
+ // How many times have we already attempted to evaluate this declaration already?
14855
+ const evaluationAttempts = ((_b = (_a = cacheEntries === null || cacheEntries === void 0 ? void 0 : cacheEntries.get(effectiveTypeCacheKey)) === null || _a === void 0 ? void 0 : _a.evaluationAttempts) !== null && _b !== void 0 ? _b : 0) + 1;
14856
+ // Ignore the pending evaluation flag if we've already attempted the
14857
+ // type evaluation many times because this probably means there's a
14858
+ // cyclical dependency that cannot be broken.
14859
+ isIncomplete = sawPendingEvaluation && evaluationAttempts < maxEffectiveTypeEvaluationAttempts;
14702
14860
  const result = {
14703
14861
  type: (0, types_1.combineTypes)(typesToCombine),
14704
- isIncomplete: sawPendingEvaluation,
14862
+ isIncomplete,
14705
14863
  includesVariableDecl,
14706
14864
  includesIllegalTypeAliasDecl: !decls.every((decl) => (0, declarationUtils_1.isPossibleTypeAliasDeclaration)(decl)),
14707
14865
  isRecursiveDefinition: false,
@@ -14723,7 +14881,6 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14723
14881
  includesVariableDecl,
14724
14882
  includesIllegalTypeAliasDecl: !decls.every((decl) => (0, declarationUtils_1.isPossibleTypeAliasDeclaration)(decl)),
14725
14883
  isRecursiveDefinition: false,
14726
- evaluationAttempts,
14727
14884
  };
14728
14885
  }
14729
14886
  function getDeclaredTypeOfSymbol(symbol, usageNode) {
@@ -14982,7 +15139,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
14982
15139
  paramType = types_1.UnknownType.create();
14983
15140
  }
14984
15141
  paramTypes.push(paramType);
14985
- writeTypeCache(param.name, paramType, 0 /* None */, /* isIncomplete */ false);
15142
+ writeTypeCache(param.name, { type: paramType }, 0 /* None */);
14986
15143
  }
14987
15144
  });
14988
15145
  // Don't bother trying to determine the contextual return
@@ -16436,9 +16593,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
16436
16593
  let specializedDestType = destType;
16437
16594
  let reverseMatchingFailed = false;
16438
16595
  if ((flags & 2 /* ReverseTypeVarMatching */) === 0) {
16439
- specializedDestType = (0, typeUtils_1.applySolvedTypeVars)(destType, destTypeVarContext,
16440
- /* unknownIfNotFound */ undefined,
16441
- /* useNarrowBoundOnly */ true);
16596
+ specializedDestType = (0, typeUtils_1.applySolvedTypeVars)(destType, destTypeVarContext, { useNarrowBoundOnly: true });
16442
16597
  if ((0, typeUtils_1.requiresSpecialization)(specializedDestType)) {
16443
16598
  reverseMatchingFailed = !assignType(specializedSrcType, specializedDestType,
16444
16599
  /* diag */ undefined, srcTypeVarContext, destTypeVarContext, (flags ^ 2 /* ReverseTypeVarMatching */) |
@@ -16448,9 +16603,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
16448
16603
  }
16449
16604
  }
16450
16605
  else {
16451
- specializedSrcType = (0, typeUtils_1.applySolvedTypeVars)(srcType, srcTypeVarContext,
16452
- /* unknownIfNotFound */ undefined,
16453
- /* useNarrowBoundOnly */ true);
16606
+ specializedSrcType = (0, typeUtils_1.applySolvedTypeVars)(srcType, srcTypeVarContext, { useNarrowBoundOnly: true });
16454
16607
  if ((0, typeUtils_1.requiresSpecialization)(specializedSrcType)) {
16455
16608
  reverseMatchingFailed = !assignType(specializedSrcType, specializedDestType,
16456
16609
  /* diag */ undefined, srcTypeVarContext, destTypeVarContext, (flags ^ 2 /* ReverseTypeVarMatching */) |
@@ -16475,8 +16628,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
16475
16628
  if ((0, types_1.isTypeVar)(specializedSrcType) &&
16476
16629
  specializedSrcType.details.isSynthesizedSelf &&
16477
16630
  specializedSrcType.details.boundType) {
16478
- specializedSrcType = (0, typeUtils_1.applySolvedTypeVars)(specializedSrcType.details.boundType, new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(specializedSrcType)),
16479
- /* unknownIfNotFound */ true);
16631
+ specializedSrcType = (0, typeUtils_1.applySolvedTypeVars)(specializedSrcType.details.boundType, new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(specializedSrcType)), { unknownIfNotFound: true });
16480
16632
  }
16481
16633
  }
16482
16634
  if (!assignType(specializedSrcType, specializedDestType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), srcTypeVarContext, destTypeVarContext, flags, recursionCount)) {
@@ -16506,6 +16658,11 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
16506
16658
  if (destDetails.argsIndex === undefined) {
16507
16659
  return;
16508
16660
  }
16661
+ // If the *args parameter isn't an unpacked TypeVarTuple or tuple,
16662
+ // we have nothing to do.
16663
+ if (!(0, types_1.isUnpacked)(destDetails.params[destDetails.argsIndex].type)) {
16664
+ return;
16665
+ }
16509
16666
  // If the source doesn't have enough positional parameters, we have nothing to do.
16510
16667
  if (srcDetails.params.length < destDetails.argsIndex) {
16511
16668
  return;
@@ -16739,9 +16896,9 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
16739
16896
  // The converse situation is OK.
16740
16897
  if (!types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(destType) &&
16741
16898
  srcParamDetails.argsIndex === undefined &&
16899
+ srcType.details.paramSpec === undefined &&
16742
16900
  destParamDetails.argsIndex !== undefined &&
16743
- !destParamDetails.hasUnpackedVariadicTypeVar &&
16744
- !targetIncludesParamSpec) {
16901
+ !destParamDetails.hasUnpackedVariadicTypeVar) {
16745
16902
  diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.Localizer.DiagnosticAddendum.argsParamMissing().format({
16746
16903
  paramName: (_h = destParamDetails.params[destParamDetails.argsIndex].param.name) !== null && _h !== void 0 ? _h : '',
16747
16904
  }));
@@ -17161,9 +17318,23 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
17161
17318
  // Verify that the positional param count matches exactly or that the override
17162
17319
  // adds only params that preserve the original signature.
17163
17320
  let foundParamCountMismatch = false;
17164
- if (overrideParamDetails.positionParamCount < baseParamDetails.positionParamCount &&
17165
- overrideParamDetails.argsIndex === undefined) {
17166
- foundParamCountMismatch = true;
17321
+ if (overrideParamDetails.positionParamCount < baseParamDetails.positionParamCount) {
17322
+ if (overrideParamDetails.argsIndex === undefined) {
17323
+ foundParamCountMismatch = true;
17324
+ }
17325
+ else {
17326
+ const overrideArgsType = overrideParamDetails.params[overrideParamDetails.argsIndex].type;
17327
+ for (let i = overrideParamDetails.positionParamCount; i < baseParamDetails.positionParamCount; i++) {
17328
+ if (!assignType(overrideArgsType, baseParamDetails.params[i].type, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overrideMethod)), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(baseMethod)), 8 /* SkipSolveTypeVars */)) {
17329
+ localize_1.Localizer.DiagnosticAddendum.overrideParamType().format({
17330
+ index: i + 1,
17331
+ baseType: printType(baseParamDetails.params[i].type),
17332
+ overrideType: printType(overrideArgsType),
17333
+ });
17334
+ canOverride = false;
17335
+ }
17336
+ }
17337
+ }
17167
17338
  }
17168
17339
  else if (overrideParamDetails.positionParamCount > baseParamDetails.positionParamCount) {
17169
17340
  // Verify that all of the override parameters that extend the
@@ -17682,6 +17853,7 @@ function createTypeEvaluator(importLookup, evaluatorOptions) {
17682
17853
  const evaluatorInterface = {
17683
17854
  runWithCancellationToken,
17684
17855
  getType,
17856
+ getTypeResult,
17685
17857
  getCachedType,
17686
17858
  getTypeOfExpression,
17687
17859
  getTypeOfAnnotation,