@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.
- package/dist/analyzer/binder.d.ts +1 -0
- package/dist/analyzer/binder.js +209 -4
- package/dist/analyzer/binder.js.map +1 -1
- package/dist/analyzer/codeFlowEngine.js +28 -3
- package/dist/analyzer/codeFlowEngine.js.map +1 -1
- package/dist/analyzer/constructorTransform.js +12 -0
- package/dist/analyzer/constructorTransform.js.map +1 -1
- package/dist/analyzer/constructors.d.ts +2 -2
- package/dist/analyzer/constructors.js +69 -10
- package/dist/analyzer/constructors.js.map +1 -1
- package/dist/analyzer/decorators.d.ts +1 -1
- package/dist/analyzer/decorators.js.map +1 -1
- package/dist/analyzer/enums.d.ts +10 -3
- package/dist/analyzer/enums.js +389 -2
- package/dist/analyzer/enums.js.map +1 -1
- package/dist/analyzer/functionTransform.d.ts +5 -0
- package/dist/analyzer/functionTransform.js +6 -3
- package/dist/analyzer/functionTransform.js.map +1 -1
- package/dist/analyzer/missingBindingMetadata.d.ts +6 -0
- package/dist/analyzer/missingBindingMetadata.js +22 -0
- package/dist/analyzer/missingBindingMetadata.js.map +1 -0
- package/dist/analyzer/namedTuples.d.ts +4 -1
- package/dist/analyzer/namedTuples.js +1 -0
- package/dist/analyzer/namedTuples.js.map +1 -1
- package/dist/analyzer/operations.js +81 -4
- package/dist/analyzer/operations.js.map +1 -1
- package/dist/analyzer/patternMatching.d.ts +5 -1
- package/dist/analyzer/patternMatching.js +3 -0
- package/dist/analyzer/patternMatching.js.map +1 -1
- package/dist/analyzer/program.d.ts +3 -0
- package/dist/analyzer/program.js +71 -1
- package/dist/analyzer/program.js.map +1 -1
- package/dist/analyzer/protocols.d.ts +1 -0
- package/dist/analyzer/protocols.js +171 -10
- package/dist/analyzer/protocols.js.map +1 -1
- package/dist/analyzer/scope.d.ts +3 -0
- package/dist/analyzer/scope.js +28 -6
- package/dist/analyzer/scope.js.map +1 -1
- package/dist/analyzer/symbol.d.ts +4 -1
- package/dist/analyzer/symbol.js +8 -0
- package/dist/analyzer/symbol.js.map +1 -1
- package/dist/analyzer/tuples.d.ts +1 -1
- package/dist/analyzer/tuples.js.map +1 -1
- package/dist/analyzer/typeCacheUtils.d.ts +1 -0
- package/dist/analyzer/typeCacheUtils.js +10 -0
- package/dist/analyzer/typeCacheUtils.js.map +1 -1
- package/dist/analyzer/typeEvaluator/boundMethodSpecialization.d.ts +15 -0
- package/dist/analyzer/typeEvaluator/boundMethodSpecialization.js +98 -0
- package/dist/analyzer/typeEvaluator/boundMethodSpecialization.js.map +1 -0
- package/dist/analyzer/typeEvaluator/classConstruction.d.ts +25 -0
- package/dist/analyzer/typeEvaluator/classConstruction.js +251 -0
- package/dist/analyzer/typeEvaluator/classConstruction.js.map +1 -0
- package/dist/analyzer/typeEvaluator/collectionInference.d.ts +41 -0
- package/dist/analyzer/typeEvaluator/collectionInference.js +695 -0
- package/dist/analyzer/typeEvaluator/collectionInference.js.map +1 -0
- package/dist/analyzer/typeEvaluator/diagnostics.d.ts +33 -0
- package/dist/analyzer/typeEvaluator/diagnostics.js +198 -0
- package/dist/analyzer/typeEvaluator/diagnostics.js.map +1 -0
- package/dist/analyzer/typeEvaluator/evaluatorCore.d.ts +80 -0
- package/dist/analyzer/typeEvaluator/evaluatorCore.js +1132 -0
- package/dist/analyzer/typeEvaluator/evaluatorCore.js.map +1 -0
- package/dist/analyzer/typeEvaluator/evaluatorNarrowing.d.ts +17 -0
- package/dist/analyzer/typeEvaluator/evaluatorNarrowing.js +370 -0
- package/dist/analyzer/typeEvaluator/evaluatorNarrowing.js.map +1 -0
- package/dist/analyzer/typeEvaluator/expressionEvaluation.d.ts +81 -0
- package/dist/analyzer/typeEvaluator/expressionEvaluation.js +1802 -0
- package/dist/analyzer/typeEvaluator/expressionEvaluation.js.map +1 -0
- package/dist/analyzer/typeEvaluator/flowAnalysis.d.ts +33 -0
- package/dist/analyzer/typeEvaluator/flowAnalysis.js +217 -0
- package/dist/analyzer/typeEvaluator/flowAnalysis.js.map +1 -0
- package/dist/analyzer/typeEvaluator/internals.d.ts +138 -0
- package/dist/analyzer/typeEvaluator/internals.js +10 -0
- package/dist/analyzer/typeEvaluator/internals.js.map +1 -0
- package/dist/analyzer/typeEvaluator/literalTypes.d.ts +3 -0
- package/dist/analyzer/typeEvaluator/literalTypes.js +52 -0
- package/dist/analyzer/typeEvaluator/literalTypes.js.map +1 -0
- package/dist/analyzer/typeEvaluator/memberResolution.d.ts +79 -0
- package/dist/analyzer/typeEvaluator/memberResolution.js +1007 -0
- package/dist/analyzer/typeEvaluator/memberResolution.js.map +1 -0
- package/dist/analyzer/typeEvaluator/overrideValidation.d.ts +15 -0
- package/dist/analyzer/typeEvaluator/overrideValidation.js +422 -0
- package/dist/analyzer/typeEvaluator/overrideValidation.js.map +1 -0
- package/dist/analyzer/typeEvaluator/returnTypeInference.d.ts +33 -0
- package/dist/analyzer/typeEvaluator/returnTypeInference.js +226 -0
- package/dist/analyzer/typeEvaluator/returnTypeInference.js.map +1 -0
- package/dist/analyzer/typeEvaluator/specialFormCreation.d.ts +39 -0
- package/dist/analyzer/typeEvaluator/specialFormCreation.js +1728 -0
- package/dist/analyzer/typeEvaluator/specialFormCreation.js.map +1 -0
- package/dist/analyzer/typeEvaluator/tupleUnpacking.d.ts +2 -0
- package/dist/analyzer/typeEvaluator/tupleUnpacking.js +36 -0
- package/dist/analyzer/typeEvaluator/tupleUnpacking.js.map +1 -0
- package/dist/analyzer/typeEvaluator/typeCompatibility.d.ts +36 -0
- package/dist/analyzer/typeEvaluator/typeCompatibility.js +1333 -0
- package/dist/analyzer/typeEvaluator/typeCompatibility.js.map +1 -0
- package/dist/analyzer/typeEvaluator/typeGuardNarrowing.d.ts +187 -0
- package/dist/analyzer/typeEvaluator/typeGuardNarrowing.js +1763 -0
- package/dist/analyzer/typeEvaluator/typeGuardNarrowing.js.map +1 -0
- package/dist/analyzer/typeEvaluator/typeVarHandling.d.ts +48 -0
- package/dist/analyzer/typeEvaluator/typeVarHandling.js +756 -0
- package/dist/analyzer/typeEvaluator/typeVarHandling.js.map +1 -0
- package/dist/analyzer/typeEvaluator.d.ts +3 -31
- package/dist/analyzer/typeEvaluator.js +5093 -13740
- package/dist/analyzer/typeEvaluator.js.map +1 -1
- package/dist/analyzer/typeGuards.d.ts +2 -2
- package/dist/analyzer/typeGuards.js +213 -1568
- package/dist/analyzer/typeGuards.js.map +1 -1
- package/dist/analyzer/typeUtils.js +6 -2
- package/dist/analyzer/typeUtils.js.map +1 -1
- package/dist/analyzer/typedDicts.js +125 -1
- package/dist/analyzer/typedDicts.js.map +1 -1
- package/dist/analyzer/types.d.ts +6 -1
- package/dist/analyzer/types.js +32 -4
- package/dist/analyzer/types.js.map +1 -1
- package/dist/browser/browserConnection.d.ts +12 -0
- package/dist/browser/browserConnection.js +23 -0
- package/dist/browser/browserConnection.js.map +1 -0
- package/dist/browser/browserFileSystem.d.ts +73 -0
- package/dist/browser/browserFileSystem.js +578 -0
- package/dist/browser/browserFileSystem.js.map +1 -0
- package/dist/browser/browserHost.d.ts +4 -0
- package/dist/browser/browserHost.js +10 -0
- package/dist/browser/browserHost.js.map +1 -0
- package/dist/browser/browserProcess.d.ts +1 -0
- package/dist/browser/browserProcess.js +17 -0
- package/dist/browser/browserProcess.js.map +1 -0
- package/dist/browser/browserServer.d.ts +8 -0
- package/dist/browser/browserServer.js +32 -0
- package/dist/browser/browserServer.js.map +1 -0
- package/dist/browser/cancellation/common.d.ts +10 -0
- package/dist/browser/cancellation/common.js +114 -0
- package/dist/browser/cancellation/common.js.map +1 -0
- package/dist/browser/cancellation/objectURLReceiverStrategy.d.ts +5 -0
- package/dist/browser/cancellation/objectURLReceiverStrategy.js +37 -0
- package/dist/browser/cancellation/objectURLReceiverStrategy.js.map +1 -0
- package/dist/browser/cancellation/objectURLSenderStrategy.d.ts +7 -0
- package/dist/browser/cancellation/objectURLSenderStrategy.js +32 -0
- package/dist/browser/cancellation/objectURLSenderStrategy.js.map +1 -0
- package/dist/browser/worker.d.ts +1 -0
- package/dist/browser/worker.js +33 -0
- package/dist/browser/worker.js.map +1 -0
- package/dist/common/processUtils.d.ts +1 -0
- package/dist/common/processUtils.js +38 -0
- package/dist/common/processUtils.js.map +1 -1
- package/dist/common/windowsProcessTree.json +20 -2
- package/dist/localization/package.nls.cs.json +2 -0
- package/dist/localization/package.nls.de.json +2 -0
- package/dist/localization/package.nls.es.json +2 -0
- package/dist/localization/package.nls.fr.json +2 -0
- package/dist/localization/package.nls.it.json +2 -0
- package/dist/localization/package.nls.ja.json +2 -0
- package/dist/localization/package.nls.ko.json +2 -0
- package/dist/localization/package.nls.pl.json +2 -0
- package/dist/localization/package.nls.pt-br.json +2 -0
- package/dist/localization/package.nls.qps-ploc.json +2 -0
- package/dist/localization/package.nls.ru.json +2 -0
- package/dist/localization/package.nls.tr.json +2 -0
- package/dist/localization/package.nls.zh-cn.json +2 -0
- package/dist/localization/package.nls.zh-tw.json +2 -0
- package/dist/pyrightServer.d.ts +34 -0
- package/dist/pyrightServer.js +239 -0
- package/dist/pyrightServer.js.map +1 -0
- package/dist/server.d.ts +3 -23
- package/dist/server.js +12 -232
- package/dist/server.js.map +1 -1
- package/dist/tests/benchmarks/typeInferenceComparison.d.ts +1 -0
- package/dist/tests/benchmarks/typeInferenceComparison.js +1235 -0
- package/dist/tests/benchmarks/typeInferenceComparison.js.map +1 -0
- package/dist/tests/benchmarks/typeInferencePyrightEntry.d.ts +1 -0
- package/dist/tests/benchmarks/typeInferencePyrightEntry.js +53 -0
- package/dist/tests/benchmarks/typeInferencePyrightEntry.js.map +1 -0
- package/dist/tests/browserCancellation.test.d.ts +1 -0
- package/dist/tests/browserCancellation.test.js +63 -0
- package/dist/tests/browserCancellation.test.js.map +1 -0
- package/dist/tests/browserServer.test.d.ts +1 -0
- package/dist/tests/browserServer.test.js +177 -0
- package/dist/tests/browserServer.test.js.map +1 -0
- package/dist/tests/constraintSolver.test.js +45 -0
- package/dist/tests/constraintSolver.test.js.map +1 -1
- package/dist/tests/mypyPrimerAnalysis.test.js +15 -1
- package/dist/tests/mypyPrimerAnalysis.test.js.map +1 -1
- package/dist/tests/signatureHelp.test.js +22 -0
- package/dist/tests/signatureHelp.test.js.map +1 -1
- package/dist/tests/typeCacheUtils.test.js +46 -0
- package/dist/tests/typeCacheUtils.test.js.map +1 -1
- package/dist/tests/typeEvaluator1.test.js +108 -0
- package/dist/tests/typeEvaluator1.test.js.map +1 -1
- package/dist/tests/typeEvaluator2.test.js +14 -0
- package/dist/tests/typeEvaluator2.test.js.map +1 -1
- package/dist/tests/typeEvaluator3.test.js +20 -0
- package/dist/tests/typeEvaluator3.test.js.map +1 -1
- package/dist/tests/typeEvaluator4.test.js +32 -0
- package/dist/tests/typeEvaluator4.test.js.map +1 -1
- package/dist/tests/typeEvaluator5.test.js +7 -1
- package/dist/tests/typeEvaluator5.test.js.map +1 -1
- package/dist/tests/typeEvaluator6.test.js +4 -0
- package/dist/tests/typeEvaluator6.test.js.map +1 -1
- package/dist/tests/typeEvaluator7.test.js +600 -1
- package/dist/tests/typeEvaluator7.test.js.map +1 -1
- package/dist/tests/typeEvaluator8.test.js +46 -0
- package/dist/tests/typeEvaluator8.test.js.map +1 -1
- package/dist/tests/typeUtils.test.js +28 -0
- package/dist/tests/typeUtils.test.js.map +1 -1
- package/dist/typeServer/stubGenerator.js +136 -3
- package/dist/typeServer/stubGenerator.js.map +1 -1
- package/dist/typeServer/typeServerConversionUtils.js +13 -0
- package/dist/typeServer/typeServerConversionUtils.js.map +1 -1
- package/package.json +3 -1
|
@@ -537,7 +537,9 @@ test.each([false, true])('Protocol36CacheReuse positiveFirst=%s', (positiveFirst
|
|
|
537
537
|
assert.strictEqual(assign(acceptedType), true);
|
|
538
538
|
const diagnostics = new diagnostic_1.DiagnosticAddendum();
|
|
539
539
|
assert.strictEqual(assign(rejectedType, diagnostics), false);
|
|
540
|
-
|
|
540
|
+
const diagnosticText = diagnostics.getString();
|
|
541
|
+
expect(diagnosticText).toContain('"__iter__" is an incompatible type');
|
|
542
|
+
expect(diagnosticText).toContain('Type "() -> Iterator[int]" is not assignable to type "() -> Iterator[str | NestedSequence[str]]"');
|
|
541
543
|
assert.ok(constraints.isSame(originalConstraints));
|
|
542
544
|
assert.strictEqual(assign(rejectedType), false);
|
|
543
545
|
assert.strictEqual(assign(acceptedType), true);
|
|
@@ -547,6 +549,57 @@ test.each([false, true])('Protocol36CacheReuse positiveFirst=%s', (positiveFirst
|
|
|
547
549
|
assert.strictEqual(evaluator.printType(evaluator.solveAndApplyConstraints(typeParam, inferredConstraints)), 'int');
|
|
548
550
|
}
|
|
549
551
|
});
|
|
552
|
+
test('ProtocolMethodTypeParamBound', () => {
|
|
553
|
+
const code = `
|
|
554
|
+
// @filename: test.py
|
|
555
|
+
//// from typing import Protocol
|
|
556
|
+
////
|
|
557
|
+
//// class Expected(Protocol):
|
|
558
|
+
//// def f[U: str](self, value: U) -> U: ...
|
|
559
|
+
////
|
|
560
|
+
//// class Actual:
|
|
561
|
+
//// def f[U: int](self, value: U) -> U: ...
|
|
562
|
+
////
|
|
563
|
+
//// def check(source: Actual):
|
|
564
|
+
//// invalid: Expected = source
|
|
565
|
+
`;
|
|
566
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
567
|
+
const file = state.testData.files[0];
|
|
568
|
+
const results = TestUtils.getAnalysisResults(state.program, [file.fileUri], state.configOptions);
|
|
569
|
+
TestUtils.validateResults(results, 1);
|
|
570
|
+
const message = results[0].errors[0].message;
|
|
571
|
+
expect(message).toContain('"f" is an incompatible type');
|
|
572
|
+
expect(message).toContain('Type "U@f" is not assignable to type "int"');
|
|
573
|
+
});
|
|
574
|
+
test('ProtocolMethodParamNameAndKind', () => {
|
|
575
|
+
const code = `
|
|
576
|
+
// @filename: test.py
|
|
577
|
+
//// from typing import Protocol
|
|
578
|
+
////
|
|
579
|
+
//// class NameProto[T](Protocol):
|
|
580
|
+
//// def f(self, x: T) -> None: ...
|
|
581
|
+
////
|
|
582
|
+
//// class NameImpl:
|
|
583
|
+
//// def f(self, y: int) -> None: ...
|
|
584
|
+
////
|
|
585
|
+
//// class KindProto[T](Protocol):
|
|
586
|
+
//// def f(self, *, x: T) -> None: ...
|
|
587
|
+
////
|
|
588
|
+
//// class KindImpl:
|
|
589
|
+
//// def f(self, x: int, /) -> None: ...
|
|
590
|
+
////
|
|
591
|
+
//// def check(a: NameImpl, b: KindImpl):
|
|
592
|
+
//// v1: NameProto[int] = a
|
|
593
|
+
//// v2: KindProto[int] = b
|
|
594
|
+
`;
|
|
595
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
596
|
+
const file = state.testData.files[0];
|
|
597
|
+
const results = TestUtils.getAnalysisResults(state.program, [file.fileUri], state.configOptions);
|
|
598
|
+
TestUtils.validateResults(results, 2);
|
|
599
|
+
const [nameError, kindError] = results[0].errors;
|
|
600
|
+
expect(nameError.message).toContain('Type "(y: int) -> None" is not assignable to type "(x: T@NameProto) -> None"');
|
|
601
|
+
expect(kindError.message).toContain('Type "(x: int, /) -> None" is not assignable to type "(*, x: T@KindProto) -> None"');
|
|
602
|
+
});
|
|
550
603
|
test.each([
|
|
551
604
|
['list[int]', false],
|
|
552
605
|
['list[list[int]]', false],
|
|
@@ -715,6 +768,60 @@ test('Protocol55UntypedDecorators', () => {
|
|
|
715
768
|
const untypedDecoratorErrors = analysisResults[0].errors.filter((diag) => diag.getRule() === diagnosticRules_1.DiagnosticRule.reportUntypedClassDecorator);
|
|
716
769
|
assert.deepStrictEqual(untypedDecoratorErrors.map((diag) => diag.range.start.line), [127, 135, 142, 149, 158, 165, 190]);
|
|
717
770
|
});
|
|
771
|
+
test('Protocol56', () => {
|
|
772
|
+
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['protocol56.py']);
|
|
773
|
+
TestUtils.validateResults(analysisResults, 4);
|
|
774
|
+
const defaultTypeError = analysisResults[0].errors.find((error) => error.message.includes('"list[object]"'));
|
|
775
|
+
assert.strictEqual(defaultTypeError?.getRule(), diagnosticRules_1.DiagnosticRule.reportArgumentType);
|
|
776
|
+
});
|
|
777
|
+
test.each(['source', 'destination'].flatMap((side) => ['Any', 'int'].flatMap((defaultType) => [false, true].flatMap((diagnostics) => [false, true].map((positiveFirst) => ({ side, defaultType, diagnostics, positiveFirst }))))))('ProtocolDefaultCache $side default=$defaultType diagnostics=$diagnostics positiveFirst=$positiveFirst', ({ side, defaultType, diagnostics, positiveFirst }) => {
|
|
778
|
+
const sourceIsGeneric = side === 'source';
|
|
779
|
+
const state = (0, testState_1.parseAndGetTestState)(`
|
|
780
|
+
// @filename: test.py
|
|
781
|
+
//// from typing import Any, Protocol
|
|
782
|
+
//// class Source${sourceIsGeneric ? `[T = ${defaultType}]` : ''}:
|
|
783
|
+
//// ${sourceIsGeneric ? 'def put(self, value: T) -> None: ...' : 'def get(self) -> int: ...'}
|
|
784
|
+
//// class Target${sourceIsGeneric ? '' : `[T = ${defaultType}]`}(Protocol):
|
|
785
|
+
//// ${sourceIsGeneric ? 'def put(self, value: int) -> None: ...' : 'def get(self) -> T: ...'}
|
|
786
|
+
//// def check(
|
|
787
|
+
//// good_source: ${sourceIsGeneric ? 'Source[int]' : 'Source'},
|
|
788
|
+
//// bad_source: ${sourceIsGeneric ? 'Source[str]' : 'Source'},
|
|
789
|
+
//// good_target: ${sourceIsGeneric ? 'Target' : 'Target[int]'},
|
|
790
|
+
//// bad_target: ${sourceIsGeneric ? 'Target' : 'Target[str]'},
|
|
791
|
+
//// ):
|
|
792
|
+
//// /*good_source*/good_source
|
|
793
|
+
//// /*bad_source*/bad_source
|
|
794
|
+
//// /*good_target*/good_target
|
|
795
|
+
//// /*bad_target*/bad_target
|
|
796
|
+
`).state;
|
|
797
|
+
const evaluator = state.program.evaluator;
|
|
798
|
+
const typeAt = (marker) => {
|
|
799
|
+
const node = (0, testState_1.getNodeAtMarker)(state, marker);
|
|
800
|
+
assert.strictEqual(node.nodeType, 38 /* ParseNodeType.Name */);
|
|
801
|
+
const type = evaluator.getTypeOfExpression(node).type;
|
|
802
|
+
assert.ok((0, types_1.isClassInstance)(type));
|
|
803
|
+
return type;
|
|
804
|
+
};
|
|
805
|
+
const goodSource = typeAt('good_source');
|
|
806
|
+
const badSource = typeAt('bad_source');
|
|
807
|
+
const goodTarget = types_1.ClassType.cloneAsInstantiable(typeAt('good_target'));
|
|
808
|
+
const badTarget = types_1.ClassType.cloneAsInstantiable(typeAt('bad_target'));
|
|
809
|
+
const assign = (target, source) => (0, protocols_1.assignClassToProtocol)(evaluator, target, source, diagnostics ? new diagnostic_1.DiagnosticAddendum() : undefined, undefined, 0 /* AssignTypeFlags.Default */, 0);
|
|
810
|
+
if (positiveFirst) {
|
|
811
|
+
assert.strictEqual(assign(goodTarget, goodSource), true);
|
|
812
|
+
}
|
|
813
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
814
|
+
assert.strictEqual(assign(badTarget, badSource), false);
|
|
815
|
+
assert.strictEqual(assign(goodTarget, goodSource), true);
|
|
816
|
+
}
|
|
817
|
+
if (!sourceIsGeneric) {
|
|
818
|
+
const typeParam = goodTarget.shared.typeParams[0];
|
|
819
|
+
const genericTarget = types_1.ClassType.specialize(goodTarget, [typeParam]);
|
|
820
|
+
const constraints = new constraintTracker_1.ConstraintTracker();
|
|
821
|
+
assert.strictEqual((0, protocols_1.assignClassToProtocol)(evaluator, genericTarget, goodSource, undefined, constraints, 0 /* AssignTypeFlags.Default */, 0), true);
|
|
822
|
+
assert.strictEqual(evaluator.printType(evaluator.solveAndApplyConstraints(typeParam, constraints)), 'int');
|
|
823
|
+
}
|
|
824
|
+
});
|
|
718
825
|
test('ProtocolExplicit1', () => {
|
|
719
826
|
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['protocolExplicit1.py']);
|
|
720
827
|
TestUtils.validateResults(analysisResults, 5);
|
|
@@ -723,6 +830,498 @@ test('ProtocolExplicit3', () => {
|
|
|
723
830
|
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['protocolExplicit3.py']);
|
|
724
831
|
TestUtils.validateResults(analysisResults, 3);
|
|
725
832
|
});
|
|
833
|
+
test.each(['cache', 'recursiveArgument', 'recursiveReturn'].flatMap((path) => ['standard', 'positionalOnly', 'keywordOnly'].flatMap((kind) => [
|
|
834
|
+
['optional', 'required', false],
|
|
835
|
+
['required', 'optional', false],
|
|
836
|
+
['optional', 'optional', true],
|
|
837
|
+
].map(([first, second, compatible]) => ({ path, kind, first, second, compatible })))))('TypedDictCallableIdentity $path $kind $first/$second', ({ path, kind, first, second, compatible }) => {
|
|
838
|
+
const suffix = kind === 'positionalOnly' ? ', /' : '';
|
|
839
|
+
const prefix = kind === 'keywordOnly' ? '*, ' : '';
|
|
840
|
+
const recursive = path !== 'cache';
|
|
841
|
+
const code = `
|
|
842
|
+
// @filename: test.py
|
|
843
|
+
//// from typing import Callable, ReadOnly, TypedDict
|
|
844
|
+
////
|
|
845
|
+
//// def optional(${prefix}x: int = 0${suffix}) -> None:
|
|
846
|
+
//// pass
|
|
847
|
+
////
|
|
848
|
+
//// def required(${prefix}x: int${suffix}) -> None:
|
|
849
|
+
//// pass
|
|
850
|
+
////
|
|
851
|
+
${recursive
|
|
852
|
+
? `//// class A[T](TypedDict, total=False):
|
|
853
|
+
//// next: ReadOnly["A[T]"]
|
|
854
|
+
//// value: ReadOnly[T]
|
|
855
|
+
////
|
|
856
|
+
//// class B[T, U](TypedDict, total=False):
|
|
857
|
+
//// next: ReadOnly["B[U, T]"]
|
|
858
|
+
//// value: ReadOnly[T]
|
|
859
|
+
//// other: ReadOnly[U]
|
|
860
|
+
////
|
|
861
|
+
//// def source[T, U](t: T, u: U) -> B[T, U]:
|
|
862
|
+
//// child: B[U, T] = {"value": u, "other": t}
|
|
863
|
+
//// return {"value": t, "other": u, "next": child}
|
|
864
|
+
////
|
|
865
|
+
//// def consume(result: A[Callable[[], None]]) -> None:
|
|
866
|
+
//// if "next" in result and "value" in result["next"]:
|
|
867
|
+
//// result["next"]["value"]()
|
|
868
|
+
////
|
|
869
|
+
${path === 'recursiveReturn'
|
|
870
|
+
? `//// def bad() -> A[Callable[[], None]]:
|
|
871
|
+
//// /*error*/return source(${first}, ${second})
|
|
872
|
+
////
|
|
873
|
+
//// consume(bad())`
|
|
874
|
+
: `//// /*error*/consume(source(${first}, ${second}))`}`
|
|
875
|
+
: `//// class A(TypedDict):
|
|
876
|
+
//// value: ReadOnly[Callable[[], None]]
|
|
877
|
+
////
|
|
878
|
+
//// class B[T](TypedDict):
|
|
879
|
+
//// value: ReadOnly[T]
|
|
880
|
+
////
|
|
881
|
+
//// class Source[T, U](TypedDict):
|
|
882
|
+
//// first: ReadOnly[B[T]]
|
|
883
|
+
//// second: ReadOnly[B[U]]
|
|
884
|
+
////
|
|
885
|
+
//// class Dest(TypedDict):
|
|
886
|
+
//// first: ReadOnly[A]
|
|
887
|
+
//// second: ReadOnly[A]
|
|
888
|
+
////
|
|
889
|
+
//// def source[T, U](t: T, u: U) -> Source[T, U]:
|
|
890
|
+
//// return {"first": {"value": t}, "second": {"value": u}}
|
|
891
|
+
////
|
|
892
|
+
//// def bad() -> Dest:
|
|
893
|
+
//// /*error*/return source(${first}, ${second})
|
|
894
|
+
////
|
|
895
|
+
//// bad()["second"]["value"]()`}
|
|
896
|
+
`;
|
|
897
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
898
|
+
state.configOptions.defaultPythonVersion = pythonVersion_1.pythonVersion3_13;
|
|
899
|
+
const file = state.testData.files[0];
|
|
900
|
+
const results = TestUtils.getAnalysisResults(state.program, [file.fileUri], state.configOptions);
|
|
901
|
+
TestUtils.validateResults(results, compatible ? 0 : 1);
|
|
902
|
+
if (!compatible) {
|
|
903
|
+
const diagnostic = results[0].errors[0];
|
|
904
|
+
assert.strictEqual(diagnostic.getRule(), path === 'recursiveArgument' ? diagnosticRules_1.DiagnosticRule.reportArgumentType : diagnosticRules_1.DiagnosticRule.reportReturnType);
|
|
905
|
+
const marker = state.getMarkerByName('error');
|
|
906
|
+
const line = file.content.slice(0, marker.position).split('\n').length - 1;
|
|
907
|
+
assert.strictEqual(diagnostic.range.start.line, line);
|
|
908
|
+
const callable = (name) => `(${prefix}x: int${name === 'optional' ? ' = 0' : ''}${suffix}) -> None`;
|
|
909
|
+
const source = `${recursive ? 'B' : 'Source'}[${callable(first)}, ${callable(second)}]`;
|
|
910
|
+
const destination = recursive ? 'A[() -> None]' : 'Dest';
|
|
911
|
+
const header = path === 'recursiveArgument'
|
|
912
|
+
? `Argument of type "${source}" cannot be assigned to parameter "result" of type "${destination}" in function "consume"`
|
|
913
|
+
: `Type "${source}" is not assignable to return type "${destination}"`;
|
|
914
|
+
const indent = '\u00a0\u00a0';
|
|
915
|
+
const entry = path === 'cache'
|
|
916
|
+
? [`${indent}"${first === 'required' ? 'first' : 'second'}" is an incompatible type`]
|
|
917
|
+
: first === 'optional'
|
|
918
|
+
? [`${indent}"next" is an incompatible type`]
|
|
919
|
+
: [];
|
|
920
|
+
const depth = entry.length + 1;
|
|
921
|
+
assert.strictEqual(diagnostic.message, [
|
|
922
|
+
header,
|
|
923
|
+
...entry,
|
|
924
|
+
`${indent.repeat(depth)}"value" is an incompatible type`,
|
|
925
|
+
`${indent.repeat(depth + 1)}Type "${callable('required')}" is not assignable to type "() -> None"`,
|
|
926
|
+
...(kind === 'positionalOnly'
|
|
927
|
+
? [
|
|
928
|
+
`${indent.repeat(depth + 2)}Position-only parameter mismatch; expected 0 but received 1`,
|
|
929
|
+
`${indent.repeat(depth + 2)}Function accepts too many positional parameters; expected 0 but received 1`,
|
|
930
|
+
]
|
|
931
|
+
: [`${indent.repeat(depth + 2)}Extra parameter "x"`]),
|
|
932
|
+
].join('\n'));
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
test.each([
|
|
936
|
+
['optional', 'required', false],
|
|
937
|
+
['required', 'optional', false],
|
|
938
|
+
['optional', 'optional', true],
|
|
939
|
+
])('TypedDictCallableConstructor %s/%s', (first, second, compatible) => {
|
|
940
|
+
const code = `
|
|
941
|
+
// @filename: test.py
|
|
942
|
+
//// from typing import Callable, ReadOnly, TypedDict, assert_type
|
|
943
|
+
////
|
|
944
|
+
//// class A[T](TypedDict):
|
|
945
|
+
//// value: ReadOnly[T]
|
|
946
|
+
////
|
|
947
|
+
//// class B[T](TypedDict):
|
|
948
|
+
//// value: ReadOnly[T]
|
|
949
|
+
////
|
|
950
|
+
//// class Dest(TypedDict):
|
|
951
|
+
//// first: ReadOnly[A[Callable[[], int]]]
|
|
952
|
+
//// second: ReadOnly[A[Callable[[], int]]]
|
|
953
|
+
////
|
|
954
|
+
//// class Source[T, U](TypedDict):
|
|
955
|
+
//// first: ReadOnly[B[T]]
|
|
956
|
+
//// second: ReadOnly[B[U]]
|
|
957
|
+
////
|
|
958
|
+
//// def optional(x: int = 0) -> int:
|
|
959
|
+
//// return x
|
|
960
|
+
////
|
|
961
|
+
//// def required(x: int) -> int:
|
|
962
|
+
//// return x
|
|
963
|
+
////
|
|
964
|
+
//// def expose() -> Dest:
|
|
965
|
+
//// source = Source(first=B(value=${first}), second=B(value=${second}))
|
|
966
|
+
//// /*error*/return source
|
|
967
|
+
////
|
|
968
|
+
//// def consumer() -> int:
|
|
969
|
+
//// assert_type(expose()["second"]["value"], Callable[[], int])
|
|
970
|
+
//// return expose()["second"]["value"]()
|
|
971
|
+
`;
|
|
972
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
973
|
+
state.configOptions.defaultPythonVersion = pythonVersion_1.pythonVersion3_13;
|
|
974
|
+
const file = state.testData.files[0];
|
|
975
|
+
const results = TestUtils.getAnalysisResults(state.program, [file.fileUri], state.configOptions);
|
|
976
|
+
TestUtils.validateResults(results, compatible ? 0 : 1);
|
|
977
|
+
if (!compatible) {
|
|
978
|
+
const diagnostic = results[0].errors[0];
|
|
979
|
+
assert.strictEqual(diagnostic.getRule(), diagnosticRules_1.DiagnosticRule.reportReturnType);
|
|
980
|
+
const marker = state.getMarkerByName('error');
|
|
981
|
+
const line = file.content.slice(0, marker.position).split('\n').length - 1;
|
|
982
|
+
assert.strictEqual(diagnostic.range.start.line, line);
|
|
983
|
+
const callable = (name) => `(x: int${name === 'optional' ? ' = 0' : ''}) -> int`;
|
|
984
|
+
const indent = '\u00a0\u00a0';
|
|
985
|
+
assert.strictEqual(diagnostic.message, [
|
|
986
|
+
`Type "Source[${callable(first)}, ${callable(second)}]" is not assignable to return type "Dest"`,
|
|
987
|
+
`${indent}"${first === 'required' ? 'first' : 'second'}" is an incompatible type`,
|
|
988
|
+
`${indent.repeat(2)}"value" is an incompatible type`,
|
|
989
|
+
`${indent.repeat(3)}Type "(x: int) -> int" is not assignable to type "() -> int"`,
|
|
990
|
+
`${indent.repeat(4)}Extra parameter "x"`,
|
|
991
|
+
].join('\n'));
|
|
992
|
+
}
|
|
993
|
+
});
|
|
994
|
+
test('TypedDictNestedSiblingDiagnostics', () => {
|
|
995
|
+
const classes = ['Int', 'Str']
|
|
996
|
+
.map((prefix) => `
|
|
997
|
+
//// class ${prefix}Leaf(TypedDict):
|
|
998
|
+
//// value: ReadOnly[${prefix === 'Int' ? 'int' : 'str'}]
|
|
999
|
+
////
|
|
1000
|
+
//// class ${prefix}Pair(TypedDict):
|
|
1001
|
+
//// first: ReadOnly[${prefix}Leaf]
|
|
1002
|
+
//// second: ReadOnly[${prefix}Leaf]
|
|
1003
|
+
////
|
|
1004
|
+
//// class ${prefix}Root(TypedDict):
|
|
1005
|
+
//// inside: ReadOnly[${prefix}Pair]
|
|
1006
|
+
////
|
|
1007
|
+
//// class ${prefix}Outer(TypedDict):
|
|
1008
|
+
//// outer: ReadOnly[${prefix}Root]
|
|
1009
|
+
////`)
|
|
1010
|
+
.join('\n');
|
|
1011
|
+
const code = `
|
|
1012
|
+
// @filename: test.py
|
|
1013
|
+
//// from typing import TypedDict
|
|
1014
|
+
//// from typing_extensions import ReadOnly
|
|
1015
|
+
////
|
|
1016
|
+
${classes}
|
|
1017
|
+
//// def check(a: IntOuter, b: StrOuter):
|
|
1018
|
+
//// /*a*/a
|
|
1019
|
+
//// /*b*/b
|
|
1020
|
+
`;
|
|
1021
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
1022
|
+
const evaluator = state.program.evaluator;
|
|
1023
|
+
const [aType, bType] = ['a', 'b'].map((marker) => {
|
|
1024
|
+
const node = (0, testState_1.getNodeAtMarker)(state, marker);
|
|
1025
|
+
assert.strictEqual(node.nodeType, 38 /* ParseNodeType.Name */);
|
|
1026
|
+
return evaluator.getTypeOfExpression(node).type;
|
|
1027
|
+
});
|
|
1028
|
+
const diagnostics = new diagnostic_1.DiagnosticAddendum();
|
|
1029
|
+
assert.strictEqual(evaluator.assignType(aType, bType, diagnostics), false);
|
|
1030
|
+
const rendered = diagnostics.getString(undefined, 1000);
|
|
1031
|
+
const indent = '\u00a0\u00a0';
|
|
1032
|
+
assert.strictEqual(rendered, [
|
|
1033
|
+
'',
|
|
1034
|
+
`${indent}"outer" is an incompatible type`,
|
|
1035
|
+
`${indent.repeat(2)}"inside" is an incompatible type`,
|
|
1036
|
+
`${indent.repeat(3)}"first" is an incompatible type`,
|
|
1037
|
+
`${indent.repeat(4)}"value" is an incompatible type`,
|
|
1038
|
+
`${indent.repeat(5)}"str" is not assignable to "int"`,
|
|
1039
|
+
`${indent.repeat(3)}"second" is an incompatible type`,
|
|
1040
|
+
`${indent.repeat(4)}"value" is an incompatible type`,
|
|
1041
|
+
`${indent.repeat(5)}"str" is not assignable to "int"`,
|
|
1042
|
+
].join('\n'));
|
|
1043
|
+
});
|
|
1044
|
+
test.each([64, 65].flatMap((width) => [false, true].map((hotFirst) => ({ width, hotFirst }))))('TypedDictDestinationWorkingSet width=$width hotFirst=$hotFirst', ({ width, hotFirst }) => {
|
|
1045
|
+
const layers = 4;
|
|
1046
|
+
const classes = Array.from({ length: layers }, (_, layer) => {
|
|
1047
|
+
const indices = Array.from({ length: width }, (_, index) => index);
|
|
1048
|
+
const fields = (prefix) => {
|
|
1049
|
+
if (layer === 0) {
|
|
1050
|
+
return '//// value: ReadOnly[int]';
|
|
1051
|
+
}
|
|
1052
|
+
const hot = Array.from({ length: 8 }, (_, index) => (hotFirst ? index : width - 8 + index));
|
|
1053
|
+
const repeatedHot = Array.from({ length: 8 }, () => hot).flat();
|
|
1054
|
+
const targets = hotFirst ? [...repeatedHot, ...indices] : [...indices, ...repeatedHot];
|
|
1055
|
+
return targets
|
|
1056
|
+
.map((target, field) => `//// field${field}: ReadOnly["${prefix === 'Source' ? `Source${layer - 1}` : `Dest${layer - 1}_${target}`}"]`)
|
|
1057
|
+
.join('\n');
|
|
1058
|
+
};
|
|
1059
|
+
return (`//// class Source${layer}(TypedDict):\n${fields('Source')}\n////\n` +
|
|
1060
|
+
indices
|
|
1061
|
+
.map((index) => `//// class Dest${layer}_${index}(TypedDict):\n${fields('Dest')}\n////`)
|
|
1062
|
+
.join('\n'));
|
|
1063
|
+
}).join('\n');
|
|
1064
|
+
const code = `
|
|
1065
|
+
// @filename: test.py
|
|
1066
|
+
//// from typing import TypedDict
|
|
1067
|
+
//// from typing_extensions import ReadOnly
|
|
1068
|
+
////
|
|
1069
|
+
${classes}
|
|
1070
|
+
//// def check(dest: Dest${layers - 1}_0, source: Source${layers - 1}):
|
|
1071
|
+
//// /*dest*/dest
|
|
1072
|
+
//// /*source*/source
|
|
1073
|
+
`;
|
|
1074
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
1075
|
+
const evaluator = state.program.evaluator;
|
|
1076
|
+
const [destType, sourceType] = ['dest', 'source'].map((marker) => {
|
|
1077
|
+
const node = (0, testState_1.getNodeAtMarker)(state, marker);
|
|
1078
|
+
assert.strictEqual(node.nodeType, 38 /* ParseNodeType.Name */);
|
|
1079
|
+
return evaluator.getTypeOfExpression(node).type;
|
|
1080
|
+
});
|
|
1081
|
+
const assignType = evaluator.assignType;
|
|
1082
|
+
let comparisons = 0;
|
|
1083
|
+
const spy = jest.spyOn(evaluator, 'assignType').mockImplementation((...args) => {
|
|
1084
|
+
assert.ok(++comparisons < 20000, 'Destination classes evicted each other from the comparison cache');
|
|
1085
|
+
return assignType(...args);
|
|
1086
|
+
});
|
|
1087
|
+
try {
|
|
1088
|
+
assert.strictEqual(evaluator.assignType(destType, sourceType), true);
|
|
1089
|
+
}
|
|
1090
|
+
finally {
|
|
1091
|
+
spy.mockRestore();
|
|
1092
|
+
}
|
|
1093
|
+
});
|
|
1094
|
+
test('TypedDictRecursive1', () => {
|
|
1095
|
+
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typedDictRecursive1.py']);
|
|
1096
|
+
TestUtils.validateResults(analysisResults, 0);
|
|
1097
|
+
});
|
|
1098
|
+
test('TypedDictRecursive2', () => {
|
|
1099
|
+
const configOptions = new configOptions_1.ConfigOptions(uri_1.Uri.empty());
|
|
1100
|
+
configOptions.defaultPythonVersion = pythonVersion_1.pythonVersion3_13;
|
|
1101
|
+
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typedDictRecursive2.py'], configOptions);
|
|
1102
|
+
TestUtils.validateResults(analysisResults, 5);
|
|
1103
|
+
const indent = '\u00a0\u00a0';
|
|
1104
|
+
assert.deepStrictEqual(analysisResults[0].errors.map((diagnostic) => diagnostic.message), [
|
|
1105
|
+
[
|
|
1106
|
+
'Type "ReadOnlyStr" is not assignable to declared type "ReadOnlyInt"',
|
|
1107
|
+
`${indent}"value" is an incompatible type`,
|
|
1108
|
+
`${indent.repeat(2)}"str" is not assignable to "int"`,
|
|
1109
|
+
].join('\n'),
|
|
1110
|
+
[
|
|
1111
|
+
'Type "StrParent" is not assignable to declared type "IntParent"',
|
|
1112
|
+
`${indent}"value" is an incompatible type`,
|
|
1113
|
+
`${indent.repeat(2)}"str" is not assignable to "int"`,
|
|
1114
|
+
].join('\n'),
|
|
1115
|
+
[
|
|
1116
|
+
'Type "StrChild" is not assignable to declared type "IntChild"',
|
|
1117
|
+
`${indent}"parent" is an incompatible type`,
|
|
1118
|
+
`${indent.repeat(2)}"value" is an incompatible type`,
|
|
1119
|
+
`${indent.repeat(3)}"str" is not assignable to "int"`,
|
|
1120
|
+
].join('\n'),
|
|
1121
|
+
[
|
|
1122
|
+
'Type "StrWrapper" is not assignable to declared type "IntWrapper"',
|
|
1123
|
+
`${indent}"parent" is an incompatible type`,
|
|
1124
|
+
`${indent.repeat(2)}"value" is an incompatible type`,
|
|
1125
|
+
`${indent.repeat(3)}"str" is not assignable to "int"`,
|
|
1126
|
+
`${indent}"child" is an incompatible type`,
|
|
1127
|
+
`${indent.repeat(2)}"parent" is an incompatible type`,
|
|
1128
|
+
`${indent.repeat(3)}"value" is an incompatible type`,
|
|
1129
|
+
`${indent.repeat(4)}"str" is not assignable to "int"`,
|
|
1130
|
+
`${indent}"again" is an incompatible type`,
|
|
1131
|
+
].join('\n'),
|
|
1132
|
+
[
|
|
1133
|
+
'Type "GenericB[str]" is not assignable to declared type "GenericA[int]"',
|
|
1134
|
+
`${indent}"value" is an incompatible type`,
|
|
1135
|
+
`${indent.repeat(2)}"str" is not assignable to "int"`,
|
|
1136
|
+
].join('\n'),
|
|
1137
|
+
]);
|
|
1138
|
+
});
|
|
1139
|
+
test('TypedDictRecursive3', () => {
|
|
1140
|
+
const configOptions = new configOptions_1.ConfigOptions(uri_1.Uri.empty());
|
|
1141
|
+
configOptions.defaultPythonVersion = pythonVersion_1.pythonVersion3_13;
|
|
1142
|
+
configOptions.diagnosticRuleSet.enableExperimentalFeatures = true;
|
|
1143
|
+
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typedDictRecursive3.py'], configOptions);
|
|
1144
|
+
TestUtils.validateResults(analysisResults, 0);
|
|
1145
|
+
});
|
|
1146
|
+
test('TypedDictRecursiveRecursionBudget', () => {
|
|
1147
|
+
const chains = ['A', 'B']
|
|
1148
|
+
.map((prefix) => Array.from({ length: 19 }, (_, index) => `
|
|
1149
|
+
//// class ${prefix}Chain${index}(TypedDict):
|
|
1150
|
+
//// next: ReadOnly["${prefix}${index === 18 ? 'Leaf' : `Chain${index + 1}`}"]
|
|
1151
|
+
////`).join('\n'))
|
|
1152
|
+
.join('\n');
|
|
1153
|
+
const code = `
|
|
1154
|
+
// @filename: test.py
|
|
1155
|
+
//// from typing import TypedDict
|
|
1156
|
+
//// from typing_extensions import ReadOnly
|
|
1157
|
+
////
|
|
1158
|
+
//// class ALeaf(TypedDict):
|
|
1159
|
+
//// value: ReadOnly[int]
|
|
1160
|
+
////
|
|
1161
|
+
//// class BLeaf(TypedDict):
|
|
1162
|
+
//// value: ReadOnly[str]
|
|
1163
|
+
////
|
|
1164
|
+
${chains}
|
|
1165
|
+
//// class ARoot(TypedDict):
|
|
1166
|
+
//// deep: ReadOnly[AChain0]
|
|
1167
|
+
//// shallow: ReadOnly[ALeaf]
|
|
1168
|
+
////
|
|
1169
|
+
//// class BRoot(TypedDict):
|
|
1170
|
+
//// deep: ReadOnly[BChain0]
|
|
1171
|
+
//// shallow: ReadOnly[BLeaf]
|
|
1172
|
+
////
|
|
1173
|
+
//// def check(a: ARoot, b: BRoot):
|
|
1174
|
+
//// /*a*/a
|
|
1175
|
+
//// /*b*/b
|
|
1176
|
+
`;
|
|
1177
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
1178
|
+
const evaluator = state.program.evaluator;
|
|
1179
|
+
const [aType, bType] = ['a', 'b'].map((marker) => {
|
|
1180
|
+
const node = (0, testState_1.getNodeAtMarker)(state, marker);
|
|
1181
|
+
assert.strictEqual(node.nodeType, 38 /* ParseNodeType.Name */);
|
|
1182
|
+
return evaluator.getTypeOfExpression(node).type;
|
|
1183
|
+
});
|
|
1184
|
+
assert.strictEqual(evaluator.assignType(aType, bType), false);
|
|
1185
|
+
const diagnostics = new diagnostic_1.DiagnosticAddendum();
|
|
1186
|
+
assert.strictEqual(evaluator.assignType(aType, bType, diagnostics), false);
|
|
1187
|
+
const indent = '\u00a0\u00a0';
|
|
1188
|
+
assert.strictEqual(diagnostics.getString(), [
|
|
1189
|
+
'',
|
|
1190
|
+
`${indent}"shallow" is an incompatible type`,
|
|
1191
|
+
`${indent.repeat(2)}"value" is an incompatible type`,
|
|
1192
|
+
`${indent.repeat(3)}"str" is not assignable to "int"`,
|
|
1193
|
+
].join('\n'));
|
|
1194
|
+
});
|
|
1195
|
+
test.each([true, false])('TypedDictRecursiveSharedGraph compatible=%s', (compatible) => {
|
|
1196
|
+
const width = compatible ? 64 : 16;
|
|
1197
|
+
const layers = compatible ? 4 : 3;
|
|
1198
|
+
const classes = ['A', 'B']
|
|
1199
|
+
.map((prefix) => Array.from({ length: layers }, (_, layer) => Array.from({ length: width }, (_, index) => {
|
|
1200
|
+
const fields = Array.from({ length: layer === 0 ? 1 : width }, (_, field) => `//// field${field}: ReadOnly["${layer === 0 ? `${prefix}Leaf` : `${prefix}${layer - 1}_${field}`}"]`).join('\n');
|
|
1201
|
+
return `//// class ${prefix}${layer}_${index}(TypedDict):\n${fields}\n////`;
|
|
1202
|
+
}).join('\n')).join('\n'))
|
|
1203
|
+
.join('\n');
|
|
1204
|
+
const code = `
|
|
1205
|
+
// @filename: test.py
|
|
1206
|
+
//// from typing import TypedDict
|
|
1207
|
+
//// from typing_extensions import ReadOnly
|
|
1208
|
+
////
|
|
1209
|
+
//// class ALeaf(TypedDict):
|
|
1210
|
+
//// value: ReadOnly[int]
|
|
1211
|
+
////
|
|
1212
|
+
//// class BLeaf(TypedDict):
|
|
1213
|
+
//// value: ReadOnly[${compatible ? 'int' : 'str'}]
|
|
1214
|
+
////
|
|
1215
|
+
${classes}
|
|
1216
|
+
//// def check(a: A${layers - 1}_0, b: B${layers - 1}_0):
|
|
1217
|
+
//// /*a*/a
|
|
1218
|
+
//// /*b*/b
|
|
1219
|
+
`;
|
|
1220
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
1221
|
+
const evaluator = state.program.evaluator;
|
|
1222
|
+
const [aType, bType] = ['a', 'b'].map((marker) => {
|
|
1223
|
+
const node = (0, testState_1.getNodeAtMarker)(state, marker);
|
|
1224
|
+
assert.strictEqual(node.nodeType, 38 /* ParseNodeType.Name */);
|
|
1225
|
+
return evaluator.getTypeOfExpression(node).type;
|
|
1226
|
+
});
|
|
1227
|
+
const assignType = evaluator.assignType;
|
|
1228
|
+
let comparisons = 0;
|
|
1229
|
+
const spy = jest.spyOn(evaluator, 'assignType').mockImplementation((...args) => {
|
|
1230
|
+
assert.ok(++comparisons < 20000, 'Shared TypedDict subgraphs were repeatedly recomputed');
|
|
1231
|
+
return assignType(...args);
|
|
1232
|
+
});
|
|
1233
|
+
try {
|
|
1234
|
+
assert.strictEqual(evaluator.assignType(aType, bType), compatible);
|
|
1235
|
+
if (!compatible) {
|
|
1236
|
+
const diagnostics = new diagnostic_1.DiagnosticAddendum();
|
|
1237
|
+
assert.strictEqual(evaluator.assignType(aType, bType, diagnostics), false);
|
|
1238
|
+
const indent = '\u00a0\u00a0';
|
|
1239
|
+
// Assert the complete 1000-line rendering, including its line-budget boundary:
|
|
1240
|
+
// 15 full outer fields (65 lines each) and a final field with 6 children (25 lines).
|
|
1241
|
+
const expectedLines = Array.from({ length: 16 }, (_, outer) => [
|
|
1242
|
+
`${indent}"field${outer}" is an incompatible type`,
|
|
1243
|
+
...Array.from({ length: outer === 15 ? 6 : 16 }, (_, inner) => [
|
|
1244
|
+
`${indent.repeat(2)}"field${inner}" is an incompatible type`,
|
|
1245
|
+
`${indent.repeat(3)}"field0" is an incompatible type`,
|
|
1246
|
+
`${indent.repeat(4)}"value" is an incompatible type`,
|
|
1247
|
+
`${indent.repeat(5)}"str" is not assignable to "int"`,
|
|
1248
|
+
]).flat(),
|
|
1249
|
+
]).flat();
|
|
1250
|
+
assert.strictEqual(diagnostics.getString(undefined, 1000), ['', ...expectedLines].join('\n'));
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
finally {
|
|
1254
|
+
spy.mockRestore();
|
|
1255
|
+
}
|
|
1256
|
+
});
|
|
1257
|
+
test.each([
|
|
1258
|
+
[false, true],
|
|
1259
|
+
[true, true],
|
|
1260
|
+
[false, false],
|
|
1261
|
+
[true, false],
|
|
1262
|
+
])('TypedDictRecursiveWide constraints=%s compatible=%s', (withConstraints, expectedCompatibility) => {
|
|
1263
|
+
const fields = (prefix) => Array.from({ length: 56 }, (_, index) => `//// rel${index}: bool | "${prefix}Args"`).join('\n');
|
|
1264
|
+
const code = `
|
|
1265
|
+
// @filename: test.py
|
|
1266
|
+
//// from typing import TypedDict
|
|
1267
|
+
////
|
|
1268
|
+
//// class AInclude(TypedDict, total=False):
|
|
1269
|
+
${fields('A')}
|
|
1270
|
+
//// value: int
|
|
1271
|
+
////
|
|
1272
|
+
//// class AArgs(TypedDict, total=False):
|
|
1273
|
+
//// include: "AInclude"
|
|
1274
|
+
////
|
|
1275
|
+
//// class BInclude(TypedDict, total=False):
|
|
1276
|
+
${fields('B')}
|
|
1277
|
+
//// value: ${expectedCompatibility ? 'int' : 'str'}
|
|
1278
|
+
////
|
|
1279
|
+
//// class BArgs(TypedDict, total=False):
|
|
1280
|
+
//// include: "BInclude"
|
|
1281
|
+
////
|
|
1282
|
+
//// def check(a: AInclude, b: BInclude):
|
|
1283
|
+
//// /*a*/a
|
|
1284
|
+
//// /*b*/b
|
|
1285
|
+
`;
|
|
1286
|
+
const state = (0, testState_1.parseAndGetTestState)(code).state;
|
|
1287
|
+
const evaluator = state.program.evaluator;
|
|
1288
|
+
const [aType, bType] = ['a', 'b'].map((marker) => {
|
|
1289
|
+
const node = (0, testState_1.getNodeAtMarker)(state, marker);
|
|
1290
|
+
assert.strictEqual(node.nodeType, 38 /* ParseNodeType.Name */);
|
|
1291
|
+
return evaluator.getTypeOfExpression(node).type;
|
|
1292
|
+
});
|
|
1293
|
+
const assignType = evaluator.assignType;
|
|
1294
|
+
let comparisons = 0;
|
|
1295
|
+
const spy = jest.spyOn(evaluator, 'assignType').mockImplementation((...args) => {
|
|
1296
|
+
// Bound work rather than wall-clock time, and fail promptly if recursion returns.
|
|
1297
|
+
assert.ok(++comparisons < 2000, 'Recursive TypedDict comparison exceeded its work budget');
|
|
1298
|
+
return assignType(...args);
|
|
1299
|
+
});
|
|
1300
|
+
try {
|
|
1301
|
+
const constraints = withConstraints ? new constraintTracker_1.ConstraintTracker() : undefined;
|
|
1302
|
+
assert.strictEqual(evaluator.assignType(bType, aType, undefined, constraints), expectedCompatibility);
|
|
1303
|
+
const diagnostics = new diagnostic_1.DiagnosticAddendum();
|
|
1304
|
+
assert.strictEqual(evaluator.assignType(aType, bType, diagnostics, constraints), expectedCompatibility);
|
|
1305
|
+
if (!expectedCompatibility) {
|
|
1306
|
+
const indent = '\u00a0\u00a0';
|
|
1307
|
+
const expectedLines = Array.from({ length: 56 }, (_, index) => [
|
|
1308
|
+
`${indent}"rel${index}" is an incompatible type`,
|
|
1309
|
+
`${indent.repeat(2)}Type "bool | BArgs" is not assignable to type "bool | AArgs"`,
|
|
1310
|
+
`${indent.repeat(3)}Type "BArgs" is not assignable to type "bool | AArgs"`,
|
|
1311
|
+
`${indent.repeat(4)}"BArgs" is not assignable to "bool"`,
|
|
1312
|
+
]).flat();
|
|
1313
|
+
assert.strictEqual(diagnostics.getString(undefined, 1000), [
|
|
1314
|
+
'',
|
|
1315
|
+
...expectedLines,
|
|
1316
|
+
`${indent}"value" is an incompatible type`,
|
|
1317
|
+
`${indent.repeat(2)}"str" is not assignable to "int"`,
|
|
1318
|
+
].join('\n'));
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
finally {
|
|
1322
|
+
spy.mockRestore();
|
|
1323
|
+
}
|
|
1324
|
+
});
|
|
726
1325
|
test('TypedDict1', () => {
|
|
727
1326
|
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typedDict1.py']);
|
|
728
1327
|
TestUtils.validateResults(analysisResults, 11);
|