@zzzen/pyright-internal 1.2.0-dev.20261101 → 1.2.0-dev.20261115

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 (207) hide show
  1. package/dist/analyzer/binder.d.ts +1 -0
  2. package/dist/analyzer/binder.js +209 -4
  3. package/dist/analyzer/binder.js.map +1 -1
  4. package/dist/analyzer/codeFlowEngine.js +28 -3
  5. package/dist/analyzer/codeFlowEngine.js.map +1 -1
  6. package/dist/analyzer/constructorTransform.js +12 -0
  7. package/dist/analyzer/constructorTransform.js.map +1 -1
  8. package/dist/analyzer/constructors.d.ts +2 -2
  9. package/dist/analyzer/constructors.js +69 -10
  10. package/dist/analyzer/constructors.js.map +1 -1
  11. package/dist/analyzer/decorators.d.ts +1 -1
  12. package/dist/analyzer/decorators.js.map +1 -1
  13. package/dist/analyzer/enums.d.ts +10 -3
  14. package/dist/analyzer/enums.js +389 -2
  15. package/dist/analyzer/enums.js.map +1 -1
  16. package/dist/analyzer/functionTransform.d.ts +5 -0
  17. package/dist/analyzer/functionTransform.js +6 -3
  18. package/dist/analyzer/functionTransform.js.map +1 -1
  19. package/dist/analyzer/missingBindingMetadata.d.ts +6 -0
  20. package/dist/analyzer/missingBindingMetadata.js +22 -0
  21. package/dist/analyzer/missingBindingMetadata.js.map +1 -0
  22. package/dist/analyzer/namedTuples.d.ts +4 -1
  23. package/dist/analyzer/namedTuples.js +1 -0
  24. package/dist/analyzer/namedTuples.js.map +1 -1
  25. package/dist/analyzer/operations.js +81 -4
  26. package/dist/analyzer/operations.js.map +1 -1
  27. package/dist/analyzer/patternMatching.d.ts +5 -1
  28. package/dist/analyzer/patternMatching.js +3 -0
  29. package/dist/analyzer/patternMatching.js.map +1 -1
  30. package/dist/analyzer/program.d.ts +3 -0
  31. package/dist/analyzer/program.js +71 -1
  32. package/dist/analyzer/program.js.map +1 -1
  33. package/dist/analyzer/protocols.d.ts +1 -0
  34. package/dist/analyzer/protocols.js +171 -10
  35. package/dist/analyzer/protocols.js.map +1 -1
  36. package/dist/analyzer/scope.d.ts +3 -0
  37. package/dist/analyzer/scope.js +28 -6
  38. package/dist/analyzer/scope.js.map +1 -1
  39. package/dist/analyzer/symbol.d.ts +4 -1
  40. package/dist/analyzer/symbol.js +8 -0
  41. package/dist/analyzer/symbol.js.map +1 -1
  42. package/dist/analyzer/tuples.d.ts +1 -1
  43. package/dist/analyzer/tuples.js.map +1 -1
  44. package/dist/analyzer/typeCacheUtils.d.ts +1 -0
  45. package/dist/analyzer/typeCacheUtils.js +10 -0
  46. package/dist/analyzer/typeCacheUtils.js.map +1 -1
  47. package/dist/analyzer/typeEvaluator/boundMethodSpecialization.d.ts +15 -0
  48. package/dist/analyzer/typeEvaluator/boundMethodSpecialization.js +98 -0
  49. package/dist/analyzer/typeEvaluator/boundMethodSpecialization.js.map +1 -0
  50. package/dist/analyzer/typeEvaluator/classConstruction.d.ts +25 -0
  51. package/dist/analyzer/typeEvaluator/classConstruction.js +251 -0
  52. package/dist/analyzer/typeEvaluator/classConstruction.js.map +1 -0
  53. package/dist/analyzer/typeEvaluator/collectionInference.d.ts +41 -0
  54. package/dist/analyzer/typeEvaluator/collectionInference.js +695 -0
  55. package/dist/analyzer/typeEvaluator/collectionInference.js.map +1 -0
  56. package/dist/analyzer/typeEvaluator/diagnostics.d.ts +33 -0
  57. package/dist/analyzer/typeEvaluator/diagnostics.js +198 -0
  58. package/dist/analyzer/typeEvaluator/diagnostics.js.map +1 -0
  59. package/dist/analyzer/typeEvaluator/evaluatorCore.d.ts +80 -0
  60. package/dist/analyzer/typeEvaluator/evaluatorCore.js +1132 -0
  61. package/dist/analyzer/typeEvaluator/evaluatorCore.js.map +1 -0
  62. package/dist/analyzer/typeEvaluator/evaluatorNarrowing.d.ts +17 -0
  63. package/dist/analyzer/typeEvaluator/evaluatorNarrowing.js +370 -0
  64. package/dist/analyzer/typeEvaluator/evaluatorNarrowing.js.map +1 -0
  65. package/dist/analyzer/typeEvaluator/expressionEvaluation.d.ts +81 -0
  66. package/dist/analyzer/typeEvaluator/expressionEvaluation.js +1802 -0
  67. package/dist/analyzer/typeEvaluator/expressionEvaluation.js.map +1 -0
  68. package/dist/analyzer/typeEvaluator/flowAnalysis.d.ts +33 -0
  69. package/dist/analyzer/typeEvaluator/flowAnalysis.js +217 -0
  70. package/dist/analyzer/typeEvaluator/flowAnalysis.js.map +1 -0
  71. package/dist/analyzer/typeEvaluator/internals.d.ts +138 -0
  72. package/dist/analyzer/typeEvaluator/internals.js +10 -0
  73. package/dist/analyzer/typeEvaluator/internals.js.map +1 -0
  74. package/dist/analyzer/typeEvaluator/literalTypes.d.ts +3 -0
  75. package/dist/analyzer/typeEvaluator/literalTypes.js +52 -0
  76. package/dist/analyzer/typeEvaluator/literalTypes.js.map +1 -0
  77. package/dist/analyzer/typeEvaluator/memberResolution.d.ts +79 -0
  78. package/dist/analyzer/typeEvaluator/memberResolution.js +1007 -0
  79. package/dist/analyzer/typeEvaluator/memberResolution.js.map +1 -0
  80. package/dist/analyzer/typeEvaluator/overrideValidation.d.ts +15 -0
  81. package/dist/analyzer/typeEvaluator/overrideValidation.js +422 -0
  82. package/dist/analyzer/typeEvaluator/overrideValidation.js.map +1 -0
  83. package/dist/analyzer/typeEvaluator/returnTypeInference.d.ts +33 -0
  84. package/dist/analyzer/typeEvaluator/returnTypeInference.js +226 -0
  85. package/dist/analyzer/typeEvaluator/returnTypeInference.js.map +1 -0
  86. package/dist/analyzer/typeEvaluator/specialFormCreation.d.ts +39 -0
  87. package/dist/analyzer/typeEvaluator/specialFormCreation.js +1728 -0
  88. package/dist/analyzer/typeEvaluator/specialFormCreation.js.map +1 -0
  89. package/dist/analyzer/typeEvaluator/tupleUnpacking.d.ts +2 -0
  90. package/dist/analyzer/typeEvaluator/tupleUnpacking.js +36 -0
  91. package/dist/analyzer/typeEvaluator/tupleUnpacking.js.map +1 -0
  92. package/dist/analyzer/typeEvaluator/typeCompatibility.d.ts +36 -0
  93. package/dist/analyzer/typeEvaluator/typeCompatibility.js +1333 -0
  94. package/dist/analyzer/typeEvaluator/typeCompatibility.js.map +1 -0
  95. package/dist/analyzer/typeEvaluator/typeGuardNarrowing.d.ts +187 -0
  96. package/dist/analyzer/typeEvaluator/typeGuardNarrowing.js +1763 -0
  97. package/dist/analyzer/typeEvaluator/typeGuardNarrowing.js.map +1 -0
  98. package/dist/analyzer/typeEvaluator/typeVarHandling.d.ts +48 -0
  99. package/dist/analyzer/typeEvaluator/typeVarHandling.js +756 -0
  100. package/dist/analyzer/typeEvaluator/typeVarHandling.js.map +1 -0
  101. package/dist/analyzer/typeEvaluator.d.ts +3 -31
  102. package/dist/analyzer/typeEvaluator.js +5093 -13740
  103. package/dist/analyzer/typeEvaluator.js.map +1 -1
  104. package/dist/analyzer/typeGuards.d.ts +2 -2
  105. package/dist/analyzer/typeGuards.js +213 -1568
  106. package/dist/analyzer/typeGuards.js.map +1 -1
  107. package/dist/analyzer/typeUtils.js +6 -2
  108. package/dist/analyzer/typeUtils.js.map +1 -1
  109. package/dist/analyzer/typedDicts.js +125 -1
  110. package/dist/analyzer/typedDicts.js.map +1 -1
  111. package/dist/analyzer/types.d.ts +6 -1
  112. package/dist/analyzer/types.js +32 -4
  113. package/dist/analyzer/types.js.map +1 -1
  114. package/dist/browser/browserConnection.d.ts +12 -0
  115. package/dist/browser/browserConnection.js +23 -0
  116. package/dist/browser/browserConnection.js.map +1 -0
  117. package/dist/browser/browserFileSystem.d.ts +73 -0
  118. package/dist/browser/browserFileSystem.js +578 -0
  119. package/dist/browser/browserFileSystem.js.map +1 -0
  120. package/dist/browser/browserHost.d.ts +4 -0
  121. package/dist/browser/browserHost.js +10 -0
  122. package/dist/browser/browserHost.js.map +1 -0
  123. package/dist/browser/browserProcess.d.ts +1 -0
  124. package/dist/browser/browserProcess.js +17 -0
  125. package/dist/browser/browserProcess.js.map +1 -0
  126. package/dist/browser/browserServer.d.ts +8 -0
  127. package/dist/browser/browserServer.js +32 -0
  128. package/dist/browser/browserServer.js.map +1 -0
  129. package/dist/browser/cancellation/common.d.ts +10 -0
  130. package/dist/browser/cancellation/common.js +114 -0
  131. package/dist/browser/cancellation/common.js.map +1 -0
  132. package/dist/browser/cancellation/objectURLReceiverStrategy.d.ts +5 -0
  133. package/dist/browser/cancellation/objectURLReceiverStrategy.js +37 -0
  134. package/dist/browser/cancellation/objectURLReceiverStrategy.js.map +1 -0
  135. package/dist/browser/cancellation/objectURLSenderStrategy.d.ts +7 -0
  136. package/dist/browser/cancellation/objectURLSenderStrategy.js +32 -0
  137. package/dist/browser/cancellation/objectURLSenderStrategy.js.map +1 -0
  138. package/dist/browser/worker.d.ts +1 -0
  139. package/dist/browser/worker.js +33 -0
  140. package/dist/browser/worker.js.map +1 -0
  141. package/dist/common/processUtils.d.ts +1 -0
  142. package/dist/common/processUtils.js +38 -0
  143. package/dist/common/processUtils.js.map +1 -1
  144. package/dist/common/windowsProcessTree.json +20 -2
  145. package/dist/localization/package.nls.cs.json +2 -0
  146. package/dist/localization/package.nls.de.json +2 -0
  147. package/dist/localization/package.nls.es.json +2 -0
  148. package/dist/localization/package.nls.fr.json +2 -0
  149. package/dist/localization/package.nls.it.json +2 -0
  150. package/dist/localization/package.nls.ja.json +2 -0
  151. package/dist/localization/package.nls.ko.json +2 -0
  152. package/dist/localization/package.nls.pl.json +2 -0
  153. package/dist/localization/package.nls.pt-br.json +2 -0
  154. package/dist/localization/package.nls.qps-ploc.json +2 -0
  155. package/dist/localization/package.nls.ru.json +2 -0
  156. package/dist/localization/package.nls.tr.json +2 -0
  157. package/dist/localization/package.nls.zh-cn.json +2 -0
  158. package/dist/localization/package.nls.zh-tw.json +2 -0
  159. package/dist/pyrightServer.d.ts +34 -0
  160. package/dist/pyrightServer.js +239 -0
  161. package/dist/pyrightServer.js.map +1 -0
  162. package/dist/server.d.ts +3 -23
  163. package/dist/server.js +12 -232
  164. package/dist/server.js.map +1 -1
  165. package/dist/tests/benchmarks/typeInferenceComparison.d.ts +1 -0
  166. package/dist/tests/benchmarks/typeInferenceComparison.js +1235 -0
  167. package/dist/tests/benchmarks/typeInferenceComparison.js.map +1 -0
  168. package/dist/tests/benchmarks/typeInferencePyrightEntry.d.ts +1 -0
  169. package/dist/tests/benchmarks/typeInferencePyrightEntry.js +53 -0
  170. package/dist/tests/benchmarks/typeInferencePyrightEntry.js.map +1 -0
  171. package/dist/tests/browserCancellation.test.d.ts +1 -0
  172. package/dist/tests/browserCancellation.test.js +63 -0
  173. package/dist/tests/browserCancellation.test.js.map +1 -0
  174. package/dist/tests/browserServer.test.d.ts +1 -0
  175. package/dist/tests/browserServer.test.js +177 -0
  176. package/dist/tests/browserServer.test.js.map +1 -0
  177. package/dist/tests/constraintSolver.test.js +45 -0
  178. package/dist/tests/constraintSolver.test.js.map +1 -1
  179. package/dist/tests/mypyPrimerAnalysis.test.js +15 -1
  180. package/dist/tests/mypyPrimerAnalysis.test.js.map +1 -1
  181. package/dist/tests/signatureHelp.test.js +22 -0
  182. package/dist/tests/signatureHelp.test.js.map +1 -1
  183. package/dist/tests/typeCacheUtils.test.js +46 -0
  184. package/dist/tests/typeCacheUtils.test.js.map +1 -1
  185. package/dist/tests/typeEvaluator1.test.js +108 -0
  186. package/dist/tests/typeEvaluator1.test.js.map +1 -1
  187. package/dist/tests/typeEvaluator2.test.js +14 -0
  188. package/dist/tests/typeEvaluator2.test.js.map +1 -1
  189. package/dist/tests/typeEvaluator3.test.js +20 -0
  190. package/dist/tests/typeEvaluator3.test.js.map +1 -1
  191. package/dist/tests/typeEvaluator4.test.js +32 -0
  192. package/dist/tests/typeEvaluator4.test.js.map +1 -1
  193. package/dist/tests/typeEvaluator5.test.js +7 -1
  194. package/dist/tests/typeEvaluator5.test.js.map +1 -1
  195. package/dist/tests/typeEvaluator6.test.js +4 -0
  196. package/dist/tests/typeEvaluator6.test.js.map +1 -1
  197. package/dist/tests/typeEvaluator7.test.js +600 -1
  198. package/dist/tests/typeEvaluator7.test.js.map +1 -1
  199. package/dist/tests/typeEvaluator8.test.js +46 -0
  200. package/dist/tests/typeEvaluator8.test.js.map +1 -1
  201. package/dist/tests/typeUtils.test.js +28 -0
  202. package/dist/tests/typeUtils.test.js.map +1 -1
  203. package/dist/typeServer/stubGenerator.js +136 -3
  204. package/dist/typeServer/stubGenerator.js.map +1 -1
  205. package/dist/typeServer/typeServerConversionUtils.js +13 -0
  206. package/dist/typeServer/typeServerConversionUtils.js.map +1 -1
  207. package/package.json +3 -1
@@ -0,0 +1,1763 @@
1
+ "use strict";
2
+ /*
3
+ * typeGuardNarrowing.ts
4
+ * Copyright (c) Microsoft Corporation.
5
+ * Licensed under the MIT license.
6
+ *
7
+ * Helper logic shared by type narrowing entry points.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.getNoneEllipsisNarrowingInfo = getNoneEllipsisNarrowingInfo;
11
+ exports.getTypeIsCallNarrowingInfo = getTypeIsCallNarrowingInfo;
12
+ exports.getIsLiteralOrClassNarrowingInfo = getIsLiteralOrClassNarrowingInfo;
13
+ exports.getIndexedLiteralNarrowingInfo = getIndexedLiteralNarrowingInfo;
14
+ exports.getIsInstanceCallNarrowingInfo = getIsInstanceCallNarrowingInfo;
15
+ exports.getBoolCallNarrowingInfo = getBoolCallNarrowingInfo;
16
+ exports.getNotExpressionNarrowingInfo = getNotExpressionNarrowingInfo;
17
+ exports.getEqualsNarrowingInfo = getEqualsNarrowingInfo;
18
+ exports.getMemberAccessNarrowingInfo = getMemberAccessNarrowingInfo;
19
+ exports.getLenComparisonNarrowingInfo = getLenComparisonNarrowingInfo;
20
+ exports.getInOperatorNarrowingInfo = getInOperatorNarrowingInfo;
21
+ exports.narrowTypeForTruthiness = narrowTypeForTruthiness;
22
+ exports.narrowTupleTypeForIsNone = narrowTupleTypeForIsNone;
23
+ exports.narrowTypeForIsNone = narrowTypeForIsNone;
24
+ exports.narrowTypeForIsEllipsis = narrowTypeForIsEllipsis;
25
+ exports.getIsInstanceClassTypes = getIsInstanceClassTypes;
26
+ exports.narrowTypeForInstanceOrSubclass = narrowTypeForInstanceOrSubclass;
27
+ exports.narrowTypeForTupleLength = narrowTypeForTupleLength;
28
+ exports.narrowTypeForContainerType = narrowTypeForContainerType;
29
+ exports.getElementTypeForContainerNarrowing = getElementTypeForContainerNarrowing;
30
+ exports.narrowTypeForContainerElementType = narrowTypeForContainerElementType;
31
+ exports.narrowTypeForTypedDictKey = narrowTypeForTypedDictKey;
32
+ exports.narrowTypeForDiscriminatedDictEntryComparison = narrowTypeForDiscriminatedDictEntryComparison;
33
+ exports.narrowTypeForDiscriminatedTupleComparison = narrowTypeForDiscriminatedTupleComparison;
34
+ exports.narrowTypeForDiscriminatedLiteralFieldComparison = narrowTypeForDiscriminatedLiteralFieldComparison;
35
+ exports.narrowTypeForDiscriminatedFieldNoneComparison = narrowTypeForDiscriminatedFieldNoneComparison;
36
+ exports.narrowTypeForTypeIs = narrowTypeForTypeIs;
37
+ exports.narrowTypeForClassComparison = narrowTypeForClassComparison;
38
+ exports.narrowTypeForLiteralComparison = narrowTypeForLiteralComparison;
39
+ exports.enumerateLiteralsForType = enumerateLiteralsForType;
40
+ exports.isNameSameScope = isNameSameScope;
41
+ exports.narrowTypeForUserDefinedTypeGuard = narrowTypeForUserDefinedTypeGuard;
42
+ const debug_1 = require("../../common/debug");
43
+ const analyzerNodeInfo_1 = require("../analyzerNodeInfo");
44
+ const constraintTracker_1 = require("../constraintTracker");
45
+ const enums_1 = require("../enums");
46
+ const operations_1 = require("../operations");
47
+ const scopeUtils_1 = require("../scopeUtils");
48
+ const typedDicts_1 = require("../typedDicts");
49
+ const types_1 = require("../types");
50
+ const typeUtils_1 = require("../typeUtils");
51
+ function getNoneEllipsisNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
52
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */) {
53
+ return undefined;
54
+ }
55
+ const isOrIsNotOperator = testExpression.d.operator === 39 /* OperatorType.Is */ || testExpression.d.operator === 40 /* OperatorType.IsNot */;
56
+ const equalsOrNotEqualsOperator = testExpression.d.operator === 12 /* OperatorType.Equals */ || testExpression.d.operator === 28 /* OperatorType.NotEquals */;
57
+ if (!isOrIsNotOperator && !equalsOrNotEqualsOperator) {
58
+ return undefined;
59
+ }
60
+ const adjIsPositiveTest = testExpression.d.operator === 39 /* OperatorType.Is */ || testExpression.d.operator === 12 /* OperatorType.Equals */
61
+ ? isPositiveTest
62
+ : !isPositiveTest;
63
+ if (testExpression.d.rightExpr.nodeType === 14 /* ParseNodeType.Constant */ &&
64
+ testExpression.d.rightExpr.d.constType === 27 /* KeywordType.None */) {
65
+ if (ctx.isMatchingExpressionOrWalrusRhs(reference, testExpression.d.leftExpr)) {
66
+ return { kind: 'none', adjIsPositiveTest };
67
+ }
68
+ const leftExpression = testExpression.d.leftExpr;
69
+ if (leftExpression.nodeType === 27 /* ParseNodeType.Index */ &&
70
+ ctx.isMatchingExpression(reference, leftExpression.d.leftExpr) &&
71
+ leftExpression.d.items.length === 1 &&
72
+ !leftExpression.d.trailingComma &&
73
+ leftExpression.d.items[0].d.argCategory === 0 /* ArgCategory.Simple */ &&
74
+ !leftExpression.d.items[0].d.name &&
75
+ leftExpression.d.items[0].d.valueExpr.nodeType === 40 /* ParseNodeType.Number */ &&
76
+ leftExpression.d.items[0].d.valueExpr.d.isInteger &&
77
+ !leftExpression.d.items[0].d.valueExpr.d.isImaginary) {
78
+ const indexValue = leftExpression.d.items[0].d.valueExpr.d.value;
79
+ if (typeof indexValue === 'number') {
80
+ return { kind: 'tuple-none', adjIsPositiveTest, tupleIndex: indexValue };
81
+ }
82
+ }
83
+ }
84
+ if (testExpression.d.rightExpr.nodeType === 21 /* ParseNodeType.Ellipsis */ &&
85
+ ctx.isMatchingExpressionOrWalrusRhs(reference, testExpression.d.leftExpr)) {
86
+ return { kind: 'ellipsis', adjIsPositiveTest };
87
+ }
88
+ return undefined;
89
+ }
90
+ function isTypeCallBase(callType) {
91
+ return (0, types_1.isInstantiableClass)(callType) && types_1.ClassType.isBuiltIn(callType, 'type');
92
+ }
93
+ function getTypeIsCallNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
94
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */) {
95
+ return undefined;
96
+ }
97
+ const isOrIsNotOperator = testExpression.d.operator === 39 /* OperatorType.Is */ || testExpression.d.operator === 40 /* OperatorType.IsNot */;
98
+ const equalsOrNotEqualsOperator = testExpression.d.operator === 12 /* OperatorType.Equals */ || testExpression.d.operator === 28 /* OperatorType.NotEquals */;
99
+ if (!isOrIsNotOperator && !equalsOrNotEqualsOperator) {
100
+ return undefined;
101
+ }
102
+ const adjIsPositiveTest = testExpression.d.operator === 39 /* OperatorType.Is */ || testExpression.d.operator === 12 /* OperatorType.Equals */
103
+ ? isPositiveTest
104
+ : !isPositiveTest;
105
+ let typeCallNode;
106
+ let otherExpr;
107
+ const isTypeCall = (expr, referenceExpr) => expr.nodeType === 9 /* ParseNodeType.Call */ &&
108
+ expr.d.args.length === 1 &&
109
+ expr.d.args[0].d.argCategory === 0 /* ArgCategory.Simple */ &&
110
+ (!referenceExpr || ctx.isMatchingExpressionOrWalrusRhs(referenceExpr, expr.d.args[0].d.valueExpr)) &&
111
+ isTypeCallBase(ctx.getTypeOfExpression(expr.d.leftExpr, 2 /* EvalFlags.CallBaseDefaults */).type);
112
+ if (isTypeCall(testExpression.d.leftExpr, reference)) {
113
+ typeCallNode = testExpression.d.leftExpr;
114
+ otherExpr = testExpression.d.rightExpr;
115
+ }
116
+ else if (isTypeCall(testExpression.d.rightExpr, reference)) {
117
+ typeCallNode = testExpression.d.rightExpr;
118
+ otherExpr = testExpression.d.leftExpr;
119
+ }
120
+ if (!typeCallNode || !otherExpr) {
121
+ return undefined;
122
+ }
123
+ const otherResult = ctx.getTypeOfExpression(otherExpr);
124
+ const classTypes = [];
125
+ let isClassType = true;
126
+ let classTypeVar;
127
+ if ((0, types_1.isTypeVar)(otherResult.type) && types_1.TypeBase.isInstantiable(otherResult.type)) {
128
+ classTypeVar = (0, typeUtils_1.convertToInstance)(otherResult.type);
129
+ }
130
+ else if ((0, types_1.isClassInstance)(otherResult.type) &&
131
+ types_1.ClassType.isBuiltIn(otherResult.type, 'type') &&
132
+ otherResult.type.priv.typeArgs?.length === 1 &&
133
+ (0, types_1.isTypeVar)(otherResult.type.priv.typeArgs[0])) {
134
+ classTypeVar = otherResult.type.priv.typeArgs[0];
135
+ }
136
+ ctx.mapSubtypesExpandTypeVars(otherResult.type, (expandedSubtype) => {
137
+ let instantiable;
138
+ if ((0, types_1.isClass)(expandedSubtype)) {
139
+ if ((0, types_1.isClassInstance)(expandedSubtype) &&
140
+ types_1.ClassType.isBuiltIn(expandedSubtype, 'type') &&
141
+ expandedSubtype.priv.typeArgs &&
142
+ expandedSubtype.priv.typeArgs.length > 0) {
143
+ const extracted = expandedSubtype.priv.typeArgs[0];
144
+ if ((0, types_1.isInstantiableClass)(extracted)) {
145
+ instantiable = extracted;
146
+ }
147
+ }
148
+ else if ((0, types_1.isInstantiableClass)(expandedSubtype)) {
149
+ instantiable = expandedSubtype;
150
+ }
151
+ }
152
+ if (instantiable) {
153
+ classTypes.push(instantiable);
154
+ }
155
+ else {
156
+ isClassType = false;
157
+ }
158
+ return undefined;
159
+ });
160
+ if (!isClassType || classTypes.length === 0) {
161
+ return undefined;
162
+ }
163
+ const allowLegacyEquality = !isOrIsNotOperator &&
164
+ typeCallNode === testExpression.d.leftExpr &&
165
+ (((0, types_1.isInstantiableClass)(otherResult.type) &&
166
+ !otherResult.type.priv.includeSubclasses &&
167
+ !otherResult.type.priv.isTypeArgExplicit) ||
168
+ isTypeCall(otherExpr));
169
+ return {
170
+ classTypes,
171
+ classTypeVar,
172
+ adjIsPositiveTest,
173
+ isOrIsNotOperator,
174
+ allowLegacyEquality,
175
+ // Attribute and index reads can invoke a different getter each time.
176
+ allowExactStringFlow: reference.nodeType === 38 /* ParseNodeType.Name */,
177
+ isIncomplete: !!otherResult.isIncomplete,
178
+ };
179
+ }
180
+ function getIsLiteralOrClassNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
181
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */) {
182
+ return undefined;
183
+ }
184
+ if (testExpression.d.operator !== 39 /* OperatorType.Is */ && testExpression.d.operator !== 40 /* OperatorType.IsNot */) {
185
+ return undefined;
186
+ }
187
+ if (!ctx.isMatchingExpressionOrWalrusRhs(reference, testExpression.d.leftExpr)) {
188
+ return undefined;
189
+ }
190
+ const adjIsPositiveTest = testExpression.d.operator === 39 /* OperatorType.Is */ ? isPositiveTest : !isPositiveTest;
191
+ const rightTypeResult = ctx.getTypeOfExpression(testExpression.d.rightExpr);
192
+ const rightType = rightTypeResult.type;
193
+ if ((0, types_1.isClassInstance)(rightType) && rightType.priv.literalValue !== undefined) {
194
+ return {
195
+ kind: 'literal',
196
+ rightType,
197
+ adjIsPositiveTest,
198
+ isIncomplete: !!rightTypeResult.isIncomplete,
199
+ };
200
+ }
201
+ if ((0, types_1.isInstantiableClass)(rightType)) {
202
+ return {
203
+ kind: 'class',
204
+ rightType,
205
+ adjIsPositiveTest,
206
+ isIncomplete: !!rightTypeResult.isIncomplete,
207
+ };
208
+ }
209
+ return undefined;
210
+ }
211
+ function getIndexedLiteralNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
212
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */) {
213
+ return undefined;
214
+ }
215
+ if (testExpression.d.operator !== 39 /* OperatorType.Is */ && testExpression.d.operator !== 40 /* OperatorType.IsNot */) {
216
+ return undefined;
217
+ }
218
+ if (testExpression.d.leftExpr.nodeType !== 27 /* ParseNodeType.Index */ ||
219
+ testExpression.d.leftExpr.d.items.length !== 1 ||
220
+ testExpression.d.leftExpr.d.trailingComma ||
221
+ testExpression.d.leftExpr.d.items[0].d.argCategory !== 0 /* ArgCategory.Simple */ ||
222
+ !ctx.isMatchingExpression(reference, testExpression.d.leftExpr.d.leftExpr)) {
223
+ return undefined;
224
+ }
225
+ const indexTypeResult = ctx.getTypeOfExpression(testExpression.d.leftExpr.d.items[0].d.valueExpr);
226
+ const indexType = indexTypeResult.type;
227
+ if (!(0, types_1.isClassInstance)(indexType) || !(0, typeUtils_1.isLiteralType)(indexType)) {
228
+ return undefined;
229
+ }
230
+ const rightTypeResult = ctx.getTypeOfExpression(testExpression.d.rightExpr);
231
+ const rightType = rightTypeResult.type;
232
+ if (!(0, types_1.isClassInstance)(rightType) || rightType.priv.literalValue === undefined) {
233
+ return undefined;
234
+ }
235
+ const adjIsPositiveTest = testExpression.d.operator === 39 /* OperatorType.Is */ ? isPositiveTest : !isPositiveTest;
236
+ if (types_1.ClassType.isBuiltIn(indexType, 'str')) {
237
+ return {
238
+ kind: 'dict',
239
+ indexType,
240
+ rightType,
241
+ adjIsPositiveTest,
242
+ isIncomplete: !!indexTypeResult.isIncomplete,
243
+ };
244
+ }
245
+ if (types_1.ClassType.isBuiltIn(indexType, 'int')) {
246
+ let canNarrow = false;
247
+ if (types_1.ClassType.isBuiltIn(rightType, 'bool')) {
248
+ canNarrow = true;
249
+ }
250
+ else if (rightType.priv.literalValue instanceof types_1.EnumLiteral) {
251
+ canNarrow = true;
252
+ }
253
+ if (canNarrow) {
254
+ return {
255
+ kind: 'tuple',
256
+ indexType,
257
+ rightType,
258
+ adjIsPositiveTest,
259
+ isIncomplete: !!rightTypeResult.isIncomplete,
260
+ };
261
+ }
262
+ }
263
+ return undefined;
264
+ }
265
+ function getIsInstanceCallNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
266
+ if (testExpression.nodeType !== 9 /* ParseNodeType.Call */ || testExpression.d.args.length !== 2) {
267
+ return undefined;
268
+ }
269
+ const arg0Expr = testExpression.d.args[0].d.valueExpr;
270
+ const arg1Expr = testExpression.d.args[1].d.valueExpr;
271
+ if (!ctx.isMatchingExpressionOrWalrusRhs(reference, arg0Expr)) {
272
+ return undefined;
273
+ }
274
+ const callTypeResult = ctx.getTypeOfExpression(testExpression.d.leftExpr, 2 /* EvalFlags.CallBaseDefaults */);
275
+ const callType = callTypeResult.type;
276
+ if (!(0, types_1.isFunction)(callType) || !types_1.FunctionType.isBuiltIn(callType, ['isinstance', 'issubclass'])) {
277
+ return undefined;
278
+ }
279
+ const isInstanceCheck = types_1.FunctionType.isBuiltIn(callType, 'isinstance');
280
+ const arg1TypeResult = ctx.getTypeOfExpression(arg1Expr, 536871546 /* EvalFlags.IsInstanceArgDefaults */);
281
+ const classTypeInfo = ctx.getIsInstanceClassTypes(arg1TypeResult.type, arg1Expr);
282
+ const isIncomplete = !!callTypeResult.isIncomplete || !!arg1TypeResult.isIncomplete;
283
+ if (classTypeInfo) {
284
+ return {
285
+ kind: 'narrow',
286
+ classTypeList: isPositiveTest ? classTypeInfo.classTypes : classTypeInfo.negativeClassTypes,
287
+ isInstanceCheck,
288
+ isIncomplete,
289
+ };
290
+ }
291
+ if (isIncomplete) {
292
+ return { kind: 'incomplete', isIncomplete: true };
293
+ }
294
+ return undefined;
295
+ }
296
+ function getBoolCallNarrowingInfo(ctx, reference, testExpression) {
297
+ if (testExpression.nodeType !== 9 /* ParseNodeType.Call */ ||
298
+ testExpression.d.args.length !== 1 ||
299
+ testExpression.d.args[0].d.name) {
300
+ return undefined;
301
+ }
302
+ if (!ctx.isMatchingExpressionOrWalrusRhs(reference, testExpression.d.args[0].d.valueExpr)) {
303
+ return undefined;
304
+ }
305
+ const callTypeResult = ctx.getTypeOfExpression(testExpression.d.leftExpr, 2 /* EvalFlags.CallBaseDefaults */);
306
+ const callType = callTypeResult.type;
307
+ if ((0, types_1.isInstantiableClass)(callType) && types_1.ClassType.isBuiltIn(callType, 'bool')) {
308
+ return { isIncomplete: !!callTypeResult.isIncomplete };
309
+ }
310
+ return undefined;
311
+ }
312
+ function getNotExpressionNarrowingInfo(reference, testExpression, isPositiveTest) {
313
+ if (testExpression.nodeType === 55 /* ParseNodeType.UnaryOperation */ &&
314
+ testExpression.d.operator === 38 /* OperatorType.Not */ &&
315
+ reference !== testExpression) {
316
+ return {
317
+ innerExpression: testExpression.d.expr,
318
+ adjIsPositiveTest: !isPositiveTest,
319
+ };
320
+ }
321
+ return undefined;
322
+ }
323
+ function getEqualsNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
324
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */) {
325
+ return undefined;
326
+ }
327
+ const equalsOrNotEqualsOperator = testExpression.d.operator === 12 /* OperatorType.Equals */ || testExpression.d.operator === 28 /* OperatorType.NotEquals */;
328
+ if (!equalsOrNotEqualsOperator) {
329
+ return undefined;
330
+ }
331
+ const adjIsPositiveTest = testExpression.d.operator === 12 /* OperatorType.Equals */ ? isPositiveTest : !isPositiveTest;
332
+ if (ctx.isMatchingExpressionOrWalrusRhs(reference, testExpression.d.leftExpr)) {
333
+ const rightTypeResult = ctx.getTypeOfExpression(testExpression.d.rightExpr);
334
+ const rightType = rightTypeResult.type;
335
+ if ((0, types_1.isClassInstance)(rightType) && rightType.priv.literalValue !== undefined) {
336
+ return {
337
+ kind: 'literal',
338
+ rightType,
339
+ adjIsPositiveTest,
340
+ isIncomplete: !!rightTypeResult.isIncomplete,
341
+ };
342
+ }
343
+ if ((0, types_1.isInstantiableClass)(rightType)) {
344
+ return {
345
+ kind: 'class',
346
+ rightType,
347
+ adjIsPositiveTest,
348
+ isIncomplete: !!rightTypeResult.isIncomplete,
349
+ };
350
+ }
351
+ }
352
+ if (testExpression.d.leftExpr.nodeType === 27 /* ParseNodeType.Index */ &&
353
+ testExpression.d.leftExpr.d.items.length === 1 &&
354
+ !testExpression.d.leftExpr.d.trailingComma &&
355
+ testExpression.d.leftExpr.d.items[0].d.argCategory === 0 /* ArgCategory.Simple */ &&
356
+ ctx.isMatchingExpression(reference, testExpression.d.leftExpr.d.leftExpr)) {
357
+ const indexTypeResult = ctx.getTypeOfExpression(testExpression.d.leftExpr.d.items[0].d.valueExpr);
358
+ const indexType = indexTypeResult.type;
359
+ if ((0, types_1.isClassInstance)(indexType) && (0, typeUtils_1.isLiteralType)(indexType) && types_1.ClassType.isBuiltIn(indexType, ['str', 'int'])) {
360
+ const rightTypeResult = ctx.getTypeOfExpression(testExpression.d.rightExpr);
361
+ const rightType = rightTypeResult.type;
362
+ if ((0, typeUtils_1.isLiteralTypeOrUnion)(rightType)) {
363
+ return {
364
+ kind: 'index',
365
+ indexType,
366
+ rightType,
367
+ adjIsPositiveTest,
368
+ isIncomplete: !!indexTypeResult.isIncomplete || !!rightTypeResult.isIncomplete,
369
+ };
370
+ }
371
+ }
372
+ }
373
+ return undefined;
374
+ }
375
+ function getMemberAccessNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
376
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */) {
377
+ return undefined;
378
+ }
379
+ const isOrIsNotOperator = testExpression.d.operator === 39 /* OperatorType.Is */ || testExpression.d.operator === 40 /* OperatorType.IsNot */;
380
+ const equalsOrNotEqualsOperator = testExpression.d.operator === 12 /* OperatorType.Equals */ || testExpression.d.operator === 28 /* OperatorType.NotEquals */;
381
+ if (!isOrIsNotOperator && !equalsOrNotEqualsOperator) {
382
+ return undefined;
383
+ }
384
+ if (testExpression.d.leftExpr.nodeType !== 35 /* ParseNodeType.MemberAccess */ ||
385
+ !ctx.isMatchingExpression(reference, testExpression.d.leftExpr.d.leftExpr)) {
386
+ return undefined;
387
+ }
388
+ const adjIsPositiveTest = testExpression.d.operator === 39 /* OperatorType.Is */ || testExpression.d.operator === 12 /* OperatorType.Equals */
389
+ ? isPositiveTest
390
+ : !isPositiveTest;
391
+ if (isOrIsNotOperator &&
392
+ testExpression.d.rightExpr.nodeType === 14 /* ParseNodeType.Constant */ &&
393
+ testExpression.d.rightExpr.d.constType === 27 /* KeywordType.None */) {
394
+ return {
395
+ kind: 'none',
396
+ memberName: testExpression.d.leftExpr.d.member.d.value,
397
+ adjIsPositiveTest,
398
+ isIncomplete: false,
399
+ };
400
+ }
401
+ const rightTypeResult = ctx.getTypeOfExpression(testExpression.d.rightExpr);
402
+ const rightType = rightTypeResult.type;
403
+ if ((0, types_1.isClassInstance)(rightType)) {
404
+ const isLiteralEqualsCase = equalsOrNotEqualsOperator && (rightType.priv.literalValue !== undefined || (0, typeUtils_1.isNoneInstance)(rightType));
405
+ const isLiteralIdentityCase = isOrIsNotOperator &&
406
+ (types_1.ClassType.isEnumClass(rightType) || types_1.ClassType.isBuiltIn(rightType, 'bool')) &&
407
+ rightType.priv.literalValue !== undefined;
408
+ if (isLiteralEqualsCase || isLiteralIdentityCase) {
409
+ return {
410
+ kind: 'literal',
411
+ memberName: testExpression.d.leftExpr.d.member.d.value,
412
+ rightType,
413
+ adjIsPositiveTest,
414
+ isIncomplete: !!rightTypeResult.isIncomplete,
415
+ };
416
+ }
417
+ }
418
+ return undefined;
419
+ }
420
+ function getLenComparisonNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
421
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */) {
422
+ return undefined;
423
+ }
424
+ const comparisonOperator = testExpression.d.operator === 12 /* OperatorType.Equals */ ||
425
+ testExpression.d.operator === 28 /* OperatorType.NotEquals */ ||
426
+ testExpression.d.operator === 20 /* OperatorType.LessThan */ ||
427
+ testExpression.d.operator === 21 /* OperatorType.LessThanOrEqual */ ||
428
+ testExpression.d.operator === 15 /* OperatorType.GreaterThan */ ||
429
+ testExpression.d.operator === 16 /* OperatorType.GreaterThanOrEqual */;
430
+ if (!comparisonOperator ||
431
+ testExpression.d.leftExpr.nodeType !== 9 /* ParseNodeType.Call */ ||
432
+ testExpression.d.leftExpr.d.args.length !== 1) {
433
+ return undefined;
434
+ }
435
+ const arg0Expr = testExpression.d.leftExpr.d.args[0].d.valueExpr;
436
+ if (!ctx.isMatchingExpression(reference, arg0Expr)) {
437
+ return undefined;
438
+ }
439
+ const callTypeResult = ctx.getTypeOfExpression(testExpression.d.leftExpr.d.leftExpr, 2 /* EvalFlags.CallBaseDefaults */);
440
+ const callType = callTypeResult.type;
441
+ if (!(0, types_1.isFunction)(callType) || callType.shared.fullName !== 'builtins.len') {
442
+ return undefined;
443
+ }
444
+ const rightTypeResult = ctx.getTypeOfExpression(testExpression.d.rightExpr);
445
+ const rightType = rightTypeResult.type;
446
+ if (!(0, types_1.isClassInstance)(rightType) ||
447
+ typeof rightType.priv.literalValue !== 'number' ||
448
+ rightType.priv.literalValue < 0) {
449
+ return undefined;
450
+ }
451
+ let tupleLength = rightType.priv.literalValue;
452
+ const isLessOrEqual = testExpression.d.operator === 12 /* OperatorType.Equals */ ||
453
+ testExpression.d.operator === 20 /* OperatorType.LessThan */ ||
454
+ testExpression.d.operator === 21 /* OperatorType.LessThanOrEqual */;
455
+ const adjIsPositiveTest = isLessOrEqual ? isPositiveTest : !isPositiveTest;
456
+ if (testExpression.d.operator === 21 /* OperatorType.LessThanOrEqual */ ||
457
+ testExpression.d.operator === 15 /* OperatorType.GreaterThan */) {
458
+ tupleLength++;
459
+ }
460
+ const isEqualityCheck = testExpression.d.operator === 12 /* OperatorType.Equals */ || testExpression.d.operator === 28 /* OperatorType.NotEquals */;
461
+ return {
462
+ tupleLength,
463
+ adjIsPositiveTest,
464
+ isLessThanCheck: !isEqualityCheck,
465
+ isIncomplete: !!callTypeResult.isIncomplete || !!rightTypeResult.isIncomplete,
466
+ };
467
+ }
468
+ function getInOperatorNarrowingInfo(ctx, reference, testExpression, isPositiveTest) {
469
+ if (testExpression.nodeType !== 7 /* ParseNodeType.BinaryOperation */ ||
470
+ (testExpression.d.operator !== 41 /* OperatorType.In */ && testExpression.d.operator !== 42 /* OperatorType.NotIn */)) {
471
+ return undefined;
472
+ }
473
+ const adjIsPositiveTest = testExpression.d.operator === 41 /* OperatorType.In */ ? isPositiveTest : !isPositiveTest;
474
+ if (ctx.isMatchingExpressionOrWalrusRhs(reference, testExpression.d.leftExpr)) {
475
+ const rightTypeResult = ctx.getTypeOfExpression(testExpression.d.rightExpr);
476
+ return {
477
+ kind: 'container',
478
+ containerType: rightTypeResult.type,
479
+ adjIsPositiveTest,
480
+ isIncomplete: !!rightTypeResult.isIncomplete,
481
+ };
482
+ }
483
+ if (ctx.isMatchingExpression(reference, testExpression.d.rightExpr)) {
484
+ const leftTypeResult = ctx.getTypeOfExpression(testExpression.d.leftExpr);
485
+ const leftType = leftTypeResult.type;
486
+ if ((0, types_1.isClassInstance)(leftType) && types_1.ClassType.isBuiltIn(leftType, 'str') && (0, typeUtils_1.isLiteralType)(leftType)) {
487
+ return {
488
+ kind: 'typedDictKey',
489
+ typedDictKeyType: types_1.ClassType.cloneAsInstantiable(leftType),
490
+ adjIsPositiveTest,
491
+ isIncomplete: !!leftTypeResult.isIncomplete,
492
+ };
493
+ }
494
+ }
495
+ return undefined;
496
+ return undefined;
497
+ }
498
+ function narrowTypeForTruthiness(evaluator, type, isPositiveTest) {
499
+ return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
500
+ if (isPositiveTest) {
501
+ if (evaluator.canBeTruthy(subtype)) {
502
+ return evaluator.removeFalsinessFromType(subtype);
503
+ }
504
+ }
505
+ else {
506
+ if (evaluator.canBeFalsy(subtype)) {
507
+ return evaluator.removeTruthinessFromType(subtype);
508
+ }
509
+ }
510
+ return undefined;
511
+ });
512
+ }
513
+ function narrowTupleTypeForIsNone(evaluator, type, isPositiveTest, indexValue) {
514
+ return evaluator.mapSubtypesExpandTypeVars(type, /* options */ undefined, (subtype) => {
515
+ const tupleType = (0, typeUtils_1.getSpecializedTupleType)(subtype);
516
+ if (!tupleType || (0, typeUtils_1.isUnboundedTupleClass)(tupleType) || !tupleType.priv.tupleTypeArgs) {
517
+ return subtype;
518
+ }
519
+ const tupleLength = tupleType.priv.tupleTypeArgs.length;
520
+ if (indexValue < 0 || indexValue >= tupleLength) {
521
+ return subtype;
522
+ }
523
+ const typeOfEntry = evaluator.makeTopLevelTypeVarsConcrete(tupleType.priv.tupleTypeArgs[indexValue].type);
524
+ if (isPositiveTest) {
525
+ if (!evaluator.assignType(typeOfEntry, evaluator.getNoneType())) {
526
+ return undefined;
527
+ }
528
+ }
529
+ else {
530
+ if ((0, typeUtils_1.isNoneInstance)(typeOfEntry)) {
531
+ return undefined;
532
+ }
533
+ }
534
+ return subtype;
535
+ });
536
+ }
537
+ function narrowTypeForIsNone(evaluator, type, isPositiveTest) {
538
+ const expandedType = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
539
+ return (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(subtype);
540
+ });
541
+ let resultIncludesNoneSubtype = false;
542
+ const result = evaluator.mapSubtypesExpandTypeVars(expandedType,
543
+ /* options */ undefined, (subtype, unexpandedSubtype) => {
544
+ if ((0, types_1.isAnyOrUnknown)(subtype)) {
545
+ if (isPositiveTest) {
546
+ resultIncludesNoneSubtype = true;
547
+ return (0, typeUtils_1.addConditionToType)(evaluator.getNoneType(), subtype.props?.condition);
548
+ }
549
+ return subtype;
550
+ }
551
+ let useExpandedSubtype = false;
552
+ if ((0, types_1.isTypeVar)(unexpandedSubtype) && !types_1.TypeVarType.isSelf(unexpandedSubtype)) {
553
+ if (unexpandedSubtype.shared.constraints.some((constraint) => {
554
+ return evaluator.assignType(constraint, evaluator.getNoneType());
555
+ })) {
556
+ useExpandedSubtype = true;
557
+ }
558
+ if (unexpandedSubtype.shared.boundType &&
559
+ evaluator.assignType(unexpandedSubtype.shared.boundType, evaluator.getNoneType())) {
560
+ useExpandedSubtype = true;
561
+ }
562
+ }
563
+ const adjustedSubtype = useExpandedSubtype ? subtype : unexpandedSubtype;
564
+ const newTypeBaseInstance = getInnermostNewTypeBaseInstance(adjustedSubtype);
565
+ if (newTypeBaseInstance && (0, typeUtils_1.isNoneInstance)(newTypeBaseInstance)) {
566
+ resultIncludesNoneSubtype = true;
567
+ return isPositiveTest ? adjustedSubtype : undefined;
568
+ }
569
+ if ((0, typeUtils_1.isNoneInstance)(subtype)) {
570
+ resultIncludesNoneSubtype = true;
571
+ return isPositiveTest ? adjustedSubtype : undefined;
572
+ }
573
+ if (evaluator.assignType(subtype, evaluator.getNoneType())) {
574
+ resultIncludesNoneSubtype = true;
575
+ return isPositiveTest
576
+ ? (0, typeUtils_1.addConditionToType)(evaluator.getNoneType(), subtype.props?.condition)
577
+ : adjustedSubtype;
578
+ }
579
+ return isPositiveTest ? undefined : adjustedSubtype;
580
+ });
581
+ if (isPositiveTest && resultIncludesNoneSubtype) {
582
+ return (0, typeUtils_1.mapSubtypes)(result, (subtype) => {
583
+ const baseInstance = getInnermostNewTypeBaseInstance(subtype);
584
+ return (0, typeUtils_1.isNoneInstance)(subtype) || (baseInstance && (0, typeUtils_1.isNoneInstance)(baseInstance)) ? subtype : undefined;
585
+ });
586
+ }
587
+ return result;
588
+ }
589
+ function narrowTypeForIsEllipsis(evaluator, node, type, isPositiveTest) {
590
+ const expandedType = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
591
+ return (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(subtype);
592
+ });
593
+ let resultIncludesEllipsisSubtype = false;
594
+ const ellipsisType = evaluator.getBuiltInObject(node, 'EllipsisType') ??
595
+ evaluator.getBuiltInObject(node, 'ellipsis') ??
596
+ types_1.AnyType.create();
597
+ const isEllipsisInstance = (subtype) => {
598
+ return (0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, ['EllipsisType', 'ellipsis']);
599
+ };
600
+ const result = evaluator.mapSubtypesExpandTypeVars(expandedType,
601
+ /* options */ undefined, (subtype, unexpandedSubtype) => {
602
+ if ((0, types_1.isAnyOrUnknown)(subtype)) {
603
+ return subtype;
604
+ }
605
+ const adjustedSubtype = (0, types_1.isTypeVar)(unexpandedSubtype) && !types_1.TypeVarType.hasConstraints(unexpandedSubtype)
606
+ ? unexpandedSubtype
607
+ : subtype;
608
+ const newTypeBaseInstance = getInnermostNewTypeBaseInstance(adjustedSubtype);
609
+ if (newTypeBaseInstance && isEllipsisInstance(newTypeBaseInstance)) {
610
+ resultIncludesEllipsisSubtype = true;
611
+ return isPositiveTest ? adjustedSubtype : undefined;
612
+ }
613
+ if (isEllipsisInstance(subtype)) {
614
+ resultIncludesEllipsisSubtype = true;
615
+ return isPositiveTest ? adjustedSubtype : undefined;
616
+ }
617
+ if (evaluator.assignType(subtype, ellipsisType)) {
618
+ resultIncludesEllipsisSubtype = true;
619
+ return isPositiveTest ? (0, typeUtils_1.addConditionToType)(ellipsisType, subtype.props?.condition) : adjustedSubtype;
620
+ }
621
+ return isPositiveTest ? undefined : adjustedSubtype;
622
+ });
623
+ if (isPositiveTest && resultIncludesEllipsisSubtype) {
624
+ return (0, typeUtils_1.mapSubtypes)(result, (subtype) => {
625
+ const baseInstance = getInnermostNewTypeBaseInstance(subtype);
626
+ return isEllipsisInstance(subtype) || (baseInstance && isEllipsisInstance(baseInstance))
627
+ ? subtype
628
+ : undefined;
629
+ });
630
+ }
631
+ return result;
632
+ }
633
+ function getIsInstanceClassTypes(evaluator, argType, argExpr) {
634
+ let foundNonClassType = false;
635
+ const classTypes = [];
636
+ const negativeClassTypes = [];
637
+ // Create a helper function that returns a list of class types or
638
+ // undefined if any of the types are not valid.
639
+ const addClassTypesToList = (types, isAmbiguous, isUnboundedEntry) => {
640
+ types.forEach((subtype) => {
641
+ if ((0, types_1.isClass)(subtype)) {
642
+ subtype = (0, typeUtils_1.specializeWithUnknownTypeArgs)(subtype, evaluator.getTupleClassType());
643
+ if ((0, types_1.isInstantiableClass)(subtype) && types_1.ClassType.isBuiltIn(subtype, 'Callable')) {
644
+ subtype = (0, typeUtils_1.convertToInstantiable)((0, typeUtils_1.getUnknownTypeForCallable)());
645
+ }
646
+ else if (types_1.TypeBase.isInstance(subtype) && types_1.ClassType.isBuiltIn(subtype, 'type')) {
647
+ if (subtype.priv.typeArgs && subtype.priv.typeArgs.length > 0) {
648
+ const typeArg = subtype.priv.typeArgs[0];
649
+ if ((0, types_1.isAnyOrUnknown)(typeArg)) {
650
+ foundNonClassType = true;
651
+ return;
652
+ }
653
+ if ((0, types_1.isInstantiableClass)(typeArg)) {
654
+ subtype = types_1.ClassType.cloneIncludeSubclasses(typeArg);
655
+ }
656
+ else if ((0, types_1.isClassInstance)(typeArg)) {
657
+ subtype = types_1.ClassType.cloneAsInstantiable(typeArg);
658
+ }
659
+ }
660
+ }
661
+ }
662
+ let classType;
663
+ if ((0, types_1.isInstantiableClass)(subtype)) {
664
+ // If this is a reference to a class that has type promotions (e.g.
665
+ // float or complex), remove the promotions for purposes of the
666
+ // isinstance check).
667
+ if (!subtype.priv.includeSubclasses && subtype.priv.includePromotions) {
668
+ subtype = types_1.ClassType.cloneRemoveTypePromotions(subtype);
669
+ }
670
+ classType = subtype;
671
+ }
672
+ else if ((0, types_1.isTypeVar)(subtype) && types_1.TypeBase.isInstantiable(subtype)) {
673
+ classType = subtype;
674
+ }
675
+ else if ((0, typeUtils_1.isNoneTypeClass)(subtype)) {
676
+ (0, debug_1.assert)((0, types_1.isInstantiableClass)(subtype));
677
+ classType = subtype;
678
+ }
679
+ else if ((0, types_1.isFunction)(subtype) &&
680
+ subtype.shared.parameters.length === 2 &&
681
+ subtype.shared.parameters[0].category === 1 /* ParamCategory.ArgsList */ &&
682
+ subtype.shared.parameters[1].category === 2 /* ParamCategory.KwargsDict */) {
683
+ classType = subtype;
684
+ }
685
+ else {
686
+ foundNonClassType = true;
687
+ return;
688
+ }
689
+ classTypes.push(classType);
690
+ // Unbounded entries may be absent, and alternative class objects
691
+ // are not all guaranteed to participate in the runtime check.
692
+ if (!isUnboundedEntry && !isAmbiguous) {
693
+ negativeClassTypes.push(classType);
694
+ }
695
+ });
696
+ };
697
+ const addClassTypesRecursive = (type, isAmbiguous, isUnboundedEntry, recursionCount, expression) => {
698
+ if (recursionCount > types_1.maxTypeRecursionCount) {
699
+ return;
700
+ }
701
+ // A runtime union checks both operands, but either operand can itself
702
+ // be an alternative class object. Keep their certainty separate.
703
+ if ((0, types_1.isUnion)(type) &&
704
+ expression?.nodeType === 7 /* ParseNodeType.BinaryOperation */ &&
705
+ expression.d.operator === 6 /* OperatorType.BitwiseOr */) {
706
+ const leftType = evaluator.getCachedType(expression.d.leftExpr);
707
+ const rightType = evaluator.getCachedType(expression.d.rightExpr);
708
+ if (leftType &&
709
+ rightType &&
710
+ !(0, operations_1.customMetaclassSupportsMethod)(leftType, '__or__') &&
711
+ !(0, operations_1.customMetaclassSupportsMethod)(rightType, '__ror__')) {
712
+ // Match the union evaluator's normalization of None operands to NoneType.
713
+ const adjustedLeftType = (0, typeUtils_1.isNoneInstance)(leftType)
714
+ ? (0, typeUtils_1.convertToInstantiable)(evaluator.getNoneType())
715
+ : leftType;
716
+ const adjustedRightType = (0, typeUtils_1.isNoneInstance)(rightType)
717
+ ? (0, typeUtils_1.convertToInstantiable)(evaluator.getNoneType())
718
+ : rightType;
719
+ addClassTypesRecursive(adjustedLeftType, isAmbiguous, isUnboundedEntry, recursionCount, expression.d.leftExpr);
720
+ addClassTypesRecursive(adjustedRightType, isAmbiguous, isUnboundedEntry, recursionCount, expression.d.rightExpr);
721
+ return;
722
+ }
723
+ }
724
+ const isRuntimeUnion = type.props?.specialForm && types_1.ClassType.isBuiltIn(type.props.specialForm, 'UnionType');
725
+ const isAmbiguousType = isAmbiguous || ((0, types_1.isUnion)(type) && !isRuntimeUnion);
726
+ (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
727
+ if ((0, types_1.isClassInstance)(subtype) && (0, typeUtils_1.isTupleClass)(subtype)) {
728
+ if (subtype.priv.tupleTypeArgs) {
729
+ let entryExpressions;
730
+ if (expression?.nodeType === 52 /* ParseNodeType.Tuple */) {
731
+ const expressions = [];
732
+ expression.d.items.forEach((item) => {
733
+ if (item.nodeType !== 56 /* ParseNodeType.Unpack */) {
734
+ expressions.push(item);
735
+ return;
736
+ }
737
+ const unpackedType = evaluator.getCachedType(item.d.expr);
738
+ const entryCount = unpackedType && (0, types_1.isClassInstance)(unpackedType) && (0, typeUtils_1.isTupleClass)(unpackedType)
739
+ ? unpackedType.priv.tupleTypeArgs?.length ?? 1
740
+ : 1;
741
+ for (let index = 0; index < entryCount; index++) {
742
+ expressions.push(undefined);
743
+ }
744
+ });
745
+ if (expressions.length === subtype.priv.tupleTypeArgs.length) {
746
+ entryExpressions = expressions;
747
+ }
748
+ }
749
+ subtype.priv.tupleTypeArgs.forEach((tupleEntry, index) => {
750
+ addClassTypesRecursive(tupleEntry.type, isAmbiguousType, isUnboundedEntry || tupleEntry.isUnbounded, recursionCount + 1, entryExpressions?.[index]);
751
+ });
752
+ }
753
+ }
754
+ else {
755
+ addClassTypesToList([subtype], isAmbiguousType, isUnboundedEntry);
756
+ }
757
+ });
758
+ };
759
+ addClassTypesRecursive(argType, /* isAmbiguous */ false, /* isUnboundedEntry */ false, 0, argExpr);
760
+ return foundNonClassType ? undefined : { classTypes, negativeClassTypes };
761
+ }
762
+ function narrowTypeForInstanceOrSubclass(evaluator, type, filterTypes, isInstanceCheck, isTypeIsCheck, isPositiveTest, errorNode, nodeInfo, narrowTypeForInstanceOrSubclassInternalCallback) {
763
+ if (!isInstanceCheck && !isTypeIsCheck && !isPositiveTest) {
764
+ filterTypes = filterTypes.filter((filterType) => {
765
+ const concreteFilterType = evaluator.makeTopLevelTypeVarsConcrete(filterType);
766
+ return (!(0, types_1.isInstantiableClass)(concreteFilterType) ||
767
+ !types_1.ClassType.isFinal(concreteFilterType) ||
768
+ !(0, operations_1.customMetaclassSupportsMethod)(concreteFilterType, '__subclasscheck__'));
769
+ });
770
+ }
771
+ if (!isPositiveTest && filterTypes.length === 0) {
772
+ return type;
773
+ }
774
+ const narrowedType = narrowTypeForInstanceOrSubclassInternalCallback(evaluator, type, filterTypes, isInstanceCheck, isTypeIsCheck, isPositiveTest,
775
+ /* allowIntersections */ false, errorNode, nodeInfo);
776
+ if (!(0, types_1.isNever)(narrowedType)) {
777
+ return narrowedType;
778
+ }
779
+ return narrowTypeForInstanceOrSubclassInternalCallback(evaluator, type, filterTypes, isInstanceCheck, isTypeIsCheck, isPositiveTest,
780
+ /* allowIntersections */ true, errorNode, nodeInfo);
781
+ }
782
+ function narrowTypeForTupleLength(evaluator, referenceType, lengthValue, isPositiveTest, isLessThanCheck) {
783
+ return (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
784
+ const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
785
+ // If it's not a tuple, we can't narrow it.
786
+ if (!(0, types_1.isClassInstance)(concreteSubtype) ||
787
+ !(0, typeUtils_1.isTupleClass)(concreteSubtype) ||
788
+ !concreteSubtype.priv.tupleTypeArgs) {
789
+ return subtype;
790
+ }
791
+ // If the tuple contains a TypeVarTuple, we can't narrow it.
792
+ if (concreteSubtype.priv.tupleTypeArgs.some((typeArg) => (0, types_1.isUnpackedTypeVarTuple)(typeArg.type))) {
793
+ return subtype;
794
+ }
795
+ // If the tuple contains no unbounded elements, then we know its length exactly.
796
+ if (!concreteSubtype.priv.tupleTypeArgs.some((typeArg) => typeArg.isUnbounded)) {
797
+ const tupleLengthMatches = isLessThanCheck
798
+ ? concreteSubtype.priv.tupleTypeArgs.length < lengthValue
799
+ : concreteSubtype.priv.tupleTypeArgs.length === lengthValue;
800
+ return tupleLengthMatches === isPositiveTest ? subtype : undefined;
801
+ }
802
+ // The tuple contains a "...". We'll expand this into as many elements as
803
+ // necessary to match the lengthValue.
804
+ const elementsToAdd = lengthValue - concreteSubtype.priv.tupleTypeArgs.length + 1;
805
+ if (!isLessThanCheck) {
806
+ // If the specified length is smaller than the minimum length of this tuple,
807
+ // we can rule it out for a positive test and rule it in for a negative test.
808
+ if (elementsToAdd < 0) {
809
+ return isPositiveTest ? undefined : subtype;
810
+ }
811
+ if (!isPositiveTest) {
812
+ // If this is an equality check for the minimum length (e.g.
813
+ // "len(x) == 0"), we can expand the minimum length by one).
814
+ const minLen = concreteSubtype.priv.tupleTypeArgs.length - 1;
815
+ if (lengthValue === minLen) {
816
+ return expandUnboundedTupleElement(concreteSubtype, 1, /* keepUnbounded */ true);
817
+ }
818
+ return subtype;
819
+ }
820
+ return expandUnboundedTupleElement(concreteSubtype, elementsToAdd, /* keepUnbounded */ false);
821
+ }
822
+ // If this is a tuple related to an "*args: P.args" parameter, don't expand it.
823
+ if ((0, types_1.isParamSpec)(subtype) && subtype.priv.paramSpecAccess) {
824
+ return subtype;
825
+ }
826
+ // Place an upper limit on the number of union subtypes we
827
+ // will expand the tuple to.
828
+ const maxTupleUnionExpansion = 32;
829
+ if (elementsToAdd > maxTupleUnionExpansion) {
830
+ return subtype;
831
+ }
832
+ if (isPositiveTest) {
833
+ if (elementsToAdd < 1) {
834
+ return undefined;
835
+ }
836
+ const typesToCombine = [];
837
+ for (let i = 0; i < elementsToAdd; i++) {
838
+ typesToCombine.push(expandUnboundedTupleElement(concreteSubtype, i, /* keepUnbounded */ false));
839
+ }
840
+ return (0, types_1.combineTypes)(typesToCombine);
841
+ }
842
+ return expandUnboundedTupleElement(concreteSubtype, elementsToAdd, /* keepUnbounded */ true);
843
+ });
844
+ }
845
+ function expandUnboundedTupleElement(tupleType, elementsToAdd, keepUnbounded) {
846
+ const tupleTypeArgs = [];
847
+ tupleType.priv.tupleTypeArgs.forEach((typeArg) => {
848
+ if (!typeArg.isUnbounded) {
849
+ tupleTypeArgs.push(typeArg);
850
+ }
851
+ else {
852
+ for (let i = 0; i < elementsToAdd; i++) {
853
+ tupleTypeArgs.push({ isUnbounded: false, type: typeArg.type });
854
+ }
855
+ if (keepUnbounded) {
856
+ tupleTypeArgs.push(typeArg);
857
+ }
858
+ }
859
+ });
860
+ return (0, typeUtils_1.specializeTupleClass)(tupleType, tupleTypeArgs);
861
+ }
862
+ function narrowTypeForContainerType(evaluator, referenceType, containerType, isPositiveTest) {
863
+ if (isPositiveTest) {
864
+ const elementType = getElementTypeForContainerNarrowing(containerType);
865
+ if (!elementType) {
866
+ return referenceType;
867
+ }
868
+ return narrowTypeForContainerElementType(evaluator, referenceType, evaluator.makeTopLevelTypeVarsConcrete(elementType));
869
+ }
870
+ // Narrowing in the negative case is possible only with tuples
871
+ // with a known length.
872
+ if (!(0, types_1.isClassInstance)(containerType) ||
873
+ !types_1.ClassType.isBuiltIn(containerType, 'tuple') ||
874
+ !containerType.priv.tupleTypeArgs) {
875
+ return referenceType;
876
+ }
877
+ // Determine which tuple types can be eliminated. Only "None",
878
+ // literal types, and final instantiable classes can be handled here.
879
+ // Non-final instantiable classes (type[A]) cannot be eliminated in negative
880
+ // tests because a subclass SubA(A) reaches the negative branch at runtime
881
+ // (since SubA != A). Generic classes are also excluded because a
882
+ // specialized class object like Box[int] is not the same runtime object
883
+ // as Box. Classes that define or inherit __class_getitem__ are excluded
884
+ // for the same reason.
885
+ const typesToEliminate = [];
886
+ containerType.priv.tupleTypeArgs.forEach((tupleEntry) => {
887
+ if (!tupleEntry.isUnbounded) {
888
+ if ((0, typeUtils_1.isNoneInstance)(tupleEntry.type)) {
889
+ typesToEliminate.push(tupleEntry.type);
890
+ }
891
+ else if ((0, types_1.isClassInstance)(tupleEntry.type) && (0, typeUtils_1.isLiteralType)(tupleEntry.type)) {
892
+ typesToEliminate.push(tupleEntry.type);
893
+ }
894
+ else if ((0, types_1.isInstantiableClass)(tupleEntry.type) &&
895
+ types_1.ClassType.isFinal(tupleEntry.type) &&
896
+ tupleEntry.type.shared.typeParams.length === 0 &&
897
+ !(0, typeUtils_1.lookUpClassMember)(tupleEntry.type, '__class_getitem__')) {
898
+ typesToEliminate.push(tupleEntry.type);
899
+ }
900
+ }
901
+ });
902
+ if (typesToEliminate.length === 0) {
903
+ return referenceType;
904
+ }
905
+ const canNarrowLiterals = typesToEliminate.some(types_1.isClassInstance);
906
+ return (0, typeUtils_1.mapSubtypes)(referenceType, (unexpandedSubtype) => {
907
+ const referenceSubtype = evaluator.makeTopLevelTypeVarsConcrete(unexpandedSubtype);
908
+ if (canNarrowLiterals &&
909
+ (0, types_1.isClassInstance)(referenceSubtype) &&
910
+ referenceSubtype.priv.literalValue === undefined) {
911
+ // If we're able to enumerate all possible literal values
912
+ // (for bool or enum), we can eliminate all others in a negative test.
913
+ const allLiteralTypes = enumerateLiteralsForType(evaluator, referenceSubtype);
914
+ if (allLiteralTypes && allLiteralTypes.length > 0) {
915
+ return (0, types_1.combineTypes)(allLiteralTypes.filter((type) => !typesToEliminate.some((t) => (0, types_1.isTypeSame)(t, type))));
916
+ }
917
+ }
918
+ if (typesToEliminate.some((t) => (0, types_1.isTypeSame)(t, referenceSubtype))) {
919
+ return undefined;
920
+ }
921
+ return unexpandedSubtype;
922
+ });
923
+ }
924
+ function getElementTypeForContainerNarrowing(containerType) {
925
+ if ((0, types_1.isUnion)(containerType)) {
926
+ const elementTypes = [];
927
+ for (const subtype of containerType.priv.subtypes) {
928
+ const elemType = getElementTypeForContainerNarrowing(subtype);
929
+ // Don't narrow if any subtype's element type is unknown or includes an
930
+ // unpacked TypeVarTuple (e.g. tuple[*Ts]), whose elements could be anything.
931
+ if (!elemType || (0, typeUtils_1.someSubtypes)(elemType, (t) => (0, types_1.isAnyOrUnknown)(t) || (0, types_1.isUnpackedTypeVarTuple)(t))) {
932
+ return undefined;
933
+ }
934
+ elementTypes.push(elemType);
935
+ }
936
+ return (0, types_1.combineTypes)(elementTypes);
937
+ }
938
+ if (!(0, types_1.isClassInstance)(containerType)) {
939
+ return undefined;
940
+ }
941
+ // We support contains narrowing only for certain built-in types that have been specialized.
942
+ // Abstract collection types (e.g. Sequence, Container, KeysView) are intentionally excluded
943
+ // because their __contains__ implementations are not constrained to the element type.
944
+ const supportedContainers = ['list', 'set', 'frozenset', 'deque', 'tuple', 'dict', 'defaultdict', 'OrderedDict'];
945
+ // The concrete dict view types returned by dict.keys() and dict.values().
946
+ const supportedDictViews = ['_collections_abc.dict_keys', '_collections_abc.dict_values'];
947
+ const isSupported = types_1.ClassType.isBuiltIn(containerType, supportedContainers) ||
948
+ supportedDictViews.includes(containerType.shared.fullName);
949
+ if (!isSupported) {
950
+ return undefined;
951
+ }
952
+ if (!containerType.priv.typeArgs || containerType.priv.typeArgs.length < 1) {
953
+ return undefined;
954
+ }
955
+ if (containerType.shared.fullName === '_collections_abc.dict_values') {
956
+ return containerType.priv.typeArgs.length > 1 ? containerType.priv.typeArgs[1] : undefined;
957
+ }
958
+ if ((0, typeUtils_1.isTupleClass)(containerType) && containerType.priv.tupleTypeArgs) {
959
+ return (0, types_1.combineTypes)(containerType.priv.tupleTypeArgs.map((t) => t.type));
960
+ }
961
+ return containerType.priv.typeArgs[0];
962
+ }
963
+ function getStringLiteralForStrEnumMember(enumMember) {
964
+ const literalValue = enumMember.priv.literalValue;
965
+ if (!(literalValue instanceof types_1.EnumLiteral) ||
966
+ !types_1.ClassType.isEnumClass(enumMember) ||
967
+ !(0, typeUtils_1.derivesFromStdlibClass)(enumMember, 'str') ||
968
+ types_1.ClassType.isEnumMemberSetMayBeIncomplete(enumMember) ||
969
+ !(0, enums_1.hasStandardEnumConstruction)(enumMember)) {
970
+ return undefined;
971
+ }
972
+ const equalityMember = (0, typeUtils_1.lookUpObjectMember)(enumMember, '__eq__', 4 /* MemberAccessFlags.SkipObjectBaseClass */ | 16 /* MemberAccessFlags.SkipInstanceMembers */);
973
+ if (!equalityMember ||
974
+ !(0, types_1.isClass)(equalityMember.classType) ||
975
+ !types_1.ClassType.isBuiltIn(equalityMember.classType, 'str')) {
976
+ return undefined;
977
+ }
978
+ const valueType = literalValue.itemType;
979
+ if ((0, types_1.isClassInstance)(valueType) && (0, typeUtils_1.isLiteralType)(valueType) && types_1.ClassType.isBuiltIn(valueType, 'str')) {
980
+ return valueType;
981
+ }
982
+ return undefined;
983
+ }
984
+ function narrowTypeForContainerElementType(evaluator, referenceType, elementType) {
985
+ return evaluator.mapSubtypesExpandTypeVars(referenceType, /* options */ undefined, (referenceSubtype) => {
986
+ return (0, typeUtils_1.mapSubtypes)(elementType, (elementSubtype) => {
987
+ if ((0, types_1.isAnyOrUnknown)(elementSubtype)) {
988
+ return referenceSubtype;
989
+ }
990
+ // If the two types are disjoint (i.e. are not comparable), eliminate this subtype.
991
+ if (!evaluator.isTypeComparable(elementSubtype, referenceSubtype)) {
992
+ return undefined;
993
+ }
994
+ if ((0, types_1.isClassInstance)(referenceSubtype) &&
995
+ types_1.ClassType.isBuiltIn(referenceSubtype, ['str', 'LiteralString']) &&
996
+ // A plain str type includes subclasses such as StrEnum; only an exact str can become a primitive literal.
997
+ (referenceSubtype.priv.isExactStringFlow || (0, typeUtils_1.isLiteralType)(referenceSubtype)) &&
998
+ (0, types_1.isClassInstance)(elementSubtype)) {
999
+ const stringLiteral = getStringLiteralForStrEnumMember(elementSubtype);
1000
+ // A broad string type can admit the enum member or another equal string subtype,
1001
+ // so convert to the primitive literal only when the reference is an exact str.
1002
+ if (stringLiteral && evaluator.assignType(referenceSubtype, stringLiteral)) {
1003
+ return (0, typeUtils_1.stripTypeForm)((0, typeUtils_1.addConditionToType)(stringLiteral, referenceSubtype.props?.condition));
1004
+ }
1005
+ }
1006
+ // If one of the two types is a literal, we can narrow to that type.
1007
+ if ((0, types_1.isClassInstance)(elementSubtype) &&
1008
+ ((0, typeUtils_1.isLiteralLikeType)(elementSubtype) || (0, typeUtils_1.isNoneInstance)(elementSubtype)) &&
1009
+ evaluator.assignType(referenceSubtype, elementSubtype)) {
1010
+ // Cross-type equality does not give a primitive the literal's runtime type.
1011
+ if ((0, types_1.isClassInstance)(referenceSubtype) &&
1012
+ types_1.ClassType.isBuiltIn(referenceSubtype) &&
1013
+ !types_1.ClassType.isBuiltIn(referenceSubtype, ['object', 'LiteralString']) &&
1014
+ (0, typeUtils_1.isLiteralType)(elementSubtype) &&
1015
+ !types_1.ClassType.isSameGenericClass(referenceSubtype, elementSubtype)) {
1016
+ return referenceSubtype;
1017
+ }
1018
+ return (0, typeUtils_1.stripTypeForm)((0, typeUtils_1.addConditionToType)(elementSubtype, referenceSubtype.props?.condition));
1019
+ }
1020
+ if ((0, types_1.isClassInstance)(referenceSubtype) &&
1021
+ ((0, typeUtils_1.isLiteralLikeType)(referenceSubtype) || (0, typeUtils_1.isNoneInstance)(referenceSubtype)) &&
1022
+ evaluator.assignType(elementSubtype, referenceSubtype)) {
1023
+ return (0, typeUtils_1.stripTypeForm)((0, typeUtils_1.addConditionToType)(referenceSubtype, elementSubtype.props?.condition));
1024
+ }
1025
+ // If the element type is a known class object that is assignable to
1026
+ // the reference type, we can narrow to that class object.
1027
+ if ((0, types_1.isInstantiableClass)(elementSubtype) &&
1028
+ !elementSubtype.priv.includeSubclasses &&
1029
+ evaluator.assignType(referenceSubtype, elementSubtype)) {
1030
+ return (0, typeUtils_1.stripTypeForm)((0, typeUtils_1.addConditionToType)(elementSubtype, referenceSubtype.props?.condition));
1031
+ }
1032
+ // It's not safe to narrow.
1033
+ return referenceSubtype;
1034
+ });
1035
+ });
1036
+ }
1037
+ function narrowTypeForTypedDictKey(evaluator, referenceType, literalKey, isPositiveTest) {
1038
+ const narrowedType = evaluator.mapSubtypesExpandTypeVars(referenceType,
1039
+ /* options */ undefined, (subtype, unexpandedSubtype) => {
1040
+ if ((0, types_1.isParamSpec)(unexpandedSubtype)) {
1041
+ return unexpandedSubtype;
1042
+ }
1043
+ if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
1044
+ const entries = (0, typedDicts_1.getTypedDictMembersForClass)(evaluator, subtype, /* allowNarrowed */ true);
1045
+ const knownEntry = entries.knownItems.get(literalKey.priv.literalValue);
1046
+ const tdEntry = knownEntry ?? entries.extraItems;
1047
+ if (isPositiveTest) {
1048
+ // The code that is commented out below implements the behavior that is technically
1049
+ // correct, but until we PEP 728 is ratified and we have a way to express "extra items"
1050
+ // and closed TypedDicts, we'll preserve the older (less correct) behavior to enable
1051
+ // narrowing of TypedDicts based on checks for specific keys.
1052
+ // TODO - remove this behavior once PEP 728 is accepted and the feature is no
1053
+ // longer experimental.
1054
+ if (!tdEntry) {
1055
+ return undefined;
1056
+ }
1057
+ // if (!tdEntry) {
1058
+ // // If there is no TD entry for this key and no "extra items" defined,
1059
+ // // we have to assume that the TypedDict may contain extra items, so
1060
+ // // narrowing it isn't possible in this case.
1061
+ // return subtype;
1062
+ // }
1063
+ if ((0, types_1.isNever)(tdEntry.valueType)) {
1064
+ // If the entry is typed as Never or the "extra items" is typed as Never,
1065
+ // then this key cannot be present in the TypedDict, and we can eliminate it.
1066
+ // A closed TypedDict has an "extra items" of Never, so this is what allows
1067
+ // a key check to discriminate between closed TypedDicts.
1068
+ return undefined;
1069
+ }
1070
+ // If the entry is currently not required and not marked provided, we can mark
1071
+ // it as provided after this guard expression confirms it is.
1072
+ if (tdEntry.isRequired || tdEntry.isProvided) {
1073
+ return subtype;
1074
+ }
1075
+ const newNarrowedEntriesMap = new Map(subtype.priv.typedDictNarrowedEntries ?? []);
1076
+ // Add the new entry.
1077
+ newNarrowedEntriesMap.set(literalKey.priv.literalValue, {
1078
+ valueType: tdEntry.valueType,
1079
+ isReadOnly: tdEntry.isReadOnly,
1080
+ isRequired: false,
1081
+ isProvided: true,
1082
+ });
1083
+ // Clone the TypedDict object with the new entries.
1084
+ return types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForNarrowedTypedDictEntries(types_1.ClassType.cloneAsInstantiable(subtype), newNarrowedEntriesMap));
1085
+ }
1086
+ else {
1087
+ if (!knownEntry) {
1088
+ // The key is not one of the known items, so it can be supplied
1089
+ // only through an "extra items" entry, which says nothing about
1090
+ // whether this particular key is present. Its absence is therefore
1091
+ // consistent with the type, and the subtype cannot be eliminated.
1092
+ return subtype;
1093
+ }
1094
+ return knownEntry.isRequired || knownEntry.isProvided ? undefined : subtype;
1095
+ }
1096
+ }
1097
+ return subtype;
1098
+ });
1099
+ return narrowedType;
1100
+ }
1101
+ function narrowTypeForDiscriminatedDictEntryComparison(evaluator, referenceType, indexLiteralType, literalType, isPositiveTest) {
1102
+ let canNarrow = true;
1103
+ const narrowedType = (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
1104
+ if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
1105
+ const symbolMap = (0, typedDicts_1.getTypedDictMembersForClass)(evaluator, subtype);
1106
+ const tdEntry = symbolMap.knownItems.get(indexLiteralType.priv.literalValue);
1107
+ if (tdEntry && (0, typeUtils_1.isLiteralTypeOrUnion)(tdEntry.valueType)) {
1108
+ if (isPositiveTest) {
1109
+ let foundMatch = false;
1110
+ (0, typeUtils_1.doForEachSubtype)(literalType, (literalSubtype) => {
1111
+ if (evaluator.assignType(tdEntry.valueType, literalSubtype)) {
1112
+ foundMatch = true;
1113
+ }
1114
+ });
1115
+ return foundMatch ? subtype : undefined;
1116
+ }
1117
+ else {
1118
+ let foundNonMatch = false;
1119
+ (0, typeUtils_1.doForEachSubtype)(literalType, (literalSubtype) => {
1120
+ if (!evaluator.assignType(literalSubtype, tdEntry.valueType)) {
1121
+ foundNonMatch = true;
1122
+ }
1123
+ });
1124
+ return foundNonMatch ? subtype : undefined;
1125
+ }
1126
+ }
1127
+ }
1128
+ canNarrow = false;
1129
+ return subtype;
1130
+ });
1131
+ return canNarrow ? narrowedType : referenceType;
1132
+ }
1133
+ function narrowTypeForDiscriminatedTupleComparison(evaluator, referenceType, indexLiteralType, literalType, isPositiveTest) {
1134
+ let canNarrow = true;
1135
+ const narrowedType = (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
1136
+ if ((0, types_1.isClassInstance)(subtype) &&
1137
+ types_1.ClassType.isTupleClass(subtype) &&
1138
+ !(0, typeUtils_1.isUnboundedTupleClass)(subtype) &&
1139
+ typeof indexLiteralType.priv.literalValue === 'number' &&
1140
+ (0, types_1.isClassInstance)(literalType)) {
1141
+ const indexValue = indexLiteralType.priv.literalValue;
1142
+ if (subtype.priv.tupleTypeArgs && indexValue >= 0 && indexValue < subtype.priv.tupleTypeArgs.length) {
1143
+ const tupleEntryType = subtype.priv.tupleTypeArgs[indexValue]?.type;
1144
+ if (tupleEntryType && (0, typeUtils_1.isLiteralTypeOrUnion)(tupleEntryType)) {
1145
+ if (isPositiveTest) {
1146
+ return evaluator.assignType(tupleEntryType, literalType) ? subtype : undefined;
1147
+ }
1148
+ else {
1149
+ return evaluator.assignType(literalType, tupleEntryType) ? undefined : subtype;
1150
+ }
1151
+ }
1152
+ }
1153
+ }
1154
+ canNarrow = false;
1155
+ return subtype;
1156
+ });
1157
+ return canNarrow ? narrowedType : referenceType;
1158
+ }
1159
+ function narrowTypeForDiscriminatedLiteralFieldComparison(evaluator, referenceType, memberName, literalType, isPositiveTest) {
1160
+ const narrowedType = (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
1161
+ let memberInfo;
1162
+ if ((0, types_1.isClassInstance)(subtype)) {
1163
+ memberInfo = (0, typeUtils_1.lookUpObjectMember)(subtype, memberName);
1164
+ }
1165
+ else if ((0, types_1.isInstantiableClass)(subtype)) {
1166
+ memberInfo = (0, typeUtils_1.lookUpClassMember)(subtype, memberName);
1167
+ }
1168
+ if (memberInfo && memberInfo.isTypeDeclared) {
1169
+ let memberType = evaluator.getTypeOfMember(memberInfo);
1170
+ // Handle the case where the field is a property
1171
+ // that has a declared literal return type for its getter.
1172
+ if ((0, types_1.isClassInstance)(subtype) && (0, types_1.isClassInstance)(memberType) && (0, typeUtils_1.isProperty)(memberType)) {
1173
+ const getterType = memberType.priv.fgetInfo?.methodType;
1174
+ if (getterType && (0, types_1.isFunction)(getterType) && getterType.shared.declaredReturnType) {
1175
+ const getterReturnType = types_1.FunctionType.getEffectiveReturnType(getterType);
1176
+ if (getterReturnType) {
1177
+ memberType = getterReturnType;
1178
+ }
1179
+ }
1180
+ }
1181
+ if ((0, typeUtils_1.isLiteralTypeOrUnion)(memberType, /* allowNone */ true)) {
1182
+ if (isPositiveTest) {
1183
+ return evaluator.assignType(memberType, literalType) ? subtype : undefined;
1184
+ }
1185
+ else {
1186
+ return evaluator.assignType(literalType, memberType) ? undefined : subtype;
1187
+ }
1188
+ }
1189
+ }
1190
+ return subtype;
1191
+ });
1192
+ return narrowedType;
1193
+ }
1194
+ function narrowTypeForDiscriminatedFieldNoneComparison(evaluator, referenceType, memberName, isPositiveTest) {
1195
+ return (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
1196
+ let memberInfo;
1197
+ if ((0, types_1.isClassInstance)(subtype)) {
1198
+ memberInfo = (0, typeUtils_1.lookUpObjectMember)(subtype, memberName);
1199
+ }
1200
+ else if ((0, types_1.isInstantiableClass)(subtype)) {
1201
+ memberInfo = (0, typeUtils_1.lookUpClassMember)(subtype, memberName);
1202
+ }
1203
+ if (memberInfo && memberInfo.isTypeDeclared) {
1204
+ // Check the declared type before narrowing, since the member type
1205
+ // below will be concretized and lose descriptor identity.
1206
+ const declaredType = evaluator.getDeclaredTypeOfSymbol(memberInfo.symbol)?.type;
1207
+ if (!declaredType) {
1208
+ // isTypeDeclared is true but the type couldn't be resolved (e.g. an
1209
+ // unresolvable stub). Conservatively skip narrowing rather than risk
1210
+ // incorrectly eliminating a descriptor-typed member.
1211
+ return subtype;
1212
+ }
1213
+ // Check if any subtype of the declared type is a descriptor or property.
1214
+ // isMaybeDescriptorInstance handles declared types in instance form (ClassInstance),
1215
+ // while isMaybeDescriptorClass handles declared types in instantiable form
1216
+ // (InstantiableClass), which occurs when the annotation refers to the class object itself.
1217
+ // This check applies to both positive and negative test paths: descriptor __get__
1218
+ // return values don't reflect stored values regardless of test polarity.
1219
+ const isDescriptorOrProperty = (0, typeUtils_1.someSubtypes)(declaredType, (declaredSubtype) => (0, typeUtils_1.isProperty)(declaredSubtype) ||
1220
+ (0, typeUtils_1.isMaybeDescriptorInstance)(declaredSubtype) ||
1221
+ (0, typeUtils_1.isMaybeDescriptorClass)(declaredSubtype));
1222
+ if (isDescriptorOrProperty) {
1223
+ return subtype;
1224
+ }
1225
+ const memberType = evaluator.makeTopLevelTypeVarsConcrete(evaluator.getTypeOfMember(memberInfo));
1226
+ let canNarrow = true;
1227
+ if (isPositiveTest) {
1228
+ (0, typeUtils_1.doForEachSubtype)(memberType, (memberSubtype) => {
1229
+ memberSubtype = evaluator.makeTopLevelTypeVarsConcrete(memberSubtype);
1230
+ if ((0, types_1.isAnyOrUnknown)(memberSubtype) || (0, typeUtils_1.isNoneInstance)(memberSubtype) || (0, types_1.isNever)(memberSubtype)) {
1231
+ canNarrow = false;
1232
+ }
1233
+ });
1234
+ }
1235
+ else {
1236
+ canNarrow = (0, typeUtils_1.isNoneInstance)(memberType);
1237
+ }
1238
+ if (canNarrow) {
1239
+ return undefined;
1240
+ }
1241
+ }
1242
+ return subtype;
1243
+ });
1244
+ }
1245
+ function narrowTypeForTypeIs(evaluator, type, classTypes, isPositiveTest, isIsOperator, classTypeVar, allowLegacyEquality, allowExactStringFlow) {
1246
+ const metaclassEqualityResults = isIsOperator ? undefined : new Map();
1247
+ const hasEqualitySemantics = allowLegacyEquality
1248
+ ? hasDeclaredIdentityEqualitySemantics
1249
+ : hasIdentityEqualitySemantics;
1250
+ if (metaclassEqualityResults &&
1251
+ classTypes.some((classType) => !hasEqualitySemantics(classType, metaclassEqualityResults))) {
1252
+ return type;
1253
+ }
1254
+ // We currently don't support narrowing in the negative direction
1255
+ // when there are more than one class types.
1256
+ if (!isPositiveTest && classTypes.length > 1) {
1257
+ return type;
1258
+ }
1259
+ // Retain the TypeVar rather than its expanded constraints so assignments and loop joins preserve correlation.
1260
+ if (isIsOperator && isPositiveTest && classTypeVar && (0, types_1.isAnyOrUnknown)(type)) {
1261
+ return classTypeVar;
1262
+ }
1263
+ let gradualArgResults;
1264
+ const typesToCombine = classTypes.map((classType) => {
1265
+ const isExactStringClass = isIsOperator &&
1266
+ allowExactStringFlow &&
1267
+ !classTypeVar &&
1268
+ !classType.priv.includeSubclasses &&
1269
+ types_1.ClassType.isBuiltIn(classType, 'str');
1270
+ return evaluator.mapSubtypesExpandTypeVars(type,
1271
+ /* options */ undefined, (subtype, unexpandedSubtype) => {
1272
+ if ((0, types_1.isClassInstance)(subtype)) {
1273
+ const isLiteral = subtype.priv.literalValue !== undefined;
1274
+ const instantiableSubtype = isLiteral
1275
+ ? types_1.ClassType.cloneIncludeSubclasses(types_1.ClassType.cloneAsInstantiable(types_1.ClassType.cloneWithLiteral(subtype, undefined)),
1276
+ /* includeSubclasses */ false)
1277
+ : types_1.ClassType.cloneAsInstantiable(subtype);
1278
+ if (metaclassEqualityResults &&
1279
+ !hasEqualitySemantics(instantiableSubtype, metaclassEqualityResults)) {
1280
+ return unexpandedSubtype;
1281
+ }
1282
+ const matches = types_1.ClassType.isDerivedFrom(classType, instantiableSubtype);
1283
+ // A literal has an exact runtime class, not an arbitrary subclass.
1284
+ if (matches && isLiteral && !types_1.ClassType.isSameGenericClass(instantiableSubtype, classType)) {
1285
+ return isPositiveTest ? undefined : subtype;
1286
+ }
1287
+ if (isPositiveTest) {
1288
+ if (matches) {
1289
+ if (types_1.ClassType.isSameGenericClass(instantiableSubtype, classType)) {
1290
+ // Keep exact-str information for a later string-literal membership check.
1291
+ const narrowedSubtype = isExactStringClass && !isLiteral
1292
+ ? types_1.ClassType.cloneExactStringFlow(subtype, true)
1293
+ : subtype;
1294
+ return (0, typeUtils_1.addConditionToType)(narrowedSubtype, (0, typeUtils_1.getTypeCondition)(classType));
1295
+ }
1296
+ let narrowedClass = classType;
1297
+ if (subtype.priv.typeArgs || subtype.priv.tupleTypeArgs) {
1298
+ if (classType.shared.typeParams.length > 0) {
1299
+ if ((0, typeUtils_1.containsAnyRecursive)(classType) ||
1300
+ !evaluator.assignType(subtype, types_1.ClassType.cloneAsInstance(classType))) {
1301
+ const genericClass = (0, typeUtils_1.selfSpecializeClass)(types_1.ClassType.specialize(classType, undefined));
1302
+ const constraints = new constraintTracker_1.ConstraintTracker();
1303
+ if (!evaluator.assignType(subtype, types_1.ClassType.cloneAsInstance(genericClass), undefined, constraints, 2 /* AssignTypeFlags.Contravariant */ |
1304
+ 2048 /* AssignTypeFlags.PopulateExpectedType */ |
1305
+ 4096 /* AssignTypeFlags.SkipPopulateUnknownExpectedType */)) {
1306
+ return (0, typeUtils_1.addConditionToType)(subtype, (0, typeUtils_1.getTypeCondition)(classType));
1307
+ }
1308
+ const specializedClass = evaluator.solveAndApplyConstraints(genericClass, constraints, {
1309
+ replaceUnsolved: {
1310
+ scopeIds: (0, typeUtils_1.getTypeVarScopeIds)(classType),
1311
+ useUnknown: true,
1312
+ tupleClassType: evaluator.getTupleClassType(),
1313
+ },
1314
+ });
1315
+ if (!(0, types_1.isInstantiableClass)(specializedClass)) {
1316
+ return (0, typeUtils_1.addConditionToType)(subtype, (0, typeUtils_1.getTypeCondition)(classType));
1317
+ }
1318
+ const results = (gradualArgResults ?? (gradualArgResults = new Map()));
1319
+ narrowedClass = types_1.ClassType.specialize(specializedClass, specializedClass.priv.typeArgs?.map((arg, index) => fillTypeGuardGradualArgs(arg, classType.priv.typeArgs?.[index], results)));
1320
+ }
1321
+ }
1322
+ else if (!evaluator.assignType(subtype, types_1.ClassType.cloneAsInstance(classType))) {
1323
+ return classType.priv.includeSubclasses && !types_1.ClassType.isFinal(classType)
1324
+ ? (0, typeUtils_1.addConditionToType)(subtype, (0, typeUtils_1.getTypeCondition)(classType))
1325
+ : undefined;
1326
+ }
1327
+ }
1328
+ let instance = types_1.ClassType.cloneAsInstance(narrowedClass);
1329
+ if (isExactStringClass) {
1330
+ instance = types_1.ClassType.cloneExactStringFlow(instance, true);
1331
+ }
1332
+ return (0, typeUtils_1.addConditionToType)(instance, subtype.props?.condition);
1333
+ }
1334
+ if (!classType.priv.includeSubclasses) {
1335
+ if (evaluator.assignType(subtype, types_1.ClassType.cloneAsInstance(classType))) {
1336
+ return (0, typeUtils_1.addConditionToType)(types_1.ClassType.cloneAsInstance(classType), (0, typeUtils_1.getTypeCondition)(subtype));
1337
+ }
1338
+ return undefined;
1339
+ }
1340
+ // A subclass of both the subtype and the class could satisfy the
1341
+ // comparison, so eliminate the subtype only if no such class can exist.
1342
+ if ((types_1.ClassType.isFinal(classType) ||
1343
+ isLiteral ||
1344
+ types_1.ClassType.isFinal(instantiableSubtype) ||
1345
+ areDisjointBasesIncompatible(instantiableSubtype, classType)) &&
1346
+ !evaluator.assignType(types_1.ClassType.cloneAsInstance(classType), subtype) &&
1347
+ !evaluator.assignType(subtype, types_1.ClassType.cloneAsInstance(classType))) {
1348
+ return undefined;
1349
+ }
1350
+ if (!(0, types_1.isTypeVar)(unexpandedSubtype) || !types_1.TypeVarType.isSelf(unexpandedSubtype)) {
1351
+ return (0, typeUtils_1.addConditionToType)(subtype, classType.props?.condition);
1352
+ }
1353
+ }
1354
+ // A final class has no subclasses, so it is treated as an exact class.
1355
+ if (!classType.priv.includeSubclasses || types_1.ClassType.isFinal(classType)) {
1356
+ // If the runtime class is exact and it matches, then
1357
+ // we can eliminate it in the negative case.
1358
+ if (matches && (isLiteral || types_1.ClassType.isFinal(instantiableSubtype))) {
1359
+ return undefined;
1360
+ }
1361
+ // We can't eliminate the subtype in the negative
1362
+ // case because it could be a subclass of the type,
1363
+ // in which case `type(x) is y` would fail.
1364
+ return subtype;
1365
+ }
1366
+ }
1367
+ if ((0, types_1.isAnyOrUnknown)(subtype)) {
1368
+ if (metaclassEqualityResults && !allowLegacyEquality) {
1369
+ return subtype;
1370
+ }
1371
+ return isPositiveTest
1372
+ ? types_1.ClassType.cloneAsInstance((0, typeUtils_1.addConditionToType)(classType, (0, typeUtils_1.getTypeCondition)(subtype)))
1373
+ : subtype;
1374
+ }
1375
+ return unexpandedSubtype;
1376
+ });
1377
+ });
1378
+ return (0, types_1.combineTypes)(typesToCombine);
1379
+ }
1380
+ function hasUnresolvedMetaclassInMro(classType) {
1381
+ return classType.shared.mro.some((baseClass) => !(0, types_1.isInstantiableClass)(baseClass) || !!(baseClass.shared.flags & 134217728 /* ClassTypeFlags.HasUnresolvedMetaclass */));
1382
+ }
1383
+ function hasIdentityEqualitySemantics(classType, metaclassEqualityResults) {
1384
+ if (classType.priv.includeSubclasses && !types_1.ClassType.isFinal(classType)) {
1385
+ return false;
1386
+ }
1387
+ if (classType.shared.typeParams.length > 0) {
1388
+ return false;
1389
+ }
1390
+ return hasDeclaredIdentityEqualitySemantics(classType, metaclassEqualityResults);
1391
+ }
1392
+ function hasDeclaredIdentityEqualitySemantics(classType, metaclassEqualityResults) {
1393
+ const metaclass = classType.shared.effectiveMetaclass;
1394
+ if (!metaclass ||
1395
+ !(0, types_1.isInstantiableClass)(metaclass) ||
1396
+ hasUnresolvedMetaclassInMro(classType) ||
1397
+ hasUnresolvedMetaclassInMro(metaclass)) {
1398
+ return false;
1399
+ }
1400
+ if (types_1.ClassType.isBuiltIn(metaclass, 'type')) {
1401
+ return true;
1402
+ }
1403
+ // Cloned metaclasses share method definitions, but the class-specific checks above cannot be shared.
1404
+ const cachedResult = metaclassEqualityResults.get(metaclass.shared);
1405
+ if (cachedResult !== undefined) {
1406
+ return cachedResult;
1407
+ }
1408
+ const result = !(0, operations_1.customMetaclassSupportsMethod)(classType, '__eq__') && !(0, operations_1.customMetaclassSupportsMethod)(classType, '__ne__');
1409
+ metaclassEqualityResults.set(metaclass.shared, result);
1410
+ return result;
1411
+ }
1412
+ function narrowTypeForClassComparison(evaluator, referenceType, classType, isPositiveTest, isIsOperator = true) {
1413
+ // Limit reuse to this invocation so results cannot outlive the evaluation that established them.
1414
+ const metaclassEqualityResults = isIsOperator ? undefined : new Map();
1415
+ if (metaclassEqualityResults && !hasIdentityEqualitySemantics(classType, metaclassEqualityResults)) {
1416
+ return referenceType;
1417
+ }
1418
+ return (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
1419
+ // Multiple class constraints expand to a union with distinct conditions, which equality cannot narrow.
1420
+ if (metaclassEqualityResults &&
1421
+ (0, types_1.isTypeVar)(subtype) &&
1422
+ !subtype.shared.recursiveAlias &&
1423
+ subtype.shared.constraints.length > 1 &&
1424
+ subtype.shared.constraints.every(types_1.isClassInstance)) {
1425
+ return subtype;
1426
+ }
1427
+ let concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
1428
+ if (metaclassEqualityResults &&
1429
+ (!(0, types_1.isInstantiableClass)(concreteSubtype) ||
1430
+ !hasIdentityEqualitySemantics(concreteSubtype, metaclassEqualityResults))) {
1431
+ return subtype;
1432
+ }
1433
+ if (isPositiveTest) {
1434
+ if ((0, types_1.isClassInstance)(concreteSubtype) &&
1435
+ types_1.TypeBase.isInstance(subtype) &&
1436
+ types_1.ClassType.isBuiltIn(concreteSubtype, 'type')) {
1437
+ concreteSubtype =
1438
+ concreteSubtype.priv.typeArgs && concreteSubtype.priv.typeArgs.length > 0
1439
+ ? (0, typeUtils_1.convertToInstantiable)(concreteSubtype.priv.typeArgs[0])
1440
+ : types_1.UnknownType.create();
1441
+ }
1442
+ if ((0, types_1.isAnyOrUnknown)(concreteSubtype)) {
1443
+ return (0, typeUtils_1.addConditionToType)(classType, (0, typeUtils_1.getTypeCondition)(concreteSubtype));
1444
+ }
1445
+ if ((0, types_1.isClass)(concreteSubtype)) {
1446
+ if (types_1.TypeBase.isInstance(concreteSubtype)) {
1447
+ if (!isIsOperator) {
1448
+ return subtype;
1449
+ }
1450
+ return types_1.ClassType.isBuiltIn(concreteSubtype, 'object') ? classType : undefined;
1451
+ }
1452
+ const isSuperType = isFilterSuperclass(subtype, concreteSubtype, classType, classType);
1453
+ if (!classType.priv.includeSubclasses) {
1454
+ // Handle the case where the LHS and RHS operands are specific
1455
+ // classes, as opposed to types that represent classes and their
1456
+ // subclasses.
1457
+ if (!concreteSubtype.priv.includeSubclasses) {
1458
+ return types_1.ClassType.isSameGenericClass(concreteSubtype, classType) ? classType : undefined;
1459
+ }
1460
+ if (isSuperType) {
1461
+ return (0, typeUtils_1.addConditionToType)(classType, (0, typeUtils_1.getTypeCondition)(concreteSubtype));
1462
+ }
1463
+ const isSubType = types_1.ClassType.isDerivedFrom(classType, concreteSubtype);
1464
+ if (isSubType) {
1465
+ return (0, typeUtils_1.addConditionToType)(classType, (0, typeUtils_1.getTypeCondition)(concreteSubtype));
1466
+ }
1467
+ return undefined;
1468
+ }
1469
+ if (types_1.ClassType.isFinal(concreteSubtype) && !isSuperType) {
1470
+ return undefined;
1471
+ }
1472
+ }
1473
+ }
1474
+ else {
1475
+ if ((0, types_1.isInstantiableClass)(concreteSubtype) &&
1476
+ types_1.ClassType.isSameGenericClass(classType, concreteSubtype) &&
1477
+ types_1.ClassType.isFinal(classType)) {
1478
+ return undefined;
1479
+ }
1480
+ }
1481
+ return subtype;
1482
+ });
1483
+ }
1484
+ function isFilterSuperclass(varType, concreteVarType, filterType, concreteFilterType) {
1485
+ if ((0, types_1.isTypeVar)(filterType) || concreteFilterType.priv.literalValue !== undefined) {
1486
+ return (0, types_1.isTypeSame)((0, typeUtils_1.convertToInstance)(filterType), varType);
1487
+ }
1488
+ // If the filter type represents all possible subclasses
1489
+ // of a type, we can't make any statements about its superclass
1490
+ // relationship with concreteVarType.
1491
+ if (concreteFilterType.priv.includeSubclasses) {
1492
+ return false;
1493
+ }
1494
+ if (types_1.ClassType.isDerivedFrom(concreteVarType, concreteFilterType)) {
1495
+ return true;
1496
+ }
1497
+ // Handle the special case where the variable type is a TypedDict and
1498
+ // we're filtering against 'dict'. TypedDict isn't derived from dict,
1499
+ // but at runtime, isinstance returns True.
1500
+ if (types_1.ClassType.isBuiltIn(concreteFilterType, 'dict') && types_1.ClassType.isTypedDictClass(concreteVarType)) {
1501
+ return true;
1502
+ }
1503
+ return false;
1504
+ }
1505
+ function isPrimitiveBackedEnumClass(classType) {
1506
+ if (!types_1.ClassType.isEnumClass(classType)) {
1507
+ return false;
1508
+ }
1509
+ return (0, typeUtils_1.derivesFromStdlibClass)(classType, 'int') || (0, typeUtils_1.derivesFromStdlibClass)(classType, 'str');
1510
+ }
1511
+ function isPrimitiveBackedEnumAndPrimitive(enumType, primitiveType) {
1512
+ if (types_1.ClassType.isEnumClass(primitiveType) || !isPrimitiveBackedEnumClass(enumType)) {
1513
+ return false;
1514
+ }
1515
+ // Exclude bool, which derives from int but whose literal values are distinct
1516
+ // from the corresponding int literals.
1517
+ if (types_1.ClassType.isBuiltIn(primitiveType, 'int')) {
1518
+ return (0, typeUtils_1.derivesFromStdlibClass)(enumType, 'int');
1519
+ }
1520
+ if (types_1.ClassType.isBuiltIn(primitiveType, 'str')) {
1521
+ return (0, typeUtils_1.derivesFromStdlibClass)(enumType, 'str');
1522
+ }
1523
+ return false;
1524
+ }
1525
+ function unwrapPrimitiveBackedEnumLiteral(classType) {
1526
+ const literalValue = classType.priv.literalValue;
1527
+ if (!(literalValue instanceof types_1.EnumLiteral) || !isPrimitiveBackedEnumClass(classType)) {
1528
+ return classType;
1529
+ }
1530
+ const itemType = literalValue.itemType;
1531
+ if ((0, types_1.isClassInstance)(itemType) && itemType.priv.literalValue !== undefined) {
1532
+ return itemType;
1533
+ }
1534
+ return classType;
1535
+ }
1536
+ function isLiteralValueEqualAtRuntime(type1, type2) {
1537
+ return types_1.ClassType.isLiteralValueSame(unwrapPrimitiveBackedEnumLiteral(type1), unwrapPrimitiveBackedEnumLiteral(type2));
1538
+ }
1539
+ function getInnermostNewTypeBaseInstance(subtype) {
1540
+ if (!(0, types_1.isClassInstance)(subtype) || !types_1.ClassType.isNewTypeClass(subtype)) {
1541
+ return undefined;
1542
+ }
1543
+ let currentType = subtype;
1544
+ while ((0, types_1.isClassInstance)(currentType) && types_1.ClassType.isNewTypeClass(currentType)) {
1545
+ if (currentType.shared.baseClasses.length === 0) {
1546
+ return undefined;
1547
+ }
1548
+ const baseClass = currentType.shared.baseClasses[0];
1549
+ if (!(0, types_1.isClass)(baseClass)) {
1550
+ return undefined;
1551
+ }
1552
+ currentType = types_1.ClassType.cloneAsInstance(baseClass);
1553
+ }
1554
+ return currentType;
1555
+ }
1556
+ function narrowTypeForLiteralComparison(evaluator, referenceType, literalType, isPositiveTest, isIsOperator) {
1557
+ return evaluator.mapSubtypesExpandTypeVars(referenceType, /* options */ undefined, (subtype) => {
1558
+ subtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
1559
+ if ((0, types_1.isAnyOrUnknown)(subtype)) {
1560
+ if (isPositiveTest) {
1561
+ return literalType;
1562
+ }
1563
+ return subtype;
1564
+ }
1565
+ // Determine whether this is a comparison between a primitive-backed enum
1566
+ // (e.g. IntEnum or StrEnum) and its underlying primitive type. Such a
1567
+ // comparison can be used for narrowing because the enum member compares
1568
+ // equal to its underlying primitive value at runtime.
1569
+ const isPrimitiveBackedEnumComparison = !isIsOperator &&
1570
+ (0, types_1.isClassInstance)(subtype) &&
1571
+ (isPrimitiveBackedEnumAndPrimitive(subtype, literalType) ||
1572
+ isPrimitiveBackedEnumAndPrimitive(literalType, subtype));
1573
+ if ((0, types_1.isClassInstance)(subtype) &&
1574
+ (types_1.ClassType.isSameGenericClass(literalType, subtype) || isPrimitiveBackedEnumComparison)) {
1575
+ if (subtype.priv.literalValue !== undefined) {
1576
+ const literalValueMatches = isPrimitiveBackedEnumComparison
1577
+ ? isLiteralValueEqualAtRuntime(subtype, literalType)
1578
+ : types_1.ClassType.isLiteralValueSame(subtype, literalType);
1579
+ if (isPositiveTest) {
1580
+ return literalValueMatches ? subtype : undefined;
1581
+ }
1582
+ const isSingleton = types_1.ClassType.isEnumClass(literalType) ||
1583
+ (0, typeUtils_1.isSentinelLiteral)(subtype) ||
1584
+ types_1.ClassType.isBuiltIn(literalType, 'bool');
1585
+ // For negative tests, we can eliminate the literal value if it doesn't match,
1586
+ // but only for equality tests or for 'is' tests that involve enums, bools, or sentinels.
1587
+ return literalValueMatches && (isSingleton || !isIsOperator) ? undefined : subtype;
1588
+ }
1589
+ if (isPositiveTest) {
1590
+ if (isPrimitiveBackedEnumComparison) {
1591
+ // If the reference type is the enum, attempt to find the member
1592
+ // whose value matches the primitive literal. If no member can be
1593
+ // identified (e.g. for an IntFlag class, whose members cannot be
1594
+ // enumerated), retain the reference type rather than narrowing it
1595
+ // to the primitive literal type.
1596
+ if (types_1.ClassType.isEnumClass(subtype)) {
1597
+ const allLiteralTypes = enumerateLiteralsForType(evaluator, subtype);
1598
+ const match = allLiteralTypes?.find((type) => isLiteralValueEqualAtRuntime(type, literalType));
1599
+ return match ?? subtype;
1600
+ }
1601
+ // The reference type is the primitive type, so narrowing it to the
1602
+ // enum literal would lose its (potentially derived) class. Retain
1603
+ // the reference type instead.
1604
+ return subtype;
1605
+ }
1606
+ return literalType;
1607
+ }
1608
+ // If we're able to enumerate all possible literal values
1609
+ // (for bool or enum), we can eliminate all others in a negative test.
1610
+ const allLiteralTypes = enumerateLiteralsForType(evaluator, subtype);
1611
+ if (allLiteralTypes && allLiteralTypes.length > 0) {
1612
+ return (0, types_1.combineTypes)(allLiteralTypes.filter((type) => isPrimitiveBackedEnumComparison
1613
+ ? !isLiteralValueEqualAtRuntime(type, literalType)
1614
+ : !types_1.ClassType.isLiteralValueSame(type, literalType)));
1615
+ }
1616
+ return subtype;
1617
+ }
1618
+ if (isPositiveTest) {
1619
+ if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, 'LiteralString')) {
1620
+ return literalType;
1621
+ }
1622
+ if (isIsOperator || (0, typeUtils_1.isNoneInstance)(subtype)) {
1623
+ const compareType = getInnermostNewTypeBaseInstance(subtype) ?? subtype;
1624
+ const isSubtype = evaluator.assignType(compareType, literalType);
1625
+ if (isSubtype) {
1626
+ return (0, types_1.isClassInstance)(subtype) && types_1.ClassType.isNewTypeClass(subtype) ? subtype : literalType;
1627
+ }
1628
+ return undefined;
1629
+ }
1630
+ }
1631
+ return subtype;
1632
+ });
1633
+ }
1634
+ function enumerateLiteralsForType(evaluator, type) {
1635
+ if (types_1.ClassType.isBuiltIn(type, 'bool')) {
1636
+ // Booleans have only two types: True and False.
1637
+ return [
1638
+ types_1.ClassType.cloneWithLiteral(type, /* value */ true),
1639
+ types_1.ClassType.cloneWithLiteral(type, /* value */ false),
1640
+ ];
1641
+ }
1642
+ if (types_1.ClassType.isEnumClass(type)) {
1643
+ // Enum expansion doesn't apply if the member set cannot be statically
1644
+ // enumerated or if the class derives from enum.Flag.
1645
+ if (types_1.ClassType.isEnumMemberSetMayBeDynamicallyModified(type) ||
1646
+ type.shared.mro.some((mroClass) => (0, types_1.isClass)(mroClass) && types_1.ClassType.isBuiltIn(mroClass, 'Flag'))) {
1647
+ return undefined;
1648
+ }
1649
+ // Enumerate all of the values in this enumeration.
1650
+ const enumList = [];
1651
+ const fields = types_1.ClassType.getSymbolTable(type);
1652
+ fields.forEach((symbol, name) => {
1653
+ if (!symbol.isIgnoredForProtocolMatch()) {
1654
+ let symbolType = evaluator.getEffectiveTypeOfSymbol(symbol);
1655
+ symbolType = (0, enums_1.transformTypeForEnumMember)(evaluator, type, name, (0, analyzerNodeInfo_1.getInfoReader)(evaluator)) ?? symbolType;
1656
+ if ((0, types_1.isClassInstance)(symbolType) &&
1657
+ types_1.ClassType.isSameGenericClass(type, symbolType) &&
1658
+ symbolType.priv.literalValue !== undefined) {
1659
+ enumList.push(symbolType);
1660
+ }
1661
+ }
1662
+ });
1663
+ return enumList;
1664
+ }
1665
+ return undefined;
1666
+ }
1667
+ function isNameSameScope(evaluator, reference, expression) {
1668
+ const refSymbol = evaluator.lookUpSymbolRecursive(reference, reference.d.value, /* honorCodeFlow */ false);
1669
+ const exprSymbol = evaluator.lookUpSymbolRecursive(expression, expression.d.value, /* honorCodeFlow */ false);
1670
+ if (!refSymbol || !exprSymbol) {
1671
+ // This shouldn't happen, but just to be safe...
1672
+ return true;
1673
+ }
1674
+ const refScope = refSymbol.scope;
1675
+ const exprScope = exprSymbol.scope;
1676
+ if (refScope === exprScope) {
1677
+ return true;
1678
+ }
1679
+ return (0, scopeUtils_1.isScopeContainedWithin)(refScope, exprScope);
1680
+ }
1681
+ function areDisjointBasesIncompatible(classType1, classType2) {
1682
+ const base1 = types_1.ClassType.getDisjointBase(classType1);
1683
+ const base2 = types_1.ClassType.getDisjointBase(classType2);
1684
+ return !!base1 && !!base2 && !types_1.ClassType.getMostDerivedDisjointBase([base1, base2]);
1685
+ }
1686
+ function fillTypeGuardGradualArgs(input, hint, results, recursionCount = 0) {
1687
+ if (!hint || input === hint || recursionCount > types_1.maxTypeRecursionCount) {
1688
+ return input;
1689
+ }
1690
+ if ((0, types_1.isAnyOrUnknown)(input)) {
1691
+ return (0, types_1.isAnyOrUnknown)(hint) ? ((0, types_1.isAny)(hint) ? hint : input) : hint;
1692
+ }
1693
+ if (!(0, types_1.isClass)(input) || !(0, types_1.isClass)(hint) || !types_1.ClassType.isSameGenericClass(input, hint)) {
1694
+ return input;
1695
+ }
1696
+ let inputResults = results.get(input);
1697
+ const cachedResult = inputResults?.get(hint);
1698
+ if (cachedResult !== undefined) {
1699
+ return cachedResult;
1700
+ }
1701
+ if (!inputResults) {
1702
+ inputResults = new Map();
1703
+ results.set(input, inputResults);
1704
+ }
1705
+ // Bound recursive aliases and reuse shared argument graphs within this narrowing operation.
1706
+ inputResults.set(hint, input);
1707
+ const inputTuple = input.priv.tupleTypeArgs;
1708
+ const hintTuple = hint.priv.tupleTypeArgs;
1709
+ if (inputTuple || hintTuple) {
1710
+ if (!inputTuple ||
1711
+ !hintTuple ||
1712
+ inputTuple.length !== hintTuple.length ||
1713
+ inputTuple.some((arg, index) => arg.isUnbounded !== hintTuple[index].isUnbounded ||
1714
+ !!arg.isOptional !== !!hintTuple[index].isOptional)) {
1715
+ return input;
1716
+ }
1717
+ const tupleArgs = inputTuple.map((arg, index) => ({
1718
+ ...arg,
1719
+ type: fillTypeGuardGradualArgs(arg.type, hintTuple[index].type, results, recursionCount + 1),
1720
+ }));
1721
+ const result = tupleArgs.every((arg, index) => arg.type === inputTuple[index].type)
1722
+ ? input
1723
+ : (0, typeUtils_1.specializeTupleClass)(input, tupleArgs, input.priv.isTypeArgExplicit, input.priv.isUnpacked);
1724
+ inputResults.set(hint, result);
1725
+ return result;
1726
+ }
1727
+ const inputArgs = input.priv.typeArgs;
1728
+ const hintArgs = hint.priv.typeArgs;
1729
+ if (!inputArgs || !hintArgs || inputArgs.length !== hintArgs.length) {
1730
+ return input;
1731
+ }
1732
+ const typeArgs = inputArgs.map((arg, index) => fillTypeGuardGradualArgs(arg, hintArgs[index], results, recursionCount + 1));
1733
+ const result = typeArgs.every((arg, index) => arg === inputArgs[index])
1734
+ ? input
1735
+ : types_1.ClassType.specialize(input, typeArgs, input.priv.isTypeArgExplicit);
1736
+ inputResults.set(hint, result);
1737
+ return result;
1738
+ }
1739
+ function narrowTypeForUserDefinedTypeGuard(evaluator, type, typeGuardType, isPositiveTest, isStrictTypeGuard, errorNode, nodeInfo, narrowTypeForInstanceOrSubclassCallback) {
1740
+ // For non-strict type guards, always narrow to the typeGuardType
1741
+ // in the positive case and don't narrow in the negative case.
1742
+ if (!isStrictTypeGuard) {
1743
+ let result = type;
1744
+ if (isPositiveTest) {
1745
+ result = typeGuardType;
1746
+ // If the type guard is a non-constrained TypeVar, add a
1747
+ // condition to the resulting type.
1748
+ if ((0, types_1.isTypeVar)(type) && !(0, types_1.isParamSpec)(type) && !types_1.TypeVarType.hasConstraints(type)) {
1749
+ result = (0, typeUtils_1.addConditionToType)(result, [{ typeVar: type, constraintIndex: 0 }]);
1750
+ }
1751
+ return result;
1752
+ }
1753
+ return result;
1754
+ }
1755
+ const filterTypes = [];
1756
+ (0, typeUtils_1.doForEachSubtype)(typeGuardType, (typeGuardSubtype) => {
1757
+ filterTypes.push((0, typeUtils_1.convertToInstantiable)(typeGuardSubtype));
1758
+ });
1759
+ return narrowTypeForInstanceOrSubclassCallback(evaluator, type, filterTypes,
1760
+ /* isInstanceCheck */ true,
1761
+ /* isTypeIsCheck */ true, isPositiveTest, errorNode, nodeInfo);
1762
+ }
1763
+ //# sourceMappingURL=typeGuardNarrowing.js.map