diff --git a/lerna.json b/lerna.json index 54d3c36fe..986cdcf78 100644 --- a/lerna.json +++ b/lerna.json @@ -2,7 +2,7 @@ "packages": [ "packages/*" ], - "version": "1.1.325", + "version": "1.1.328", "command": { "version": { "push": false, diff --git a/packages/pyright-internal/package-lock.json b/packages/pyright-internal/package-lock.json index 09eb8e354..0b330fa16 100644 --- a/packages/pyright-internal/package-lock.json +++ b/packages/pyright-internal/package-lock.json @@ -1,12 +1,12 @@ { "name": "pyright-internal", - "version": "1.1.325", + "version": "1.1.328", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "pyright-internal", - "version": "1.1.325", + "version": "1.1.328", "license": "MIT", "dependencies": { "@iarna/toml": "2.2.5", diff --git a/packages/pyright-internal/package.json b/packages/pyright-internal/package.json index 28438a354..1de6cbf9d 100644 --- a/packages/pyright-internal/package.json +++ b/packages/pyright-internal/package.json @@ -2,7 +2,7 @@ "name": "pyright-internal", "displayName": "pyright", "description": "Type checker for the Python language", - "version": "1.1.325", + "version": "1.1.328", "license": "MIT", "private": true, "files": [ diff --git a/packages/pyright-internal/src/analyzer/binder.ts b/packages/pyright-internal/src/analyzer/binder.ts index 6f31a2d71..385f86020 100644 --- a/packages/pyright-internal/src/analyzer/binder.ts +++ b/packages/pyright-internal/src/analyzer/binder.ts @@ -1934,7 +1934,7 @@ export class Binder extends ParseTreeWalker { loadSymbolsFromPath: true, range: getEmptyRange(), usesLocalName: false, - moduleName: this._fileInfo.moduleName, + moduleName: this._formatModuleName(node.module.nameParts), isInExceptSuite: this._isInExceptSuite, }; @@ -1961,7 +1961,7 @@ export class Binder extends ParseTreeWalker { symbolName: importedName, submoduleFallback, range: convertTextRangeToRange(nameNode, this._fileInfo.lines), - moduleName: this._fileInfo.moduleName, + moduleName: this._formatModuleName(node.module.nameParts), isInExceptSuite: this._isInExceptSuite, isNativeLib: importInfo?.isNativeLib, }; @@ -2336,6 +2336,11 @@ export class Binder extends ParseTreeWalker { return true; } + private _formatModuleName(nameParts: NameNode[]): string { + // Ignore the leading dots for purposes of module name formatting. + return nameParts.map((name) => name.value).join('.'); + } + private _removeActiveTypeParameters(node: TypeParameterListNode) { node.parameters.forEach((typeParamNode) => { const entry = this._activeTypeParams.get(typeParamNode.name.value); @@ -2539,7 +2544,7 @@ export class Binder extends ParseTreeWalker { loadSymbolsFromPath: false, range: getEmptyRange(), usesLocalName: !!importAlias, - moduleName: firstNamePartValue, + moduleName: importAlias ? this._formatModuleName(node.module.nameParts) : firstNamePartValue, firstNamePart: firstNamePartValue, isInExceptSuite: this._isInExceptSuite, }; @@ -2555,7 +2560,7 @@ export class Binder extends ParseTreeWalker { range: getEmptyRange(), usesLocalName: !!importAlias, moduleName: importInfo?.importName ?? '', - firstNamePart: firstNamePartValue, + firstNamePart: importAlias ? this._formatModuleName(node.module.nameParts) : firstNamePartValue, isUnresolved: true, isInExceptSuite: this._isInExceptSuite, }; diff --git a/packages/pyright-internal/src/analyzer/checker.ts b/packages/pyright-internal/src/analyzer/checker.ts index 5b1fe6971..b5afb2fa7 100644 --- a/packages/pyright-internal/src/analyzer/checker.ts +++ b/packages/pyright-internal/src/analyzer/checker.ts @@ -150,6 +150,7 @@ import { } from './typeUtils'; import { TypeVarContext } from './typeVarContext'; import { + AnyType, ClassType, ClassTypeFlags, FunctionType, @@ -622,6 +623,8 @@ export class Checker extends ParseTreeWalker { this._validateTypeGuardFunction(node, functionTypeResult.functionType, containingClassNode !== undefined); this._validateFunctionTypeVarUsage(node, functionTypeResult); + + this._validateGeneratorReturnType(node, functionTypeResult.functionType); } // If we're at the module level within a stub file, report a diagnostic @@ -1179,7 +1182,12 @@ export class Checker extends ParseTreeWalker { const baseType = this._evaluator.getType(node.baseExpression); if (baseType) { doForEachSubtype(baseType, (subtype) => { - if (isClassInstance(subtype) && subtype.tupleTypeArguments && !isUnboundedTupleClass(subtype)) { + if ( + isClassInstance(subtype) && + subtype.tupleTypeArguments && + !isUnboundedTupleClass(subtype) && + !this._evaluator.isTypeSubsumedByOtherType(subtype, baseType, /* allowAnyToSubsume */ false) + ) { const tupleLength = subtype.tupleTypeArguments.length; if ( @@ -1719,6 +1727,7 @@ export class Checker extends ParseTreeWalker { const exprTypeResult = this._evaluator.getTypeOfExpression(expression); let isExprFunction = true; + let isCoroutine = false; doForEachSubtype(exprTypeResult.type, (subtype) => { subtype = this._evaluator.makeTopLevelTypeVarsConcrete(subtype); @@ -1726,6 +1735,10 @@ export class Checker extends ParseTreeWalker { if (!isFunction(subtype) && !isOverloadedFunction(subtype)) { isExprFunction = false; } + + if (isClassInstance(subtype) && ClassType.isBuiltIn(subtype, 'Coroutine')) { + isCoroutine = true; + } }); if (isExprFunction) { @@ -1736,6 +1749,15 @@ export class Checker extends ParseTreeWalker { expression ); } + + if (isCoroutine) { + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportUnnecessaryComparison, + DiagnosticRule.reportUnnecessaryComparison, + Localizer.Diagnostic.coroutineInConditionalExpression(), + expression + ); + } } private _reportUnusedExpression(node: ParseNode) { @@ -2163,6 +2185,68 @@ export class Checker extends ParseTreeWalker { return true; } + // If the function is a generator, validates that its annotated return type + // is appropriate for a generator. + private _validateGeneratorReturnType(node: FunctionNode, functionType: FunctionType) { + if (!FunctionType.isGenerator(functionType)) { + return; + } + + const declaredReturnType = functionType.details.declaredReturnType; + if (!declaredReturnType) { + return; + } + + if (isNever(declaredReturnType)) { + return; + } + + const functionDecl = functionType.details.declaration; + if (!functionDecl || !functionDecl.yieldStatements || functionDecl.yieldStatements.length === 0) { + return; + } + + let generatorType: Type | undefined; + if ( + !node.isAsync && + isClassInstance(declaredReturnType) && + ClassType.isBuiltIn(declaredReturnType, 'AwaitableGenerator') + ) { + // Handle the old-style (pre-await) generator case + // if the return type explicitly uses AwaitableGenerator. + generatorType = this._evaluator.getTypingType(node, 'AwaitableGenerator'); + } else { + generatorType = this._evaluator.getTypingType(node, node.isAsync ? 'AsyncGenerator' : 'Generator'); + } + + if (!generatorType || !isInstantiableClass(generatorType)) { + return; + } + + const specializedGenerator = ClassType.cloneAsInstance( + ClassType.cloneForSpecialization( + generatorType, + [AnyType.create(), AnyType.create(), AnyType.create()], + /* isTypeArgumentExplicit */ true + ) + ); + + const diagAddendum = new DiagnosticAddendum(); + if (!this._evaluator.assignType(declaredReturnType, specializedGenerator, diagAddendum)) { + const errorMessage = node.isAsync + ? Localizer.Diagnostic.generatorAsyncReturnType() + : Localizer.Diagnostic.generatorSyncReturnType(); + + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + errorMessage.format({ yieldType: this._evaluator.printType(AnyType.create()) }) + + diagAddendum.getString(), + node.returnTypeAnnotation ?? node.name + ); + } + } + // Determines whether the specified type is one that should trigger // an "unused" value diagnostic. private _isTypeValidForUnusedValueTest(type: Type) { @@ -2818,22 +2902,6 @@ export class Checker extends ParseTreeWalker { ); } - overloadedFunctions.forEach((overload) => { - if ( - overload.details.declaration && - !ParseTreeUtils.isFunctionSuiteEmpty(overload.details.declaration.node) - ) { - const diag = new DiagnosticAddendum(); - diag.addMessage(Localizer.DiagnosticAddendum.overloadWithImplementation()); - this._evaluator.addDiagnostic( - this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, - DiagnosticRule.reportGeneralTypeIssues, - Localizer.Diagnostic.overloadWithImplementation().format({ name }) + diag.getString(), - overload.details.declaration.node.name - ); - } - }); - // If the file is not a stub and this is the first overload, // verify that there is an implementation. if (!this._fileInfo.isStubFile && overloadedFunctions.length > 0) { @@ -2951,21 +3019,28 @@ export class Checker extends ParseTreeWalker { // therefore has an implied assignment. let isImplicitlyAssigned = false; + // Is this a class variable within a protocol class? If so, it can + // be marked final without providing a value. + let isProtocolClass = false; + if (symbol.isClassMember() && !symbol.isClassVar()) { const containingClass = ParseTreeUtils.getEnclosingClass(firstDecl.node, /* stopAtFunction */ true); + if (containingClass) { const classType = this._evaluator.getTypeOfClass(containingClass); - if ( - classType && - isClass(classType.decoratedType) && - ClassType.isDataClass(classType.decoratedType) - ) { - isImplicitlyAssigned = true; + if (classType && isClass(classType.decoratedType)) { + if (ClassType.isDataClass(classType.decoratedType)) { + isImplicitlyAssigned = true; + } + + if (ClassType.isProtocolClass(classType.decoratedType)) { + isProtocolClass = true; + } } } } - if (!isImplicitlyAssigned) { + if (!isImplicitlyAssigned && !isProtocolClass) { this._evaluator.addError(Localizer.Diagnostic.finalUnassigned().format({ name }), firstDecl.node); } } @@ -3598,7 +3673,7 @@ export class Checker extends ParseTreeWalker { // unknown type into the filtered type list to avoid any // false positives. const isClassRelationshipIndeterminate = - filterIsSubclass && filterIsSubclass && !ClassType.isSameGenericClass(varType, filterType); + filterIsSuperclass && filterIsSubclass && !ClassType.isSameGenericClass(varType, filterType); if (isClassRelationshipIndeterminate) { filteredTypes.push(UnknownType.create()); @@ -3757,37 +3832,64 @@ export class Checker extends ParseTreeWalker { let errorMessage: string | undefined; let deprecatedMessage: string | undefined; + function getDeprecatedMessageForFunction(functionType: FunctionType): string { + if ( + functionType.details.declaration && + functionType.details.declaration.node.nodeType === ParseNodeType.Function + ) { + const containingClass = ParseTreeUtils.getEnclosingClass( + functionType.details.declaration.node, + /* stopAtFunction */ true + ); + + if (containingClass) { + return Localizer.Diagnostic.deprecatedMethod().format({ + name: functionType.details.name || '', + className: containingClass.name.value, + }); + } + } + + return Localizer.Diagnostic.deprecatedFunction().format({ + name: functionType.details.name, + }); + } + function getDeprecatedMessageForOverloadedCall(evaluator: TypeEvaluator, type: Type) { // Determine if the node is part of a call expression. If so, // we can determine which overload(s) were used to satisfy // the call expression and determine whether any of them // are deprecated. - const callNode = ParseTreeUtils.getCallForName(node); + let callTypeResult: TypeResult | undefined; + const callNode = ParseTreeUtils.getCallForName(node); if (callNode) { - const callTypeResult = evaluator.getTypeResult(callNode); + callTypeResult = evaluator.getTypeResult(callNode); + } else { + const decoratorNode = ParseTreeUtils.getDecoratorForName(node); + if (decoratorNode) { + callTypeResult = evaluator.getTypeResultForDecorator(decoratorNode); + } + } - if ( - callTypeResult && - callTypeResult.overloadsUsedForCall && - callTypeResult.overloadsUsedForCall.length > 0 - ) { - callTypeResult.overloadsUsedForCall.forEach((overload) => { - if (overload.details.deprecatedMessage !== undefined) { - if (node.value === overload.details.name) { - deprecatedMessage = overload.details.deprecatedMessage; - errorMessage = Localizer.Diagnostic.deprecatedFunction().format({ - name: overload.details.name, - }); - } else if (isInstantiableClass(type) && overload.details.name === '__init__') { - deprecatedMessage = overload.details.deprecatedMessage; - errorMessage = Localizer.Diagnostic.deprecatedConstructor().format({ - name: type.details.name, - }); - } + if ( + callTypeResult && + callTypeResult.overloadsUsedForCall && + callTypeResult.overloadsUsedForCall.length > 0 + ) { + callTypeResult.overloadsUsedForCall.forEach((overload) => { + if (overload.details.deprecatedMessage !== undefined) { + if (node.value === overload.details.name) { + deprecatedMessage = overload.details.deprecatedMessage; + errorMessage = getDeprecatedMessageForFunction(overload); + } else if (isInstantiableClass(type) && overload.details.name === '__init__') { + deprecatedMessage = overload.details.deprecatedMessage; + errorMessage = Localizer.Diagnostic.deprecatedConstructor().format({ + name: type.details.name, + }); } - }); - } + } + }); } } @@ -3805,11 +3907,11 @@ export class Checker extends ParseTreeWalker { getDeprecatedMessageForOverloadedCall(this._evaluator, subtype); } } else if (isFunction(subtype)) { - if (subtype.details.deprecatedMessage !== undefined && node.value === subtype.details.name) { - deprecatedMessage = subtype.details.deprecatedMessage; - errorMessage = Localizer.Diagnostic.deprecatedFunction().format({ - name: subtype.details.name || '', - }); + if (subtype.details.deprecatedMessage !== undefined) { + if (!subtype.details.name || node.value === subtype.details.name) { + deprecatedMessage = subtype.details.deprecatedMessage; + errorMessage = getDeprecatedMessageForFunction(subtype); + } } } else if (isOverloadedFunction(subtype)) { // Determine if the node is part of a call expression. If so, @@ -5853,12 +5955,37 @@ export class Checker extends ParseTreeWalker { // rule is disabled. if (this._fileInfo.diagnosticRuleSet.reportIncompatibleVariableOverride !== 'none') { const decls = overrideSymbol.getDeclarations(); + if (decls.length > 0) { const lastDecl = decls[decls.length - 1]; + const primaryDecl = decls[0]; + // Verify that the override type is assignable to (same or narrower than) // the declared type of the base symbol. - const diagAddendum = new DiagnosticAddendum(); - if (!this._evaluator.assignType(baseType, overrideType, diagAddendum)) { + const isInvariant = primaryDecl?.type === DeclarationType.Variable && !primaryDecl.isFinal; + + let diagAddendum = new DiagnosticAddendum(); + if ( + !this._evaluator.assignType( + baseType, + overrideType, + diagAddendum, + /* destTypeVarContext */ undefined, + /* srcTypeVarContext */ undefined, + isInvariant ? AssignTypeFlags.EnforceInvariance : AssignTypeFlags.Default + ) + ) { + if (isInvariant) { + diagAddendum = new DiagnosticAddendum(); + diagAddendum.addMessage(Localizer.DiagnosticAddendum.overrideIsInvariant()); + diagAddendum.createAddendum().addMessage( + Localizer.DiagnosticAddendum.overrideInvariantMismatch().format({ + overrideType: this._evaluator.printType(overrideType), + baseType: this._evaluator.printType(baseType), + }) + ); + } + const diag = this._evaluator.addDiagnostic( this._fileInfo.diagnosticRuleSet.reportIncompatibleVariableOverride, DiagnosticRule.reportIncompatibleVariableOverride, diff --git a/packages/pyright-internal/src/analyzer/codeFlowEngine.ts b/packages/pyright-internal/src/analyzer/codeFlowEngine.ts index f77dc4fcb..ed7c8af5b 100644 --- a/packages/pyright-internal/src/analyzer/codeFlowEngine.ts +++ b/packages/pyright-internal/src/analyzer/codeFlowEngine.ts @@ -466,7 +466,7 @@ export function getCodeFlowEngine( flowTypeResult = undefined; } else if ( reference.nodeType === ParseNodeType.MemberAccess && - evaluator.isAsymmetricDescriptorAssignment(targetNode) + evaluator.isAsymmetricAccessorAssignment(targetNode) ) { flowTypeResult = undefined; } @@ -1627,7 +1627,6 @@ export function getCodeFlowEngine( const returnType = functionType.details.declaredReturnType; if (returnType) { if ( - FunctionType.isAsync(functionType) && isClassInstance(returnType) && ClassType.isBuiltIn(returnType, 'Coroutine') && returnType.typeArguments && diff --git a/packages/pyright-internal/src/analyzer/constraintSolver.ts b/packages/pyright-internal/src/analyzer/constraintSolver.ts index 828282750..712e7abee 100644 --- a/packages/pyright-internal/src/analyzer/constraintSolver.ts +++ b/packages/pyright-internal/src/analyzer/constraintSolver.ts @@ -435,6 +435,12 @@ export function assignTypeToTypeVar( } if ((flags & AssignTypeFlags.PopulatingExpectedType) !== 0) { + // If we're populating the expected type and the srcType is + // Unknown, ignore it. + if (isUnknown(adjSrcType)) { + return true; + } + // If we're populating the expected type, constrain either the // narrow type bound, wide type bound or both. Don't overwrite // an existing entry. @@ -835,6 +841,7 @@ function assignTypeToParamSpec( newFunction.details.constructorTypeVarScopeId = srcType.details.constructorTypeVarScopeId; newFunction.details.paramSpecTypeVarScopeId = srcType.details.paramSpecTypeVarScopeId; newFunction.details.docString = srcType.details.docString; + newFunction.details.deprecatedMessage = srcType.details.deprecatedMessage; newFunction.details.paramSpec = srcType.details.paramSpec; typeVarContext.setTypeVarType(destType, newFunction); } diff --git a/packages/pyright-internal/src/analyzer/constructors.ts b/packages/pyright-internal/src/analyzer/constructors.ts index f7adfb8f5..18ffb5aca 100644 --- a/packages/pyright-internal/src/analyzer/constructors.ts +++ b/packages/pyright-internal/src/analyzer/constructors.ts @@ -35,6 +35,7 @@ import { buildTypeVarContextFromSpecializedClass, convertToInstance, doForEachSubtype, + ensureFunctionSignaturesAreUnique, getTypeVarScopeId, isPartlyUnknown, isTupleClass, @@ -366,6 +367,14 @@ function validateNewMethod( let argumentErrors = false; const overloadsUsedForCall: FunctionType[] = []; + if (inferenceContext?.signatureTracker) { + newMethodTypeResult.type = ensureFunctionSignaturesAreUnique( + newMethodTypeResult.type, + inferenceContext.signatureTracker, + errorNode.start + ); + } + const typeVarContext = new TypeVarContext(getTypeVarScopeId(type)); typeVarContext.addSolveForScope(getTypeVarScopeId(newMethodTypeResult.type)); if (type.typeAliasInfo) { @@ -434,81 +443,104 @@ function validateInitMethod( let argumentErrors = false; const overloadsUsedForCall: FunctionType[] = []; + if (inferenceContext?.signatureTracker) { + initMethodType = ensureFunctionSignaturesAreUnique( + initMethodType, + inferenceContext.signatureTracker, + errorNode.start + ); + } + // If there is an expected type, analyze the __init__ call for each of the // subtypes that comprise the expected type. If one or more analyzes with no // errors, use those results. This requires special-case processing because // the __init__ method doesn't return the expected type. It always // returns None. if (inferenceContext) { - returnType = mapSubtypes(inferenceContext.expectedType, (expectedSubType) => { - expectedSubType = transformPossibleRecursiveTypeAlias(expectedSubType); - - // If the expected type is the same type as the class and the class - // is already explicitly specialized, don't override the explicit - // specialization. - if ( - isClassInstance(expectedSubType) && - ClassType.isSameGenericClass(type, expectedSubType) && - type.typeArguments - ) { - return undefined; - } + let foundWorkingExpectedType = false; - const typeVarContext = new TypeVarContext(getTypeVarScopeId(type)); - typeVarContext.addSolveForScope(getTypeVarScopeId(initMethodType)); - - if ( - populateTypeVarContextBasedOnExpectedType( - evaluator, - ClassType.cloneAsInstance(type), - expectedSubType, - typeVarContext, - getTypeVarScopesForNode(errorNode), - errorNode.start - ) - ) { - const specializedConstructor = applySolvedTypeVars(initMethodType, typeVarContext); - - let callResult: CallResult | undefined; - callResult = evaluator.useSpeculativeMode(errorNode, () => { - return evaluator.validateCallArguments( - errorNode, - argList, - { type: specializedConstructor }, - typeVarContext.clone(), - skipUnknownArgCheck - ); - }); - - if (!callResult.argumentErrors) { - // Call validateCallArguments again, this time without speculative - // mode, so any errors are reported. - callResult = evaluator.validateCallArguments( - errorNode, - argList, - { type: specializedConstructor }, - typeVarContext, - skipUnknownArgCheck - ); + returnType = mapSubtypes( + inferenceContext.expectedType, + (expectedSubType) => { + // If we've already successfully evaluated the __init__ method with + // one expected type, ignore the remaining ones. + if (foundWorkingExpectedType) { + return undefined; + } - if (callResult.isTypeIncomplete) { - isTypeIncomplete = true; - } + expectedSubType = transformPossibleRecursiveTypeAlias(expectedSubType); + + // If the expected type is the same type as the class and the class + // is already explicitly specialized, don't override the explicit + // specialization. + if ( + isClassInstance(expectedSubType) && + ClassType.isSameGenericClass(type, expectedSubType) && + type.typeArguments + ) { + return undefined; + } - if (callResult.argumentErrors) { - argumentErrors = true; - } + const typeVarContext = new TypeVarContext(getTypeVarScopeId(type)); + typeVarContext.addSolveForScope(getTypeVarScopeId(initMethodType)); - if (callResult.overloadsUsedForCall) { - appendArray(overloadsUsedForCall, callResult.overloadsUsedForCall); + if ( + populateTypeVarContextBasedOnExpectedType( + evaluator, + ClassType.cloneAsInstance(type), + expectedSubType, + typeVarContext, + getTypeVarScopesForNode(errorNode), + errorNode.start + ) + ) { + const specializedConstructor = applySolvedTypeVars(initMethodType, typeVarContext); + + let callResult: CallResult | undefined; + callResult = evaluator.useSpeculativeMode(errorNode, () => { + return evaluator.validateCallArguments( + errorNode, + argList, + { type: specializedConstructor }, + typeVarContext.clone(), + skipUnknownArgCheck + ); + }); + + if (!callResult.argumentErrors) { + // Call validateCallArguments again, this time without speculative + // mode, so any errors are reported. + callResult = evaluator.validateCallArguments( + errorNode, + argList, + { type: specializedConstructor }, + typeVarContext, + skipUnknownArgCheck + ); + + if (callResult.isTypeIncomplete) { + isTypeIncomplete = true; + } + + if (callResult.argumentErrors) { + argumentErrors = true; + } + + if (callResult.overloadsUsedForCall) { + appendArray(overloadsUsedForCall, callResult.overloadsUsedForCall); + } + + // Note that we've found an expected type that works. + foundWorkingExpectedType = true; + + return applyExpectedSubtypeForConstructor(evaluator, type, expectedSubType, typeVarContext); } - - return applyExpectedSubtypeForConstructor(evaluator, type, expectedSubType, typeVarContext); } - } - return undefined; - }); + return undefined; + }, + /* sortSubtypes */ true + ); if (isNever(returnType) || argumentErrors) { returnType = undefined; diff --git a/packages/pyright-internal/src/analyzer/dataClasses.ts b/packages/pyright-internal/src/analyzer/dataClasses.ts index bd5947e8d..b9a0bfc3e 100644 --- a/packages/pyright-internal/src/analyzer/dataClasses.ts +++ b/packages/pyright-internal/src/analyzer/dataClasses.ts @@ -623,8 +623,7 @@ export function synthesizeDataClassMethods( }); } - let synthesizeHashFunction = - !ClassType.isSkipSynthesizedDataClassEq(classType) && ClassType.isFrozenDataClass(classType); + let synthesizeHashFunction = ClassType.isFrozenDataClass(classType); const synthesizeHashNone = !ClassType.isSkipSynthesizedDataClassEq(classType) && !ClassType.isFrozenDataClass(classType); diff --git a/packages/pyright-internal/src/analyzer/declarationUtils.ts b/packages/pyright-internal/src/analyzer/declarationUtils.ts index 8f4e66a16..99f9506e5 100644 --- a/packages/pyright-internal/src/analyzer/declarationUtils.ts +++ b/packages/pyright-internal/src/analyzer/declarationUtils.ts @@ -125,6 +125,7 @@ export function getNameFromDeclaration(declaration: Declaration) { case DeclarationType.Class: case DeclarationType.Function: case DeclarationType.TypeParameter: + case DeclarationType.TypeAlias: return declaration.node.name.value; case DeclarationType.Parameter: @@ -156,6 +157,7 @@ export function getNameNodeForDeclaration(declaration: Declaration): NameNode | case DeclarationType.Function: case DeclarationType.TypeParameter: case DeclarationType.Parameter: + case DeclarationType.TypeAlias: return declaration.node.name; case DeclarationType.Variable: @@ -293,7 +295,19 @@ export function resolveAliasDeclaration( } } - return resolveAliasDeclaration(importLookup, curDeclaration.submoduleFallback, options); + let submoduleFallback = curDeclaration.submoduleFallback; + if (curDeclaration.symbolName) { + submoduleFallback = { ...curDeclaration.submoduleFallback }; + let baseModuleName = submoduleFallback.moduleName; + + if (baseModuleName) { + baseModuleName = `${baseModuleName}.`; + } + + submoduleFallback.moduleName = `${baseModuleName}${curDeclaration.symbolName}`; + } + + return resolveAliasDeclaration(importLookup, submoduleFallback, options); } // If the symbol comes from a native library, we won't @@ -338,6 +352,8 @@ export function resolveAliasDeclaration( return undefined; } + const prevDeclaration = curDeclaration; + // Prefer the last unvisited declaration in the list. This ensures that // we use all of the overloads if it's an overloaded function. const unvisitedDecls = declarations.filter((decl) => !alreadyVisited.includes(decl)); @@ -350,7 +366,7 @@ export function resolveAliasDeclaration( if (lookupResult?.isInPyTypedPackage) { if (!sawPyTypedTransition) { if (symbol.isPrivatePyTypedImport()) { - privatePyTypedImporter = curDeclaration?.moduleName; + privatePyTypedImporter = prevDeclaration?.moduleName; } // Note that we've seen a transition from a non-py.typed to a py.typed diff --git a/packages/pyright-internal/src/analyzer/decorators.ts b/packages/pyright-internal/src/analyzer/decorators.ts index 357c3b36f..ed0742aa2 100644 --- a/packages/pyright-internal/src/analyzer/decorators.ts +++ b/packages/pyright-internal/src/analyzer/decorators.ts @@ -160,7 +160,13 @@ export function applyFunctionDecorator( } if (decoratorCallType.details.builtInName === 'deprecated') { - undecoratedType.details.deprecatedMessage = getCustomDeprecationMessage(decoratorNode); + const deprecationMessage = getCustomDeprecationMessage(decoratorNode); + undecoratedType.details.deprecatedMessage = deprecationMessage; + + if (isFunction(inputFunctionType)) { + inputFunctionType.details.deprecatedMessage = deprecationMessage; + } + return inputFunctionType; } } @@ -431,14 +437,21 @@ function getTypeOfDecorator(evaluator: TypeEvaluator, node: DecoratorNode, funct }, ]; - const returnType = - evaluator.validateCallArguments( - node.expression, - argList, - decoratorTypeResult, - /* typeVarContext */ undefined, - /* skipUnknownArgCheck */ true - ).returnType || UnknownType.create(); + const callTypeResult = evaluator.validateCallArguments( + node.expression, + argList, + decoratorTypeResult, + /* typeVarContext */ undefined, + /* skipUnknownArgCheck */ true + ); + + evaluator.setTypeResultForNode(node, { + type: callTypeResult.returnType ?? UnknownType.create(), + overloadsUsedForCall: callTypeResult.overloadsUsedForCall, + isIncomplete: callTypeResult.isTypeIncomplete, + }); + + const returnType = callTypeResult.returnType ?? UnknownType.create(); // If the return type is a function that has no annotations // and just *args and **kwargs parameters, assume that it @@ -545,6 +558,21 @@ export function addOverloadsToFunctionType(evaluator: TypeEvaluator, node: Funct }); } + // PEP 702 indicates that if the implementation of an overloaded + // function is marked deprecated, all of the overloads should be + // treated as deprecated as well. + if (implementation && implementation.details.deprecatedMessage !== undefined) { + overloadedTypes = overloadedTypes.map((overload) => { + if (FunctionType.isOverloaded(overload) && overload.details.deprecatedMessage === undefined) { + return FunctionType.cloneWithDeprecatedMessage( + overload, + implementation.details.deprecatedMessage + ); + } + return overload; + }); + } + // Create a new overloaded type that copies the contents of the previous // one and adds a new function. const newOverload = OverloadedFunctionType.create(overloadedTypes); diff --git a/packages/pyright-internal/src/analyzer/importResolver.ts b/packages/pyright-internal/src/analyzer/importResolver.ts index 6b7303552..920c4e95e 100644 --- a/packages/pyright-internal/src/analyzer/importResolver.ts +++ b/packages/pyright-internal/src/analyzer/importResolver.ts @@ -30,7 +30,7 @@ import { isDiskPathRoot, isFile, normalizePath, - normalizePathCase, + realCasePath, resolvePaths, stripFileExtension, stripTrailingDirectorySeparator, @@ -170,9 +170,7 @@ export class ImportResolver { } const root = this.getParentImportResolutionRoot(sourceFilePath, execEnv.root); - const origin = ensureTrailingDirectorySeparator( - getDirectoryPath(normalizePathCase(this.fileSystem, normalizePath(sourceFilePath))) - ); + const origin = ensureTrailingDirectorySeparator(getDirectoryPath(sourceFilePath)); let current = origin; while (this._shouldWalkUp(current, root, execEnv)) { @@ -506,7 +504,7 @@ export class ImportResolver { // If the import is absolute and no other method works, try resolving the // absolute in the importing file's directory, then the parent directory, // and so on, until the import root is reached. - sourceFilePath = normalizePathCase(this.fileSystem, normalizePath(sourceFilePath)); + sourceFilePath = realCasePath(normalizePath(sourceFilePath), this.fileSystem); const origin = ensureTrailingDirectorySeparator(getDirectoryPath(sourceFilePath)); const result = this.cachedParentImportResults.getImportResult(origin, importName, importResult); @@ -838,7 +836,7 @@ export class ImportResolver { protected getParentImportResolutionRoot(sourceFilePath: string, executionRoot: string | undefined) { if (executionRoot) { - return ensureTrailingDirectorySeparator(normalizePathCase(this.fileSystem, normalizePath(executionRoot))); + return ensureTrailingDirectorySeparator(realCasePath(normalizePath(executionRoot), this.fileSystem)); } return ensureTrailingDirectorySeparator(getDirectoryPath(sourceFilePath)); @@ -2605,12 +2603,7 @@ export class ImportResolver { return [false, '']; } - return [ - true, - ensureTrailingDirectorySeparator( - normalizePathCase(this.fileSystem, normalizePath(combinePaths(current, '..'))) - ), - ]; + return [true, ensureTrailingDirectorySeparator(normalizePath(combinePaths(current, '..')))]; } private _shouldWalkUp(current: string, root: string, execEnv: ExecutionEnvironment) { diff --git a/packages/pyright-internal/src/analyzer/namedTuples.ts b/packages/pyright-internal/src/analyzer/namedTuples.ts index b1542658b..07b953908 100644 --- a/packages/pyright-internal/src/analyzer/namedTuples.ts +++ b/packages/pyright-internal/src/analyzer/namedTuples.ts @@ -321,7 +321,7 @@ export function createNamedTupleType( // Set the type in the type cache for the dict node so it // doesn't get evaluated again. - evaluator.setTypeForNode(entryList); + evaluator.setTypeResultForNode(entryList, { type: UnknownType.create() }); } else { // A dynamic expression was used, so we can't evaluate // the named tuple statically. @@ -332,7 +332,7 @@ export function createNamedTupleType( // Set the type of the value expression node to Any so we don't attempt to // re-evaluate it later, potentially generating "partially unknown" errors // in strict mode. - evaluator.setTypeForNode(entriesArg.valueExpression, AnyType.create()); + evaluator.setTypeResultForNode(entriesArg.valueExpression, { type: AnyType.create() }); } } } diff --git a/packages/pyright-internal/src/analyzer/parameterUtils.ts b/packages/pyright-internal/src/analyzer/parameterUtils.ts index 6d13e3417..d3968639a 100644 --- a/packages/pyright-internal/src/analyzer/parameterUtils.ts +++ b/packages/pyright-internal/src/analyzer/parameterUtils.ts @@ -12,15 +12,18 @@ import { ClassType, FunctionParameter, FunctionType, + isAnyOrUnknown, isClassInstance, + isParamSpec, isPositionOnlySeparator, + isTypeSame, isTypeVar, isUnpackedClass, isVariadicTypeVar, Type, TypeVarType, } from './types'; -import { partiallySpecializeType } from './typeUtils'; +import { doForEachSubtype, partiallySpecializeType } from './typeUtils'; export function isTypedKwargs(param: FunctionParameter): boolean { return ( @@ -306,3 +309,73 @@ export function getParameterListDetails(type: FunctionType): ParameterListDetail return result; } + +// Returns true if the type of the argument type is "*args: P.args" or +// "*args: Any". Both of these match a parameter of type "*args: P.args". +export function isParamSpecArgsArgument(paramSpec: TypeVarType, argType: Type) { + let isCompatible = true; + + doForEachSubtype(argType, (argSubtype) => { + if ( + isParamSpec(argSubtype) && + argSubtype.paramSpecAccess === 'args' && + isTypeSame(argSubtype, paramSpec, { ignoreTypeFlags: true }) + ) { + return; + } + + if ( + isClassInstance(argSubtype) && + argSubtype.tupleTypeArguments && + argSubtype.tupleTypeArguments.length === 1 && + argSubtype.tupleTypeArguments[0].isUnbounded && + isAnyOrUnknown(argSubtype.tupleTypeArguments[0].type) + ) { + return; + } + + if (isAnyOrUnknown(argSubtype)) { + return; + } + + isCompatible = false; + }); + + return isCompatible; +} + +// Returns true if the type of the argument type is "**kwargs: P.kwargs" or +// "*kwargs: Any". Both of these match a parameter of type "*kwargs: P.kwargs". +export function isParamSpecKwargsArgument(paramSpec: TypeVarType, argType: Type) { + let isCompatible = true; + + doForEachSubtype(argType, (argSubtype) => { + if ( + isParamSpec(argSubtype) && + argSubtype.paramSpecAccess === 'kwargs' && + isTypeSame(argSubtype, paramSpec, { ignoreTypeFlags: true }) + ) { + return; + } + + if ( + isClassInstance(argSubtype) && + ClassType.isBuiltIn(argSubtype, 'dict') && + argSubtype.typeArguments && + argSubtype.typeArguments.length === 2 && + isClassInstance(argSubtype.typeArguments[0]) && + ClassType.isBuiltIn(argSubtype.typeArguments[0], 'str') && + isAnyOrUnknown(argSubtype.typeArguments[1]) + ) { + return; + } + + if (isAnyOrUnknown(argSubtype)) { + return; + } + + isCompatible = false; + }); + + return isCompatible; +} diff --git a/packages/pyright-internal/src/analyzer/parentDirectoryCache.ts b/packages/pyright-internal/src/analyzer/parentDirectoryCache.ts index 459defafa..522b8118b 100644 --- a/packages/pyright-internal/src/analyzer/parentDirectoryCache.ts +++ b/packages/pyright-internal/src/analyzer/parentDirectoryCache.ts @@ -9,7 +9,7 @@ import { getOrAdd } from '../common/collectionUtils'; import { FileSystem } from '../common/fileSystem'; -import { ensureTrailingDirectorySeparator, normalizePath, normalizePathCase } from '../common/pathUtils'; +import { ensureTrailingDirectorySeparator, normalizePath, realCasePath } from '../common/pathUtils'; import { ImportResult } from './importResult'; export type ImportPath = { importPath: string | undefined }; @@ -56,7 +56,7 @@ export class ParentDirectoryCache { this._libPathCache = this._libPathCache ?? this._importRootGetter() - .map((r) => ensureTrailingDirectorySeparator(normalizePathCase(fs, normalizePath(r)))) + .map((r) => ensureTrailingDirectorySeparator(realCasePath(normalizePath(r), fs))) .filter((r) => r !== root) .filter((r) => r.startsWith(root)); diff --git a/packages/pyright-internal/src/analyzer/parseTreeUtils.ts b/packages/pyright-internal/src/analyzer/parseTreeUtils.ts index 6f3db5c50..d0135ef8b 100644 --- a/packages/pyright-internal/src/analyzer/parseTreeUtils.ts +++ b/packages/pyright-internal/src/analyzer/parseTreeUtils.ts @@ -566,6 +566,23 @@ export function getCallForName(node: NameNode): CallNode | undefined { return undefined; } +export function getDecoratorForName(node: NameNode): DecoratorNode | undefined { + if (node.parent?.nodeType === ParseNodeType.Decorator && node.parent.expression === node) { + return node.parent; + } + + if ( + node.parent?.nodeType === ParseNodeType.MemberAccess && + node.parent.memberName === node && + node.parent.parent?.nodeType === ParseNodeType.Decorator && + node.parent.parent.expression === node.parent + ) { + return node.parent.parent; + } + + return undefined; +} + export function getEnclosingSuite(node: ParseNode): SuiteNode | undefined { let curNode = node.parent; diff --git a/packages/pyright-internal/src/analyzer/patternMatching.ts b/packages/pyright-internal/src/analyzer/patternMatching.ts index 780ca6c69..55e11f92f 100644 --- a/packages/pyright-internal/src/analyzer/patternMatching.ts +++ b/packages/pyright-internal/src/analyzer/patternMatching.ts @@ -447,7 +447,7 @@ function narrowTypeBasedOnMappingPattern( }); } - let mappingInfo = getMappingPatternInfo(evaluator, type); + let mappingInfo = getMappingPatternInfo(evaluator, type, pattern); // Further narrow based on pattern entry types. mappingInfo = mappingInfo.filter((mappingSubtypeInfo) => { @@ -1079,7 +1079,7 @@ function narrowTypeBasedOnValuePattern( // Returns information about all subtypes that match the definition of a "mapping" as // specified in PEP 634. -function getMappingPatternInfo(evaluator: TypeEvaluator, type: Type): MappingPatternInfo[] { +function getMappingPatternInfo(evaluator: TypeEvaluator, type: Type, node: PatternAtomNode): MappingPatternInfo[] { const mappingInfo: MappingPatternInfo[] = []; doForEachSubtype(type, (subtype) => { @@ -1093,35 +1093,56 @@ function getMappingPatternInfo(evaluator: TypeEvaluator, type: Type): MappingPat value: concreteSubtype, }, }); - } else if (isClassInstance(concreteSubtype)) { + return; + } + + if (isClassInstance(concreteSubtype)) { + // Is it a TypedDict? if (ClassType.isTypedDictClass(concreteSubtype)) { mappingInfo.push({ subtype, typedDict: concreteSubtype, }); - } else { - let mroClassToSpecialize: ClassType | undefined; - for (const mroClass of concreteSubtype.details.mro) { - if (isInstantiableClass(mroClass) && ClassType.isBuiltIn(mroClass, 'Mapping')) { - mroClassToSpecialize = mroClass; - break; - } + return; + } + + // Is it a subclass of Mapping? + let mroClassToSpecialize: ClassType | undefined; + for (const mroClass of concreteSubtype.details.mro) { + if (isInstantiableClass(mroClass) && ClassType.isBuiltIn(mroClass, 'Mapping')) { + mroClassToSpecialize = mroClass; + break; } + } - if (mroClassToSpecialize) { - const specializedMapping = partiallySpecializeType( - mroClassToSpecialize, - concreteSubtype - ) as ClassType; - if (specializedMapping.typeArguments && specializedMapping.typeArguments.length >= 2) { - mappingInfo.push({ - subtype, - dictTypeArgs: { - key: specializedMapping.typeArguments[0], - value: specializedMapping.typeArguments[1], - }, - }); - } + if (mroClassToSpecialize) { + const specializedMapping = partiallySpecializeType(mroClassToSpecialize, concreteSubtype) as ClassType; + + if (specializedMapping.typeArguments && specializedMapping.typeArguments.length >= 2) { + mappingInfo.push({ + subtype, + dictTypeArgs: { + key: specializedMapping.typeArguments[0], + value: specializedMapping.typeArguments[1], + }, + }); + } + + return; + } + + // Is it a superclass of Mapping? + const mappingType = evaluator.getTypingType(node, 'Mapping'); + if (mappingType && isInstantiableClass(mappingType)) { + const mappingObject = ClassType.cloneAsInstance(mappingType); + if (evaluator.assignType(type, mappingObject)) { + mappingInfo.push({ + subtype, + dictTypeArgs: { + key: UnknownType.create(), + value: UnknownType.create(), + }, + }); } } } @@ -1427,7 +1448,7 @@ export function assignTypeToPatternTargets( } case ParseNodeType.PatternMapping: { - const mappingInfo = getMappingPatternInfo(evaluator, narrowedType); + const mappingInfo = getMappingPatternInfo(evaluator, narrowedType, pattern); pattern.entries.forEach((mappingEntry) => { const keyTypes: Type[] = []; diff --git a/packages/pyright-internal/src/analyzer/program.ts b/packages/pyright-internal/src/analyzer/program.ts index ed16698a1..ff86c2871 100644 --- a/packages/pyright-internal/src/analyzer/program.ts +++ b/packages/pyright-internal/src/analyzer/program.ts @@ -29,7 +29,6 @@ import { getRelativePath, makeDirectories, normalizePath, - normalizePathCase, stripFileExtension, } from '../common/pathUtils'; import { convertRangeToTextRange } from '../common/positionUtils'; @@ -169,17 +168,17 @@ export class Program { constructor( initialImportResolver: ImportResolver, initialConfigOptions: ConfigOptions, - private _serviceProvider: ServiceProvider, + readonly serviceProvider: ServiceProvider, logTracker?: LogTracker, private _disableChecker?: boolean, cacheManager?: CacheManager, id?: string ) { - this._console = _serviceProvider.tryGet(ServiceKeys.console) || new StandardConsole(); + this._console = serviceProvider.tryGet(ServiceKeys.console) || new StandardConsole(); this._logTracker = logTracker ?? new LogTracker(this._console, 'FG'); this._importResolver = initialImportResolver; this._configOptions = initialConfigOptions; - this._sourceFileFactory = _serviceProvider.sourceFileFactory(); + this._sourceFileFactory = serviceProvider.sourceFileFactory(); this._cacheManager = cacheManager ?? new CacheManager(); this._cacheManager.registerCacheOwner(this); @@ -301,13 +300,13 @@ export class Program { // We need to determine which files to remove from the existing file list. const newFileMap = new Map(); filePaths.forEach((path) => { - newFileMap.set(normalizePathCase(this.fileSystem, path), path); + newFileMap.set(path, path); }); // Files that are not in the tracked file list are // marked as no longer tracked. this._sourceFileList.forEach((oldFile) => { - const filePath = normalizePathCase(this.fileSystem, oldFile.sourceFile.getFilePath()); + const filePath = oldFile.sourceFile.getFilePath(); if (!newFileMap.has(filePath)) { oldFile.isTracked = false; } @@ -573,9 +572,8 @@ export class Program { } containsSourceFileIn(folder: string): boolean { - const normalizedFolder = normalizePathCase(this.fileSystem, folder); for (const normalizedSourceFilePath of this._sourceFileMap.keys()) { - if (normalizedSourceFilePath.startsWith(normalizedFolder)) { + if (normalizedSourceFilePath.startsWith(folder)) { return true; } } @@ -612,7 +610,7 @@ export class Program { } getSourceFileInfo(filePath: string): SourceFileInfo | undefined { - return this._sourceFileMap.get(normalizePathCase(this.fileSystem, filePath)); + return this._sourceFileMap.get(filePath); } getBoundSourceFileInfo(filePath: string, content?: string, force?: boolean): SourceFileInfo | undefined { @@ -945,7 +943,7 @@ export class Program { const program = new Program( this._importResolver, this._configOptions, - this._serviceProvider, + this.serviceProvider, new LogTracker(this._console, 'Cloned') ); @@ -1157,7 +1155,7 @@ export class Program { return true; } - const filePath = normalizePathCase(this.fileSystem, fileInfo.sourceFile.getFilePath()); + const filePath = fileInfo.sourceFile.getFilePath(); // Avoid infinite recursion. if (recursionSet.has(filePath)) { @@ -1331,7 +1329,7 @@ export class Program { sourceFileInfo.chainedSourceFile = undefined; } else { const filePath = sourceFileInfo.chainedSourceFile.sourceFile.getFilePath(); - newImportPathMap.set(normalizePathCase(this.fileSystem, filePath), { + newImportPathMap.set(filePath, { path: filePath, isTypeshedFile: false, isThirdPartyImport: false, @@ -1347,7 +1345,7 @@ export class Program { const filePath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1]; if (filePath) { const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult); - newImportPathMap.set(normalizePathCase(this.fileSystem, filePath), { + newImportPathMap.set(filePath, { path: filePath, isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile, @@ -1362,7 +1360,7 @@ export class Program { if (this._isImportAllowed(sourceFileInfo, importResult, implicitImport.isStubFile)) { if (!implicitImport.isNativeLib) { const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult); - newImportPathMap.set(normalizePathCase(this.fileSystem, implicitImport.path), { + newImportPathMap.set(implicitImport.path, { path: implicitImport.path, isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile, @@ -1409,15 +1407,13 @@ export class Program { const updatedImportMap = new Map(); sourceFileInfo.imports.forEach((importInfo) => { - const oldFilePath = normalizePathCase(this.fileSystem, importInfo.sourceFile.getFilePath()); + const oldFilePath = importInfo.sourceFile.getFilePath(); // A previous import was removed. if (!newImportPathMap.has(oldFilePath)) { importInfo.mutate((s) => { s.importedBy = s.importedBy.filter( - (fi) => - normalizePathCase(this.fileSystem, fi.sourceFile.getFilePath()) !== - normalizePathCase(this.fileSystem, sourceFileInfo.sourceFile.getFilePath()) + (fi) => fi.sourceFile.getFilePath() !== sourceFileInfo.sourceFile.getFilePath() ); }); } else { @@ -1492,12 +1488,12 @@ export class Program { } private _removeSourceFileFromListAndMap(filePath: string, indexToRemove: number) { - this._sourceFileMap.delete(normalizePathCase(this.fileSystem, filePath)); + this._sourceFileMap.delete(filePath); this._sourceFileList.splice(indexToRemove, 1); } private _addToSourceFileListAndMap(fileInfo: SourceFileInfo) { - const filePath = normalizePathCase(this.fileSystem, fileInfo.sourceFile.getFilePath()); + const filePath = fileInfo.sourceFile.getFilePath(); // We should never add a file with the same path twice. assert(!this._sourceFileMap.has(filePath)); @@ -1791,14 +1787,12 @@ export class Program { ); if (importResult.isImportFound && !importResult.isNativeLib && importResult.resolvedPaths.length > 0) { - let resolvedPath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1]; + const resolvedPath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1]; if (resolvedPath) { // See if the source file already exists in the program. sourceFileInfo = this.getSourceFileInfo(resolvedPath); if (!sourceFileInfo) { - resolvedPath = normalizePathCase(this.fileSystem, resolvedPath); - // Start tracking the source file. this.addTrackedFile(resolvedPath); sourceFileInfo = this.getSourceFileInfo(resolvedPath); @@ -2020,7 +2014,7 @@ export class Program { ) { // If the file is already in the closure map, we found a cyclical // dependency. Don't recur further. - const filePath = normalizePathCase(this.fileSystem, file.sourceFile.getFilePath()); + const filePath = file.sourceFile.getFilePath(); if (closureMap.has(filePath)) { return; } @@ -2066,7 +2060,7 @@ export class Program { return false; } - const filePath = normalizePathCase(this.fileSystem, sourceFileInfo.sourceFile.getFilePath()); + const filePath = sourceFileInfo.sourceFile.getFilePath(); filesVisited.set(filePath, sourceFileInfo); @@ -2129,7 +2123,7 @@ export class Program { } private _markFileDirtyRecursive(sourceFileInfo: SourceFileInfo, markSet: Set, forceRebinding = false) { - const filePath = normalizePathCase(this.fileSystem, sourceFileInfo.sourceFile.getFilePath()); + const filePath = sourceFileInfo.sourceFile.getFilePath(); // Don't mark it again if it's already been visited. if (markSet.has(filePath)) { @@ -2147,6 +2141,7 @@ export class Program { }); // Change in the current file could impact checker result of chainedSourceFile such as unused symbols. + let reevaluationRequired = false; let chainedSourceFile = sourceFileInfo.chainedSourceFile; while (chainedSourceFile) { if (chainedSourceFile.sourceFile.isCheckingRequired()) { @@ -2155,8 +2150,17 @@ export class Program { return; } + reevaluationRequired = true; chainedSourceFile.sourceFile.markReanalysisRequired(/* forceRebinding */ false); chainedSourceFile = chainedSourceFile.chainedSourceFile; } + + // If the checker is going to run again, we have to recreate the type evaulator so + // that it actually reevaluates all the nodes (instead of using the cache). + // This is necessary because the original file change may not recreate the TypeEvaluator. + // For example, it might be a file delete. + if (reevaluationRequired) { + this._createNewEvaluator(); + } } } diff --git a/packages/pyright-internal/src/analyzer/protocols.ts b/packages/pyright-internal/src/analyzer/protocols.ts index d9359be20..6f9b21ef0 100644 --- a/packages/pyright-internal/src/analyzer/protocols.ts +++ b/packages/pyright-internal/src/analyzer/protocols.ts @@ -17,6 +17,7 @@ import { getLastTypedDeclaredForSymbol } from './symbolUtils'; import { TypeEvaluator } from './typeEvaluatorTypes'; import { ClassType, + isClass, isClassInstance, isFunction, isInstantiableClass, @@ -490,7 +491,10 @@ function assignClassToProtocolInternal( srcPrimaryDecl?.type === DeclarationType.Variable ) { const isDestConst = !!destPrimaryDecl.isConstant; - const isSrcConst = ClassType.isReadOnlyInstanceVariables(srcType) || !!srcPrimaryDecl.isConstant; + const isSrcConst = + (isClass(srcMemberInfo.classType) && + ClassType.isReadOnlyInstanceVariables(srcMemberInfo.classType)) || + !!srcPrimaryDecl.isConstant; if (!isDestConst && isSrcConst) { if (subDiag) { diff --git a/packages/pyright-internal/src/analyzer/pythonPathUtils.ts b/packages/pyright-internal/src/analyzer/pythonPathUtils.ts index 642052278..51f559603 100644 --- a/packages/pyright-internal/src/analyzer/pythonPathUtils.ts +++ b/packages/pyright-internal/src/analyzer/pythonPathUtils.ts @@ -43,14 +43,14 @@ export function getTypeShedFallbackPath(fs: FileSystem) { const typeshedPath = combinePaths(moduleDirectory, pathConsts.typeshedFallback); if (fs.existsSync(typeshedPath)) { - return typeshedPath; + return fs.realCasePath(typeshedPath); } // In the debug version of Pyright, the code is one level // deeper, so we need to look one level up for the typeshed fallback. const debugTypeshedPath = combinePaths(getDirectoryPath(moduleDirectory), pathConsts.typeshedFallback); if (fs.existsSync(debugTypeshedPath)) { - return debugTypeshedPath; + return fs.realCasePath(debugTypeshedPath); } return undefined; @@ -86,7 +86,7 @@ export function findPythonSearchPaths( ); if (sitePackagesPath) { addPathIfUnique(foundPaths, sitePackagesPath); - sitePackagesPaths.push(sitePackagesPath); + sitePackagesPaths.push(fs.realCasePath(sitePackagesPath)); } }); @@ -114,16 +114,18 @@ export function findPythonSearchPaths( // Fall back on the python interpreter. const pathResult = host.getPythonSearchPaths(configOptions.pythonPath, importFailureInfo); if (includeWatchPathsOnly && workspaceRoot) { - const paths = pathResult.paths.filter( - (p) => - !containsPath(workspaceRoot, p, /* ignoreCase */ true) || - containsPath(pathResult.prefix, p, /* ignoreCase */ true) - ); + const paths = pathResult.paths + .filter( + (p) => + !containsPath(workspaceRoot, p, /* ignoreCase */ true) || + containsPath(pathResult.prefix, p, /* ignoreCase */ true) + ) + .map((p) => fs.realCasePath(p)); return paths; } - return pathResult.paths; + return pathResult.paths.map((p) => fs.realCasePath(p)); } export function isPythonBinary(p: string): boolean { @@ -198,7 +200,7 @@ export function getPathsFromPthFiles(fs: FileSystem, parentDir: string): string[ .sort((a, b) => compareComparableValues(a.name, b.name)); pthFiles.forEach((pthFile) => { - const filePath = combinePaths(parentDir, pthFile.name); + const filePath = fs.realCasePath(combinePaths(parentDir, pthFile.name)); const fileStats = tryStat(fs, filePath); // Skip all files that are much larger than expected. @@ -210,7 +212,7 @@ export function getPathsFromPthFiles(fs: FileSystem, parentDir: string): string[ if (trimmedLine.length > 0 && !trimmedLine.startsWith('#') && !trimmedLine.match(/^import\s/)) { const pthPath = combinePaths(parentDir, trimmedLine); if (fs.existsSync(pthPath) && isDirectory(fs, pthPath)) { - searchPaths.push(pthPath); + searchPaths.push(fs.realCasePath(pthPath)); } } }); diff --git a/packages/pyright-internal/src/analyzer/service.ts b/packages/pyright-internal/src/analyzer/service.ts index bb14415a8..dabd5ed92 100644 --- a/packages/pyright-internal/src/analyzer/service.ts +++ b/packages/pyright-internal/src/analyzer/service.ts @@ -27,7 +27,6 @@ import { defaultStubsDirectory } from '../common/pathConsts'; import { FileSpec, combinePaths, - comparePaths, containsPath, forEachAncestorDirectory, getDirectoryPath, @@ -43,6 +42,7 @@ import { makeDirectories, normalizePath, normalizeSlashes, + realCasePath, stripFileExtension, tryRealpath, tryStat, @@ -311,8 +311,9 @@ export class AnalyzerService { this._backgroundAnalysisProgram.setConfigOptions(configOptions); - this._executionRootPath = normalizePath( - combinePaths(commandLineOptions.executionRoot, configOptions.projectRoot) + this._executionRootPath = realCasePath( + combinePaths(commandLineOptions.executionRoot, configOptions.projectRoot), + this.fs ); this._applyConfigOptions(host); } @@ -545,7 +546,7 @@ export class AnalyzerService { // Calculates the effective options based on the command-line options, // an optional config file, and default values. private _getConfigOptions(host: Host, commandLineOptions: CommandLineOptions): ConfigOptions { - let projectRoot = commandLineOptions.executionRoot; + let projectRoot = realCasePath(commandLineOptions.executionRoot, this.fs); let configFilePath: string | undefined; let pyprojectFilePath: string | undefined; @@ -553,16 +554,16 @@ export class AnalyzerService { // If the config file path was specified, determine whether it's // a directory (in which case the default config file name is assumed) // or a file. - configFilePath = combinePaths( - commandLineOptions.executionRoot, - normalizePath(commandLineOptions.configFilePath) + configFilePath = realCasePath( + combinePaths(commandLineOptions.executionRoot, normalizePath(commandLineOptions.configFilePath)), + this.fs ); if (!this.fs.existsSync(configFilePath)) { this._console.info(`Configuration file not found at ${configFilePath}.`); - configFilePath = commandLineOptions.executionRoot; + configFilePath = realCasePath(commandLineOptions.executionRoot, this.fs); } else { if (configFilePath.toLowerCase().endsWith('.json')) { - projectRoot = getDirectoryPath(configFilePath); + projectRoot = realCasePath(getDirectoryPath(configFilePath), this.fs); } else { projectRoot = configFilePath; configFilePath = this._findConfigFile(configFilePath); @@ -614,7 +615,7 @@ export class AnalyzerService { this._console.info( `Setting pythonPath for service "${this._instanceName}": ` + `"${commandLineOptions.pythonPath}"` ); - configOptions.pythonPath = commandLineOptions.pythonPath; + (configOptions.pythonPath = commandLineOptions.pythonPath), this.fs; } if (commandLineOptions.pythonEnvironmentName) { this._console.info( @@ -745,7 +746,7 @@ export class AnalyzerService { if (commandLineOptions.typeshedPath) { if (!configOptions.typeshedPath) { - configOptions.typeshedPath = commandLineOptions.typeshedPath; + configOptions.typeshedPath = realCasePath(commandLineOptions.typeshedPath, this.fs); } else { reportDuplicateSetting('typeshedPath', configOptions.typeshedPath); } @@ -756,7 +757,7 @@ export class AnalyzerService { // stdlib packages that don't match the current Python version. if ( configOptions.typeshedPath && - comparePaths(configOptions.typeshedPath, projectRoot) === 0 && + configOptions.typeshedPath === projectRoot && configOptions.defaultPythonVersion !== undefined ) { const excludeList = this.getImportResolver().getTypeshedStdlibExcludeList( @@ -794,7 +795,7 @@ export class AnalyzerService { if (commandLineOptions.stubPath) { if (!configOptions.stubPath) { - configOptions.stubPath = commandLineOptions.stubPath; + configOptions.stubPath = realCasePath(commandLineOptions.stubPath, this.fs); } else { reportDuplicateSetting('stubPath', configOptions.stubPath); } @@ -865,7 +866,7 @@ export class AnalyzerService { private _getTypeStubFolder() { const stubPath = this._configOptions.stubPath ?? - normalizePath(combinePaths(this._configOptions.projectRoot, defaultStubsDirectory)); + realCasePath(combinePaths(this._configOptions.projectRoot, defaultStubsDirectory), this.fs); if (!this._typeStubTargetPath || !this._typeStubTargetImportName) { const errMsg = `Import '${this._typeStubTargetImportName}'` + ` could not be resolved`; @@ -919,7 +920,7 @@ export class AnalyzerService { for (const name of configFileNames) { const fileName = combinePaths(searchPath, name); if (this.fs.existsSync(fileName)) { - return fileName; + return realCasePath(fileName, this.fs); } } return undefined; @@ -932,7 +933,7 @@ export class AnalyzerService { private _findPyprojectTomlFile(searchPath: string) { const fileName = combinePaths(searchPath, pyprojectTomlName); if (this.fs.existsSync(fileName)) { - return fileName; + return realCasePath(fileName, this.fs); } return undefined; } @@ -1276,6 +1277,9 @@ export class AnalyzerService { return; } + // Make sure path is the true case. + path = realCasePath(path, this.fs); + const eventInfo = getEventInfo(this.fs, this._console, this._program, event, path); if (!eventInfo) { // no-op event, return. diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index 6e756cf01..768ce3ed0 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -37,6 +37,7 @@ import { CaseNode, ClassNode, ConstantNode, + DecoratorNode, DictionaryNode, ExceptNode, ExpressionNode, @@ -138,6 +139,8 @@ import { ParameterSource, VirtualParameterDetails, getParameterListDetails, + isParamSpecArgsArgument, + isParamSpecKwargsArgument, } from './parameterUtils'; import * as ParseTreeUtils from './parseTreeUtils'; import { assignTypeToPatternTargets, checkForUnusedPattern, narrowTypeBasedOnPattern } from './patternMatching'; @@ -286,6 +289,7 @@ import { TypeCategory, TypeCondition, TypeFlags, + TypeVarScopeId, TypeVarScopeType, TypeVarType, TypedDictEntry, @@ -703,8 +707,8 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } } - function setTypeForNode(node: ParseNode, type: Type = UnknownType.create(), flags = EvaluatorFlags.None) { - writeTypeCache(node, { type }, flags); + function setTypeResultForNode(node: ParseNode, typeResult: TypeResult, flags = EvaluatorFlags.None) { + writeTypeCache(node, typeResult, flags); } function setAsymmetricDescriptorAssignment(node: ParseNode) { @@ -834,8 +838,14 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions }); } + function getTypeResultForDecorator(node: DecoratorNode): TypeResult | undefined { + return evaluateTypeForSubnode(node, () => { + evaluateTypesForExpressionInContext(node.expression); + }); + } + // Reads the type of the node from the cache. - function getCachedType(node: ExpressionNode): Type | undefined { + function getCachedType(node: ExpressionNode | DecoratorNode): Type | undefined { return readTypeCache(node, EvaluatorFlags.None); } @@ -1291,7 +1301,9 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions ClassType.isTupleClass(typeResult.type) && typeResult.type.tupleTypeArguments?.length === 0; - if (!isEmptyVariadic) { + const isEllipsis = isClassInstance(typeResult.type) && ClassType.isBuiltIn(typeResult.type, 'ellipsis'); + + if (!isEmptyVariadic && !isEllipsis) { addExpectedClassDiagnostic(typeResult.type, node); typeResult.type = UnknownType.create(); typeResult.typeErrors = true; @@ -1927,7 +1939,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions memberAccessFlags = MemberAccessFlags.None, bindToType?: ClassType | TypeVarType ): TypeResult | undefined { - const memberInfo = getTypeOfClassMemberName( + let memberInfo = getTypeOfClassMemberName( errorNode, ClassType.cloneAsInstantiable(objectType), /* isAccessedThroughObject */ true, @@ -1938,6 +1950,27 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions bindToType ); + if (!memberInfo) { + const metaclass = objectType.details.effectiveMetaclass; + if ( + metaclass && + isInstantiableClass(metaclass) && + !ClassType.isBuiltIn(metaclass, 'type') && + !ClassType.isSameGenericClass(metaclass, objectType) + ) { + memberInfo = getTypeOfClassMemberName( + errorNode, + metaclass, + /* isAccessedThroughObject */ false, + memberName, + usage, + /* diag */ undefined, + memberAccessFlags | MemberAccessFlags.AccessInstanceMembersOnly, + ClassType.cloneAsInstantiable(objectType) + ); + } + } + if (memberInfo) { return { type: memberInfo.type, @@ -1946,6 +1979,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions isAsymmetricAccessor: memberInfo.isAsymmetricAccessor, }; } + return undefined; } @@ -3580,8 +3614,17 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions // If this is a TypeVarTuple *Ts, convert it to an unpacked tuple // *tuple[*Ts]. if (isVariadicTypeVar(subtype)) { + // If it's in a union, convert to type or object. if (subtype.isVariadicInUnion) { - return subtype; + if (TypeBase.isInstantiable(subtype)) { + if (typeClassType && isInstantiableClass(typeClassType)) { + return typeClassType; + } + } else if (objectType) { + return objectType; + } + + return AnyType.create(); } if (tupleClassType && isInstantiableClass(tupleClassType)) { @@ -4843,9 +4886,9 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions scopeUsesTypeParameterSyntax = !!curNode.typeParameters; nestedClassCount++; } else if (curNode.nodeType === ParseNodeType.Function) { - const functionTypeInfo = getTypeOfFunction(curNode); - if (functionTypeInfo) { - const functionDetails = functionTypeInfo.functionType.details; + const functionType = getTypeOfFunctionPredecorated(curNode); + if (functionType) { + const functionDetails = functionType.details; typeParametersForScope = functionDetails.typeParameters; // Was this type parameter "rescoped" to a callable found within the @@ -5495,6 +5538,9 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions if (flags & MemberAccessFlags.AccessClassMembersOnly) { classLookupFlags |= ClassMemberLookupFlags.SkipInstanceVariables; } + if (flags & MemberAccessFlags.AccessInstanceMembersOnly) { + classLookupFlags |= ClassMemberLookupFlags.SkipClassVariables; + } if (flags & MemberAccessFlags.SkipBaseClasses) { classLookupFlags |= ClassMemberLookupFlags.SkipBaseClasses; } @@ -7460,7 +7506,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions }); // Set the node's type so it isn't reevaluated later. - setTypeForNode(node.items[0].valueExpression, UnknownType.create()); + setTypeResultForNode(node.items[0].valueExpression, { type: UnknownType.create() }); } else { node.items.forEach((arg, index) => { const typeResult = getTypeArgTypeResult(arg.valueExpression, index); @@ -7518,7 +7564,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions }; // Set the node's type so it isn't reevaluated later. - setTypeForNode(node, UnknownType.create()); + setTypeResultForNode(node, { type: UnknownType.create() }); } else if (node.nodeType === ParseNodeType.Dictionary && supportsDictExpression) { const inlinedTypeDict = typedDictClassType && isInstantiableClass(typedDictClassType) @@ -7593,21 +7639,25 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions if (inferenceContext && isUnion(inferenceContext.expectedType)) { let matchingSubtype: Type | undefined; - doForEachSubtype(inferenceContext.expectedType, (subtype) => { - if (isAny(subtype)) { - expectedTypeContainsAny = true; - } + doForEachSubtype( + inferenceContext.expectedType, + (subtype) => { + if (isAny(subtype)) { + expectedTypeContainsAny = true; + } - if (!matchingSubtype) { - const subtypeResult = useSpeculativeMode(node, () => { - return getTypeOfTupleWithContext(node, makeInferenceContext(subtype)); - }); + if (!matchingSubtype) { + const subtypeResult = useSpeculativeMode(node, () => { + return getTypeOfTupleWithContext(node, makeInferenceContext(subtype)); + }); - if (subtypeResult && assignType(subtype, subtypeResult.type)) { - matchingSubtype = subtype; + if (subtypeResult && assignType(subtype, subtypeResult.type)) { + matchingSubtype = subtype; + } } - } - }); + }, + /* sortSubtypes */ true + ); effectiveExpectedType = matchingSubtype; } @@ -8696,6 +8746,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions ): CallResult { let filteredMatchResults: MatchArgsToParamsResult[] = []; let contextFreeArgTypes: Type[] | undefined; + let isTypeIncomplete = !!typeResult.isIncomplete; // Start by evaluating the types of the arguments without any expected // type. Also, filter the list of overloads based on the number of @@ -8732,7 +8783,19 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions if (!isDiagnosticSuppressedForNode(errorNode)) { const functionName = typeResult.type.overloads[0].details.name || ''; const diagAddendum = new DiagnosticAddendum(); - const argTypes = argList.map((t) => printType(getTypeOfArgument(t).type)); + const argTypes = argList.map((t) => { + const typeString = printType(getTypeOfArgument(t).type); + + if (t.argumentCategory === ArgumentCategory.UnpackedList) { + return `*${typeString}`; + } + + if (t.argumentCategory === ArgumentCategory.UnpackedDictionary) { + return `**${typeString}`; + } + + return typeString; + }); diagAddendum.addMessage( Localizer.DiagnosticAddendum.argumentTypes().format({ types: argTypes.join(', ') }) @@ -8745,7 +8808,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions ); } - return { argumentErrors: true, isTypeIncomplete: false, overloadsUsedForCall: [] }; + return { argumentErrors: true, isTypeIncomplete, overloadsUsedForCall: [] }; } // Create a helper function that evaluates the overload that best @@ -8782,7 +8845,6 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } let expandedArgTypes: (Type | undefined)[][] | undefined = [argList.map((arg) => undefined)]; - let isTypeIncomplete = !!typeResult.isIncomplete; while (true) { const callResult = validateOverloadsWithExpandedTypes( @@ -8846,7 +8908,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions return { ...result, argumentErrors: true }; } - return { argumentErrors: true, isTypeIncomplete: false, overloadsUsedForCall: [] }; + return { argumentErrors: true, isTypeIncomplete, overloadsUsedForCall: [] }; } // Replaces each item in the expandedArgTypes with n items where n is @@ -9945,19 +10007,21 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions // all positional parameters specified in the Concatenate must be // filled explicitly. if (typeResult.type.details.paramSpec && paramIndex < positionParamLimitIndex) { - if (!isDiagnosticSuppressedForNode(errorNode)) { - addDiagnostic( - AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, - DiagnosticRule.reportGeneralTypeIssues, - positionParamLimitIndex === 1 - ? Localizer.Diagnostic.argPositionalExpectedOne() - : Localizer.Diagnostic.argPositionalExpectedCount().format({ - expected: positionParamLimitIndex, - }), - argList[argIndex].valueExpression ?? errorNode - ); + if (isTypeVar(argTypeResult.type) && argTypeResult.type.paramSpecAccess === 'args') { + if (!isDiagnosticSuppressedForNode(errorNode)) { + addDiagnostic( + AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + positionParamLimitIndex === 1 + ? Localizer.Diagnostic.argPositionalExpectedOne() + : Localizer.Diagnostic.argPositionalExpectedCount().format({ + expected: positionParamLimitIndex, + }), + argList[argIndex].valueExpression ?? errorNode + ); + } + reportedArgError = true; } - reportedArgError = true; } const argType = argTypeResult.type; @@ -10306,17 +10370,19 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } reportedArgError = true; } - } else if (isParamSpec(argType) && argType.paramSpecAccess === 'kwargs') { + } else if ( + typeResult.type.details.paramSpec && + isParamSpecKwargsArgument(typeResult.type.details.paramSpec, argType) + ) { unpackedDictionaryArgType = AnyType.create(); - if (typeResult.type.details.paramSpec) { - validateArgTypeParams.push({ - paramCategory: ParameterCategory.KwargsDict, - paramType: typeResult.type.details.paramSpec, - requiresTypeVarMatching: false, - argument: argList[argIndex], - errorNode: argList[argIndex].valueExpression || errorNode, - }); - } + validateArgTypeParams.push({ + paramCategory: ParameterCategory.KwargsDict, + paramType: typeResult.type.details.paramSpec, + requiresTypeVarMatching: false, + argument: argList[argIndex], + argType: isParamSpec(argType) ? undefined : AnyType.create(), + errorNode: argList[argIndex].valueExpression || errorNode, + }); } else { const strObjType = getBuiltInObject(errorNode, 'str'); @@ -10477,8 +10543,8 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions reportedArgError = true; } } else if (argList[argIndex].argumentCategory === ArgumentCategory.UnpackedList) { - // Handle the case where a *args: P.args is passed as an argument to - // a function that accepts a ParamSpec. + // Handle the case where a *args: P.args (or *args: Any) is passed as an + // argument to a function that accepts a ParamSpec. if (typeResult.type.details.paramSpec) { const argTypeResult = getTypeOfArgument(argList[argIndex]); const argType = argTypeResult.type; @@ -10487,12 +10553,13 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions isTypeIncomplete = true; } - if (isParamSpec(argType) && argType.paramSpecAccess === 'args') { + if (isParamSpecArgsArgument(typeResult.type.details.paramSpec, argType)) { validateArgTypeParams.push({ paramCategory: ParameterCategory.ArgsList, paramType: typeResult.type.details.paramSpec, requiresTypeVarMatching: false, argument: argList[argIndex], + argType: isParamSpec(argType) ? undefined : AnyType.create(), errorNode: argList[argIndex].valueExpression ?? errorNode, }); } @@ -10815,26 +10882,30 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions // that is type compatible with that class, filter the subtypes in // the union to see if we can find one that is potentially compatible. if (isUnion(effectiveExpectedType)) { - const filteredType = mapSubtypes(effectiveExpectedType, (subtype) => { - if (!isClassInstance(subtype) || subtype.details.typeParameters.length === 0) { - return undefined; - } + const filteredType = mapSubtypes( + effectiveExpectedType, + (subtype) => { + if (!isClassInstance(subtype) || subtype.details.typeParameters.length === 0) { + return undefined; + } - if ( - ClassType.isProtocolClass(subtype) || - subtype.details.mro.some((mroClass) => { - return ( - isClassInstance(mroClass) && - mroClass.details.typeParameters.length > 0 && - ClassType.isSameGenericClass(effectiveReturnType, mroClass) - ); - }) - ) { - return subtype; - } + if ( + ClassType.isProtocolClass(subtype) || + subtype.details.mro.some((mroClass) => { + return ( + isClassInstance(mroClass) && + mroClass.details.typeParameters.length > 0 && + ClassType.isSameGenericClass(effectiveReturnType, mroClass) + ); + }) + ) { + return subtype; + } - return undefined; - }); + return undefined; + }, + /* sortSubtypes */ true + ); if (isClassInstance(filteredType)) { effectiveExpectedType = filteredType; @@ -11069,13 +11140,13 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions if (type.details.paramSpec) { if (argParam.argument.argumentCategory === ArgumentCategory.UnpackedList) { - if (isParamSpec(argResult.argType) && argResult.argType.paramSpecAccess === 'args') { + if (isParamSpecArgsArgument(type.details.paramSpec, argResult.argType)) { sawParamSpecArgs = true; } } if (argParam.argument.argumentCategory === ArgumentCategory.UnpackedDictionary) { - if (isParamSpec(argResult.argType) && argResult.argType.paramSpecAccess === 'kwargs') { + if (isParamSpecKwargsArgument(type.details.paramSpec, argResult.argType)) { sawParamSpecKwargs = true; } } @@ -12368,6 +12439,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions allowParamSpec: true, allowTypeVarsWithoutScopeId: true, }); + if (typeResult.typeErrors) { return undefined; } @@ -12376,6 +12448,11 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions functionType.details.paramSpec = typeResult.type; return functionType; } + + if (isClassInstance(typeResult.type) && ClassType.isBuiltIn(typeResult.type, 'ellipsis')) { + FunctionType.addDefaultParameters(functionType); + return functionType; + } } addDiagnostic( @@ -12849,25 +12926,29 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions let matchingSubtype: Type | undefined; let matchingSubtypeResult: TypeResult | undefined; - doForEachSubtype(inferenceContext.expectedType, (subtype) => { - // Use shortcut if we've already found a match. - if (matchingSubtypeResult && !matchingSubtypeResult.typeErrors) { - return; - } + doForEachSubtype( + inferenceContext.expectedType, + (subtype) => { + // Use shortcut if we've already found a match. + if (matchingSubtypeResult && !matchingSubtypeResult.typeErrors) { + return; + } - const subtypeResult = useSpeculativeMode(node, () => { - return getTypeOfDictionaryWithContext(node, makeInferenceContext(subtype)); - }); + const subtypeResult = useSpeculativeMode(node, () => { + return getTypeOfDictionaryWithContext(node, makeInferenceContext(subtype)); + }); - if (subtypeResult && assignType(subtype, subtypeResult.type)) { - // If this is the first result we're seeing or it's the first result - // without errors, select it as the match. - if (!matchingSubtypeResult || (matchingSubtypeResult.typeErrors && !subtypeResult.typeErrors)) { - matchingSubtype = subtype; - matchingSubtypeResult = subtypeResult; + if (subtypeResult && assignType(subtype, subtypeResult.type)) { + // If this is the first result we're seeing or it's the first result + // without errors, select it as the match. + if (!matchingSubtypeResult || (matchingSubtypeResult.typeErrors && !subtypeResult.typeErrors)) { + matchingSubtype = subtype; + matchingSubtypeResult = subtypeResult; + } } - } - }); + }, + /* sortSubtypes */ true + ); effectiveExpectedType = matchingSubtype; } @@ -13354,25 +13435,29 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions let matchingSubtype: Type | undefined; let matchingSubtypeResult: TypeResult | undefined; - doForEachSubtype(inferenceContext.expectedType, (subtype) => { - // Use shortcut if we've already found a match. - if (matchingSubtypeResult && !matchingSubtypeResult.typeErrors) { - return; - } + doForEachSubtype( + inferenceContext.expectedType, + (subtype) => { + // Use shortcut if we've already found a match. + if (matchingSubtypeResult && !matchingSubtypeResult.typeErrors) { + return; + } - const subtypeResult = useSpeculativeMode(node, () => { - return getTypeOfListOrSetWithContext(node, makeInferenceContext(subtype)); - }); + const subtypeResult = useSpeculativeMode(node, () => { + return getTypeOfListOrSetWithContext(node, makeInferenceContext(subtype)); + }); - if (subtypeResult && assignType(subtype, subtypeResult.type)) { - // If this is the first result we're seeing or it's the first result - // without errors, select it as the match. - if (!matchingSubtypeResult || (matchingSubtypeResult.typeErrors && !subtypeResult.typeErrors)) { - matchingSubtype = subtype; - matchingSubtypeResult = subtypeResult; + if (subtypeResult && assignType(subtype, subtypeResult.type)) { + // If this is the first result we're seeing or it's the first result + // without errors, select it as the match. + if (!matchingSubtypeResult || (matchingSubtypeResult.typeErrors && !subtypeResult.typeErrors)) { + matchingSubtype = subtype; + matchingSubtypeResult = subtypeResult; + } } - } - }); + }, + /* sortSubtypes */ true + ); effectiveExpectedType = matchingSubtype; } @@ -15090,13 +15175,15 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions return convertToInstance(typeVar) as TypeVarType; }); + const typeAliasScopeId = ParseTreeUtils.getScopeIdForNode(name); + // Validate the default types for all type parameters. typeParameters.forEach((typeParam, index) => { let bestErrorNode = errorNode; if (typeParamNodes && index < typeParamNodes.length) { bestErrorNode = typeParamNodes[index].defaultExpression ?? typeParamNodes[index].name; } - validateTypeParameterDefault(bestErrorNode, typeParam, typeParameters!.slice(0, index)); + validateTypeParameterDefault(bestErrorNode, typeParam, typeParameters!.slice(0, index), typeAliasScopeId); }); // Verify that we have at most one variadic type variable. @@ -15111,7 +15198,6 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } const fileInfo = AnalyzerNodeInfo.getFileInfo(name); - const typeAliasScopeId = ParseTreeUtils.getScopeIdForNode(name); const boundTypeVars = typeParameters.filter( (typeVar) => typeVar.scopeId !== typeAliasScopeId && typeVar.scopeType === TypeVarScopeType.Class @@ -15863,13 +15949,6 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions // a TypedDict, it is considered a TypedDict. if (ClassType.isBuiltIn(argType, 'TypedDict') || ClassType.isTypedDictClass(argType)) { classType.details.flags |= ClassTypeFlags.TypedDictClass; - } else if (ClassType.isTypedDictClass(classType) && !ClassType.isTypedDictClass(argType)) { - // Exempt Generic from this test. As of Python 3.11, generic TypedDict - // classes are supported. - if (!isInstantiableClass(argType) || !ClassType.isBuiltIn(argType, 'Generic')) { - // TypedDict classes must derive only from other TypedDict classes. - addError(Localizer.Diagnostic.typedDictBaseClass(), arg); - } } // Validate that the class isn't deriving from itself, creating a @@ -16112,7 +16191,8 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions validateTypeParameterDefault( bestErrorNode, typeParam, - classType.details.typeParameters.slice(0, index) + classType.details.typeParameters.slice(0, index), + classType.details.typeVarScopeId! ); }); @@ -16312,6 +16392,27 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions // Synthesize TypedDict methods. if (ClassType.isTypedDictClass(classType)) { + // TypedDict classes must derive only from other TypedDict classes. + let foundInvalidBaseClass = false; + const diag = new DiagnosticAddendum(); + + classType.details.baseClasses.forEach((baseClass) => { + if ( + isClass(baseClass) && + !ClassType.isTypedDictClass(baseClass) && + !ClassType.isBuiltIn(baseClass, ['_TypedDict', 'Generic']) + ) { + foundInvalidBaseClass = true; + diag.addMessage( + Localizer.DiagnosticAddendum.typedDictBaseClass().format({ type: baseClass.details.name }) + ); + } + }); + + if (foundInvalidBaseClass) { + addError(Localizer.Diagnostic.typedDictBaseClass() + diag.getString(), node.name); + } + synthesizeTypedDictClassMethods( evaluatorInterface, node, @@ -16336,7 +16437,10 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions let skipSynthesizeHash = false; const hashSymbol = lookUpClassMember(classType, '__hash__', ClassMemberLookupFlags.SkipBaseClasses); - if (hashSymbol) { + + // If there is a hash symbol defined in the class (i.e. one that we didn't + // synthesize above), then we shouldn't synthesize a new one for the dataclass. + if (hashSymbol && !hashSymbol.symbol.getSynthesizedType()) { skipSynthesizeHash = true; } @@ -16404,14 +16508,18 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions function validateTypeParameterDefault( errorNode: ExpressionNode, typeParam: TypeVarType, - otherLiveTypeParams: TypeVarType[] + otherLiveTypeParams: TypeVarType[], + scopeId: TypeVarScopeId ) { if ( !typeParam.details.defaultType && !typeParam.details.isSynthesized && !typeParam.details.isSynthesizedSelf ) { - const typeVarWithDefault = otherLiveTypeParams.find((param) => param.details.defaultType); + const typeVarWithDefault = otherLiveTypeParams.find( + (param) => param.details.defaultType && param.scopeId === scopeId + ); + if (typeVarWithDefault) { addDiagnostic( AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, @@ -16836,21 +16944,97 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } function getTypeOfFunction(node: FunctionNode): FunctionTypeResult | undefined { - const fileInfo = AnalyzerNodeInfo.getFileInfo(node); - - // Is this type already cached? - const cachedFunctionType = readTypeCache(node.name, EvaluatorFlags.None) as FunctionType; + // Is this predecorated function type cached? + let functionType = readTypeCache(node.name, EvaluatorFlags.None); - if (cachedFunctionType) { - if (!isFunction(cachedFunctionType)) { + if (functionType) { + if (!isFunction(functionType)) { // This can happen in certain rare circumstances where the // function declaration falls within an unreachable code block. return undefined; } - return { - functionType: cachedFunctionType, - decoratedType: readTypeCache(node, EvaluatorFlags.None) || UnknownType.create(), - }; + } else { + functionType = getTypeOfFunctionPredecorated(node); + } + + // Is the decorated function type cached? + let decoratedType = readTypeCache(node, EvaluatorFlags.None); + if (decoratedType) { + return { functionType, decoratedType }; + } + + // Populate the cache with a temporary value to handle recursion. + writeTypeCache(node, { type: functionType }, /* flags */ undefined); + + // If it's an async function, wrap the return type in an Awaitable or Generator. + // Set the "partially evaluated" flag around this logic to detect recursion. + functionType.details.flags |= FunctionTypeFlags.PartiallyEvaluated; + const preDecoratedType = node.isAsync ? createAsyncFunction(node, functionType) : functionType; + functionType.details.flags &= ~FunctionTypeFlags.PartiallyEvaluated; + + // Apply all of the decorators in reverse order. + decoratedType = preDecoratedType; + let foundUnknown = false; + for (let i = node.decorators.length - 1; i >= 0; i--) { + const decorator = node.decorators[i]; + + const newDecoratedType = applyFunctionDecorator( + evaluatorInterface, + decoratedType, + functionType, + decorator, + node + ); + + const unknownOrAny = containsAnyOrUnknown(newDecoratedType, /* recurse */ false); + + if (unknownOrAny && isUnknown(unknownOrAny)) { + // Report this error only on the first unknown type. + if (!foundUnknown) { + const fileInfo = AnalyzerNodeInfo.getFileInfo(node); + + addDiagnostic( + fileInfo.diagnosticRuleSet.reportUntypedFunctionDecorator, + DiagnosticRule.reportUntypedFunctionDecorator, + Localizer.Diagnostic.functionDecoratorTypeUnknown(), + node.decorators[i].expression + ); + + foundUnknown = true; + } + } else { + // Apply the decorator only if the type is known. + decoratedType = newDecoratedType; + } + } + + // See if there are any overloads provided by previous function declarations. + if (isFunction(decoratedType)) { + if (FunctionType.isOverloaded(decoratedType)) { + // Mark all the parameters as accessed. + node.parameters.forEach((param) => { + markParamAccessed(param); + }); + } + + decoratedType = addOverloadsToFunctionType(evaluatorInterface, node, decoratedType); + } + + writeTypeCache(node, { type: decoratedType }, EvaluatorFlags.None); + + return { functionType, decoratedType }; + } + + // Evaluates the type of a "def" statement without applying an async + // modifier or any decorators. + function getTypeOfFunctionPredecorated(node: FunctionNode): FunctionType { + const fileInfo = AnalyzerNodeInfo.getFileInfo(node); + + // Is this type already cached? + const cachedFunctionType = readTypeCache(node.name, EvaluatorFlags.None); + + if (cachedFunctionType && isFunction(cachedFunctionType)) { + return cachedFunctionType; } let functionDecl: FunctionDeclaration | undefined; @@ -16864,11 +17048,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions const containingClassNode = ParseTreeUtils.getEnclosingClass(node, /* stopAtFunction */ true); let containingClassType: ClassType | undefined; if (containingClassNode) { - const classInfo = getTypeOfClass(containingClassNode); - if (!classInfo) { - return undefined; - } - containingClassType = classInfo.classType; + containingClassType = getTypeOfClass(containingClassNode)?.classType; } let functionFlags = getFunctionFlagsFromDecorators(evaluatorInterface, node, !!containingClassNode); @@ -16911,14 +17091,13 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions functionType.details.declaration = functionDecl; - // Allow recursion by registering the partially-constructed - // function type. + // Allow recursion by caching and registering the partially-constructed function type. const scope = ScopeUtils.getScopeForNode(node); const functionSymbol = scope?.lookUpSymbolRecursive(node.name.value); if (functionDecl && functionSymbol) { setSymbolResolutionPartialType(functionSymbol.symbol, functionDecl, functionType); } - writeTypeCache(node, { type: functionType }, /* flags */ undefined); + writeTypeCache(node.name, { type: functionType }, /* flags */ undefined); // Is this an "__init__" method within a pseudo-generic class? If so, @@ -16967,15 +17146,6 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions functionType.details.typeParameters = typeParametersSeen; } - const markParamAccessed = (param: ParameterNode) => { - if (param.name) { - const symbolWithScope = lookUpSymbolRecursive(param.name, param.name.value, /* honorCodeFlow */ false); - if (symbolWithScope) { - setSymbolAccessed(fileInfo, symbolWithScope.symbol, param.name); - } - } - }; - let paramsArePositionOnly = true; const isFirstParamClsOrSelf = containingClassType && @@ -17254,65 +17424,31 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions const typeParamNode = node.typeParameters.parameters[index]; bestErrorNode = typeParamNode.defaultExpression ?? typeParamNode.name; } - validateTypeParameterDefault(bestErrorNode, typeParam, functionType.details.typeParameters.slice(0, index)); - }); - // If it's an async function, wrap the return type in an Awaitable or Generator. - const preDecoratedType = node.isAsync ? createAsyncFunction(node, functionType) : functionType; + validateTypeParameterDefault( + bestErrorNode, + typeParam, + functionType.details.typeParameters.slice(0, index), + functionType.details.typeVarScopeId! + ); + }); // Clear the "partially evaluated" flag to indicate that the functionType // is fully evaluated. functionType.details.flags &= ~FunctionTypeFlags.PartiallyEvaluated; - // Apply all of the decorators in reverse order. - let decoratedType: Type = preDecoratedType; - let foundUnknown = false; - for (let i = node.decorators.length - 1; i >= 0; i--) { - const decorator = node.decorators[i]; - - const newDecoratedType = applyFunctionDecorator( - evaluatorInterface, - decoratedType, - functionType, - decorator, - node - ); - const unknownOrAny = containsAnyOrUnknown(newDecoratedType, /* recurse */ false); - - if (unknownOrAny && isUnknown(unknownOrAny)) { - // Report this error only on the first unknown type. - if (!foundUnknown) { - addDiagnostic( - fileInfo.diagnosticRuleSet.reportUntypedFunctionDecorator, - DiagnosticRule.reportUntypedFunctionDecorator, - Localizer.Diagnostic.functionDecoratorTypeUnknown(), - node.decorators[i].expression - ); + writeTypeCache(node.name, { type: functionType }, EvaluatorFlags.None); - foundUnknown = true; - } - } else { - // Apply the decorator only if the type is known. - decoratedType = newDecoratedType; - } - } + return functionType; + } - // See if there are any overloads provided by previous function declarations. - if (isFunction(decoratedType)) { - if (FunctionType.isOverloaded(decoratedType)) { - // Mark all the parameters as accessed. - node.parameters.forEach((param) => { - markParamAccessed(param); - }); + function markParamAccessed(param: ParameterNode) { + if (param.name) { + const symbolWithScope = lookUpSymbolRecursive(param.name, param.name.value, /* honorCodeFlow */ false); + if (symbolWithScope) { + setSymbolAccessed(AnalyzerNodeInfo.getFileInfo(param), symbolWithScope.symbol, param.name); } - - decoratedType = addOverloadsToFunctionType(evaluatorInterface, node, decoratedType); } - - writeTypeCache(node.name, { type: functionType }, EvaluatorFlags.None); - writeTypeCache(node, { type: decoratedType }, EvaluatorFlags.None); - - return { functionType, decoratedType }; } // If the declared return type of a function contains type variables that @@ -20394,28 +20530,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions if (resolvedDecl.type === DeclarationType.Alias) { // Build a module type that corresponds to the declaration and // its associated loader actions. - let moduleName = resolvedDecl.moduleName; - if (decl.type === DeclarationType.Alias) { - if (decl.symbolName) { - moduleName += '.' + decl.symbolName; - } - - // If the module name is relative to the current file, use that - // file's module name as a reference. - if (moduleName.startsWith('.')) { - const fileInfo = AnalyzerNodeInfo.getFileInfo(decl.node); - const nameParts = fileInfo.moduleName.split('.'); - moduleName = moduleName.substr(1); - - while (moduleName.startsWith('.') && nameParts.length > 0) { - moduleName = moduleName.substr(1); - nameParts.pop(); - } - - moduleName = nameParts.join('.') + '.' + moduleName; - } - } - const moduleType = ModuleType.create(moduleName, resolvedDecl.path); + const moduleType = ModuleType.create(resolvedDecl.moduleName, resolvedDecl.path); if (resolvedDecl.symbolName && resolvedDecl.submoduleFallback) { return applyLoaderActionsToModuleType(moduleType, resolvedDecl.submoduleFallback, importLookup); } else { @@ -20691,6 +20806,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions isIncomplete, includesVariableDecl: typedDecls.some((decl) => decl.type === DeclarationType.Variable), includesIllegalTypeAliasDecl: !typedDecls.every((decl) => isPossibleTypeAliasDeclaration(decl)), + includesSpeculativeResult: false, isRecursiveDefinition: !declaredType, }; @@ -20715,12 +20831,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } // Infer the type. - const typesToCombine: Type[] = []; const decls = symbol.getDeclarations(); - let isIncomplete = false; - let sawPendingEvaluation = false; - let includesVariableDecl = false; - let includesSpeculativeResult = false; let declIndexToConsider: number | undefined; @@ -20731,6 +20842,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions isIncomplete: false, includesVariableDecl: false, includesIllegalTypeAliasDecl: !decls.every((decl) => isPossibleTypeAliasDeclaration(decl)), + includesSpeculativeResult: false, isRecursiveDefinition: false, }; @@ -20761,23 +20873,28 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } } + // Determine which declarations to use for inference. + const declsToConsider: Declaration[] = []; + let sawExplicitTypeAlias = false; decls.forEach((decl, index) => { - let considerDecl = declIndexToConsider === undefined || index === declIndexToConsider; + if (declIndexToConsider !== undefined && declIndexToConsider !== index) { + return; + } // If we have already seen an explicit type alias, do not consider // additional decls. This can happen if multiple TypeAlias declarations // are provided -- normally an error, but it can happen in stdlib stubs // if the user sets the pythonPlatform to "All". if (sawExplicitTypeAlias) { - considerDecl = false; + return; } // If the symbol is explicitly marked as a ClassVar, consider only the // declarations that assign to it from within the class body, not through // a member access expression. if (symbol.isClassVar() && decl.type === DeclarationType.Variable && decl.isDefinedByMemberAccess) { - considerDecl = false; + return; } if (usageNode !== undefined) { @@ -20787,109 +20904,142 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions const declScope = ParseTreeUtils.getExecutionScopeNode(decl.node); if (usageScope === declScope) { if (!isFlowPathBetweenNodes(decl.node, usageNode)) { - considerDecl = false; + return; } } } } - if (considerDecl) { - const resolvedDecl = - resolveAliasDeclaration(decl, /* resolveLocalNames */ true, { - allowExternallyHiddenAccess: AnalyzerNodeInfo.getFileInfo(decl.node).isStubFile, - }) ?? decl; + const resolvedDecl = + resolveAliasDeclaration(decl, /* resolveLocalNames */ true, { + allowExternallyHiddenAccess: AnalyzerNodeInfo.getFileInfo(decl.node).isStubFile, + }) ?? decl; - const isExplicitTypeAlias = isExplicitTypeAliasDeclaration(resolvedDecl); - const isTypeAlias = isExplicitTypeAlias || isPossibleTypeAliasOrTypedDict(resolvedDecl); + const isExplicitTypeAlias = isExplicitTypeAliasDeclaration(resolvedDecl); + const isTypeAlias = isExplicitTypeAlias || isPossibleTypeAliasOrTypedDict(resolvedDecl); - if (isExplicitTypeAlias) { - sawExplicitTypeAlias = true; - } + if (isExplicitTypeAlias) { + sawExplicitTypeAlias = true; + } - // If this is a type alias, evaluate it outside of the recursive symbol - // resolution check so we can evaluate the full assignment statement. - if ( - isTypeAlias && - resolvedDecl.type === DeclarationType.Variable && - resolvedDecl.inferredTypeSource?.parent?.nodeType === ParseNodeType.Assignment - ) { - evaluateTypesForAssignmentStatement(resolvedDecl.inferredTypeSource.parent); - } + // If this is a type alias, evaluate it outside of the recursive symbol + // resolution check so we can evaluate the full assignment statement. + if ( + isTypeAlias && + resolvedDecl.type === DeclarationType.Variable && + resolvedDecl.inferredTypeSource?.parent?.nodeType === ParseNodeType.Assignment + ) { + evaluateTypesForAssignmentStatement(resolvedDecl.inferredTypeSource.parent); + } - if (pushSymbolResolution(symbol, decl)) { - try { - let type = getInferredTypeOfDeclaration(symbol, decl); + declsToConsider.push(resolvedDecl); + }); - if (!popSymbolResolution(symbol)) { - isIncomplete = true; - } + const evaluationAttempts = (cacheEntries?.get(effectiveTypeCacheKey)?.evaluationAttempts ?? 0) + 1; + const result = getTypeOfSymbolForDecls(symbol, declsToConsider, evaluationAttempts); - if (type) { - if (resolvedDecl.type === DeclarationType.Variable) { - // Exempt typing.pyi, which uses variables to define some - // special forms like Any. - const fileInfo = AnalyzerNodeInfo.getFileInfo(resolvedDecl.node); - if (!fileInfo.isTypingStubFile) { - includesVariableDecl = true; - } + // Add the result to the effective type cache if it doesn't include speculative results. + if (!result.includesSpeculativeResult) { + addToEffectiveTypeCache(result); + } - let isConstant = false; - if (resolvedDecl.type === DeclarationType.Variable) { - if (resolvedDecl.isConstant || isFinalVariableDeclaration(resolvedDecl)) { - isConstant = true; - } - } + return result; - // Treat enum values declared within an enum class as though they are const even - // though they may not be named as such. - if ( - isClassInstance(type) && - ClassType.isEnumClass(type) && - isDeclInEnumClass(evaluatorInterface, resolvedDecl) - ) { + function addToEffectiveTypeCache(result: EffectiveTypeResult) { + // Add the entry to the cache so we don't need to compute it next time. + if (!cacheEntries) { + cacheEntries = new Map(); + effectiveTypeCache.set(symbol.id, cacheEntries); + } + + cacheEntries.set(effectiveTypeCacheKey, result); + } + } + + // Returns the type of a symbol based on a subset of its declarations. + function getTypeOfSymbolForDecls( + symbol: Symbol, + decls: Declaration[], + evaluationAttempts: number + ): EffectiveTypeResult { + const typesToCombine: Type[] = []; + let isIncomplete = false; + let sawPendingEvaluation = false; + let includesVariableDecl = false; + let includesSpeculativeResult = false; + + decls.forEach((decl) => { + if (pushSymbolResolution(symbol, decl)) { + try { + let type = getInferredTypeOfDeclaration(symbol, decl); + + if (!popSymbolResolution(symbol)) { + isIncomplete = true; + } + + if (type) { + if (decl.type === DeclarationType.Variable) { + // Exempt typing.pyi, which uses variables to define some + // special forms like Any. + const fileInfo = AnalyzerNodeInfo.getFileInfo(decl.node); + if (!fileInfo.isTypingStubFile) { + includesVariableDecl = true; + } + + let isConstant = false; + if (decl.type === DeclarationType.Variable) { + if (decl.isConstant || isFinalVariableDeclaration(decl)) { isConstant = true; } + } - // If the symbol is constant, we can retain the literal - // value. Otherwise, strip literal values to widen the type. - if (TypeBase.isInstance(type) && !isExplicitTypeAlias && !isConstant) { - type = stripLiteralValue(type); - } + // Treat enum values declared within an enum class as though they are const even + // though they may not be named as such. + if ( + isClassInstance(type) && + ClassType.isEnumClass(type) && + isDeclInEnumClass(evaluatorInterface, decl) + ) { + isConstant = true; } - typesToCombine.push(type); - if (isSpeculativeModeInUse(decl.node)) { - includesSpeculativeResult = true; + // If the symbol is constant, we can retain the literal + // value. Otherwise, strip literal values to widen the type. + if (TypeBase.isInstance(type) && !isConstant && !isExplicitTypeAliasDeclaration(decl)) { + type = stripLiteralValue(type); } - } else { - isIncomplete = true; } - } catch (e: any) { - // Clean up the stack before rethrowing. - popSymbolResolution(symbol); - throw e; - } - } else { - if (resolvedDecl.type === DeclarationType.Class) { - const classTypeInfo = getTypeOfClass(resolvedDecl.node); - if (classTypeInfo?.decoratedType) { - typesToCombine.push(classTypeInfo.decoratedType); + + typesToCombine.push(type); + + if (isSpeculativeModeInUse(decl.node)) { + includesSpeculativeResult = true; } + } else { + isIncomplete = true; + } + } catch (e: any) { + // Clean up the stack before rethrowing. + popSymbolResolution(symbol); + throw e; + } + } else { + if (decl.type === DeclarationType.Class) { + const classTypeInfo = getTypeOfClass(decl.node); + if (classTypeInfo?.decoratedType) { + typesToCombine.push(classTypeInfo.decoratedType); } + } - isIncomplete = true; + isIncomplete = true; - // Note that at least one decl could not be evaluated because - // it was already in the process of being evaluated. - sawPendingEvaluation = true; - } + // Note that at least one decl could not be evaluated because + // it was already in the process of being evaluated. + sawPendingEvaluation = true; } }); - // How many times have we already attempted to evaluate this declaration already? - const evaluationAttempts = (cacheEntries?.get(effectiveTypeCacheKey)?.evaluationAttempts ?? 0) + 1; - - let resultType: Type; + let type: Type; if (typesToCombine.length > 0) { // Ignore the pending evaluation flag if we've already attempted the @@ -20897,35 +21047,20 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions // cyclical dependency that cannot be broken. isIncomplete = sawPendingEvaluation && evaluationAttempts < maxEffectiveTypeEvaluationAttempts; - resultType = combineTypes(typesToCombine); + type = combineTypes(typesToCombine); } else { - resultType = UnboundType.create(); + type = UnboundType.create(); } - const result: EffectiveTypeResult = { - type: resultType, + return { + type, isIncomplete, includesVariableDecl, includesIllegalTypeAliasDecl: !decls.every((decl) => isPossibleTypeAliasDeclaration(decl)), + includesSpeculativeResult, isRecursiveDefinition: false, evaluationAttempts, }; - - if (!includesSpeculativeResult) { - addToEffectiveTypeCache(result); - } - - return result; - - function addToEffectiveTypeCache(result: EffectiveTypeResult) { - // Add the entry to the cache so we don't need to compute it next time. - if (!cacheEntries) { - cacheEntries = new Map(); - effectiveTypeCache.set(symbol.id, cacheEntries); - } - - cacheEntries.set(effectiveTypeCacheKey, result); - } } // If a declaration has an explicit type (e.g. a variable with an annotation), @@ -21917,7 +22052,10 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions return assignTypeArguments( destType, curSrcType, - diag, + // Don't emit a diag addendum if we're in an invariant context. It's + // sufficient to simply indicate that the types are not the same + // in this case. Adding more information is unnecessary and confusing. + (flags & AssignTypeFlags.EnforceInvariance) === 0 ? diag : undefined, destTypeVarContext, srcTypeVarContext, flags, @@ -22549,9 +22687,12 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions if (isInstantiableClass(destType)) { if (isInstantiableClass(expandedSrcType)) { - // PEP 544 says that if the dest type is a Type[Proto] class, + // PEP 544 says that if the dest type is a type[Proto] class, // the source must be a "concrete" (non-protocol) class. - if (ClassType.isProtocolClass(destType)) { + if ( + ClassType.isProtocolClass(destType) && + (flags & AssignTypeFlags.IgnoreProtocolAssignmentCheck) === 0 + ) { if ( ClassType.isProtocolClass(expandedSrcType) && isInstantiableClass(srcType) && @@ -23092,7 +23233,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions return remainingDestSubtypes.every((destSubtype) => isTypeSubsumedByOtherType( destSubtype, - destType.subtypes, + destType, /* allowAnyToSubsume */ true, recursionCount ) @@ -23196,7 +23337,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions // in the same union. If so, we can ignore this. const isSubtypeSubsumed = isTypeSubsumedByOtherType( subtype, - srcType.subtypes, + srcType, /* allowAnyToSubsume */ false, recursionCount ); @@ -23230,9 +23371,10 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions } // Determines whether a type is "subsumed by" (i.e. is a proper subtype of) one - // of the other types in a list. - function isTypeSubsumedByOtherType(type: Type, otherTypes: Type[], allowAnyToSubsume: boolean, recursionCount = 0) { + // of the other type. + function isTypeSubsumedByOtherType(type: Type, otherType: Type, allowAnyToSubsume: boolean, recursionCount = 0) { const concreteType = makeTopLevelTypeVarsConcrete(type); + const otherTypes = isUnion(otherType) ? otherType.subtypes : [otherType]; for (const otherType of otherTypes) { if (isTypeSame(otherType, type)) { @@ -24381,6 +24523,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions effectiveSrcType.details.flags | FunctionTypeFlags.SynthesizedMethod, effectiveSrcType.details.docString ); + remainingFunction.details.deprecatedMessage = effectiveSrcType.details.deprecatedMessage; remainingFunction.details.typeVarScopeId = effectiveSrcType.details.typeVarScopeId; remainingFunction.details.constructorTypeVarScopeId = effectiveSrcType.details.constructorTypeVarScopeId; @@ -25832,6 +25975,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions runWithCancellationToken, getType, getTypeResult, + getTypeResultForDecorator, getCachedType, getTypeOfExpression, getTypeOfAnnotation, @@ -25855,7 +25999,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions validateInitSubclassArgs, isAfterNodeReachable, isNodeReachable, - isAsymmetricDescriptorAssignment: isAsymmetricAccessorAssignment, + isAsymmetricAccessorAssignment, suppressDiagnostics, getDeclarationsForStringNode, getDeclarationsForNameNode, @@ -25869,6 +26013,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions markNamesAccessed, makeTopLevelTypeVarsConcrete, mapSubtypesExpandTypeVars, + isTypeSubsumedByOtherType, lookUpSymbolRecursive, getDeclaredTypeOfSymbol, getEffectiveTypeOfSymbol, @@ -25921,7 +26066,7 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions disposeEvaluator, useSpeculativeMode, isSpeculativeModeInUse, - setTypeForNode, + setTypeResultForNode, checkForCancellation, printControlFlowGraph, printTypeVarContext, diff --git a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts index e1e302465..b3fb60427 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts @@ -19,6 +19,7 @@ import { CallNode, CaseNode, ClassNode, + DecoratorNode, ExpressionNode, FunctionNode, MatchNode, @@ -267,6 +268,7 @@ export interface EffectiveTypeResult { isIncomplete: boolean; includesVariableDecl: boolean; includesIllegalTypeAliasDecl: boolean; + includesSpeculativeResult: boolean; isRecursiveDefinition: boolean; evaluationAttempts?: number; } @@ -409,37 +411,41 @@ export const enum MemberAccessFlags { // the class are considered. AccessClassMembersOnly = 1 << 0, + // Consider only instance members, not members that could be + // class members. + AccessInstanceMembersOnly = 1 << 1, + // By default, members of base classes are also searched. // Set this flag to consider only the specified class' members. - SkipBaseClasses = 1 << 1, + SkipBaseClasses = 1 << 2, // Do not include the "object" base class in the search. - SkipObjectBaseClass = 1 << 2, + SkipObjectBaseClass = 1 << 3, // Consider writes to symbols flagged as ClassVars as an error. - DisallowClassVarWrites = 1 << 3, + DisallowClassVarWrites = 1 << 4, // Normally __new__ is treated as a static method, but when // it is invoked implicitly through a constructor call, it // acts like a class method instead. - TreatConstructorAsClassMethod = 1 << 4, + TreatConstructorAsClassMethod = 1 << 5, // By default, class member lookups start with the class itself // and fall back on the metaclass if it's not found. This option // skips the first check. - ConsiderMetaclassOnly = 1 << 5, + ConsiderMetaclassOnly = 1 << 6, // If an attribute cannot be found when looking for instance // members, normally an attribute access override method // (__getattr__, etc.) may provide the missing attribute type. // This disables this check. - SkipAttributeAccessOverride = 1 << 6, + SkipAttributeAccessOverride = 1 << 7, // Do not include the class itself, only base classes. - SkipOriginalClass = 1 << 7, + SkipOriginalClass = 1 << 8, // Do not include the "type" base class in the search. - SkipTypeBaseClass = 1 << 8, + SkipTypeBaseClass = 1 << 9, } export interface ValidateTypeArgsOptions { @@ -455,6 +461,7 @@ export interface TypeEvaluator { getType: (node: ExpressionNode) => Type | undefined; getTypeResult: (node: ExpressionNode) => TypeResult | undefined; + getTypeResultForDecorator: (node: DecoratorNode) => TypeResult | undefined; getCachedType: (node: ExpressionNode) => Type | undefined; getTypeOfExpression: (node: ExpressionNode, flags?: EvaluatorFlags, context?: InferenceContext) => TypeResult; getTypeOfAnnotation: (node: ExpressionNode, options?: AnnotationTypeOptions) => Type; @@ -488,7 +495,7 @@ export interface TypeEvaluator { isAfterNodeReachable: (node: ParseNode) => boolean; isNodeReachable: (node: ParseNode, sourceNode?: ParseNode | undefined) => boolean; - isAsymmetricDescriptorAssignment: (node: ParseNode) => boolean; + isAsymmetricAccessorAssignment: (node: ParseNode) => boolean; suppressDiagnostics: (node: ParseNode, callback: () => void) => void; getDeclarationsForStringNode: (node: StringNode) => Declaration[] | undefined; @@ -523,6 +530,7 @@ export interface TypeEvaluator { conditionFilter: TypeCondition[] | undefined, callback: (expandedSubtype: Type, unexpandedSubtype: Type) => Type | undefined ) => Type; + isTypeSubsumedByOtherType: (type: Type, otherType: Type, allowAnyToSubsume: boolean) => boolean; lookUpSymbolRecursive: (node: ParseNode, name: string, honorCodeFlow: boolean) => SymbolWithScope | undefined; getDeclaredTypeOfSymbol: (symbol: Symbol) => DeclaredSymbolTypeInfo; getEffectiveTypeOfSymbol: (symbol: Symbol) => Type; @@ -671,7 +679,7 @@ export interface TypeEvaluator { disposeEvaluator: () => void; useSpeculativeMode: (speculativeNode: ParseNode | undefined, callback: () => T) => T; isSpeculativeModeInUse: (node: ParseNode | undefined) => boolean; - setTypeForNode: (node: ParseNode, type?: Type, flags?: EvaluatorFlags) => void; + setTypeResultForNode: (node: ParseNode, typeResult: TypeResult, flags?: EvaluatorFlags) => void; checkForCancellation: () => void; printControlFlowGraph: ( diff --git a/packages/pyright-internal/src/analyzer/typeGuards.ts b/packages/pyright-internal/src/analyzer/typeGuards.ts index 4ea1004be..0b2ac4749 100644 --- a/packages/pyright-internal/src/analyzer/typeGuards.ts +++ b/packages/pyright-internal/src/analyzer/typeGuards.ts @@ -49,9 +49,11 @@ import { isSameWithoutLiteralValue, isTypeSame, isTypeVar, + isUnpackedVariadicTypeVar, maxTypeRecursionCount, NoneType, OverloadedFunctionType, + TupleTypeArgument, Type, TypeBase, TypeCategory, @@ -83,6 +85,7 @@ import { lookUpClassMember, lookUpObjectMember, mapSubtypes, + specializeTupleClass, transformPossibleRecursiveTypeAlias, } from './typeUtils'; import { TypeVarContext } from './typeVarContext'; @@ -1342,7 +1345,7 @@ function narrowTypeForIsInstance( foundSuperclass = true; } - // Normally, a type should never be both a subclass or a superclass. + // Normally, a type should never be both a subclass and a superclass. // This can happen if either of the class types derives from a // class whose type is unknown (e.g. an import failed). We'll // note this case specially so we don't do any narrowing, which @@ -1368,7 +1371,7 @@ function narrowTypeForIsInstance( /* diag */ undefined, /* destTypeVarContext */ undefined, /* srcTypeVarContext */ undefined, - AssignTypeFlags.IgnoreTypeVarScope + AssignTypeFlags.IgnoreTypeVarScope | AssignTypeFlags.IgnoreProtocolAssignmentCheck ) ) { // If the variable type is a superclass of the isinstance @@ -1572,7 +1575,16 @@ function narrowTypeForIsInstance( for (const filterType of classTypeList) { const concreteFilterType = evaluator.makeTopLevelTypeVarsConcrete(filterType); - if (evaluator.assignType(varType, convertToInstance(concreteFilterType))) { + if ( + evaluator.assignType( + varType, + convertToInstance(concreteFilterType), + /* diag */ undefined, + /* destTypeVarContext */ undefined, + /* srcTypeVarContext */ undefined, + AssignTypeFlags.IgnoreTypeVarScope + ) + ) { // If the filter type is a Callable, use the original type. If the // filter type is a callback protocol, use the filter type. if (isFunction(filterType)) { @@ -1754,14 +1766,48 @@ function narrowTypeForTupleLength( if ( !isClassInstance(concreteSubtype) || !isTupleClass(concreteSubtype) || - isUnboundedTupleClass(concreteSubtype) || !concreteSubtype.tupleTypeArguments ) { return subtype; } - const tupleLengthMatches = concreteSubtype.tupleTypeArguments.length === lengthValue; - return tupleLengthMatches === isPositiveTest ? subtype : undefined; + // If the tuple contains a variadic TypeVar, we can't narrow it. + if (concreteSubtype.tupleTypeArguments.some((typeArg) => isUnpackedVariadicTypeVar(typeArg.type))) { + return subtype; + } + + // If the tuple contains no unbounded elements, then we know its length exactly. + if (!concreteSubtype.tupleTypeArguments.some((typeArg) => typeArg.isUnbounded)) { + const tupleLengthMatches = concreteSubtype.tupleTypeArguments.length === lengthValue; + return tupleLengthMatches === isPositiveTest ? subtype : undefined; + } + + // The tuple contains a "...". We'll expand this into as many elements as + // necessary to match the lengthValue. + const elementsToAdd = lengthValue - concreteSubtype.tupleTypeArguments.length + 1; + + // If the specified length is smaller than the minimum length of this tuple, + // we can rule it out for a positive test. + if (elementsToAdd < 0) { + return isPositiveTest ? undefined : subtype; + } + + if (!isPositiveTest) { + return subtype; + } + + const tupleTypeArgs: TupleTypeArgument[] = []; + concreteSubtype.tupleTypeArguments.forEach((typeArg) => { + if (!typeArg.isUnbounded) { + tupleTypeArgs.push(typeArg); + } else { + for (let i = 0; i < elementsToAdd; i++) { + tupleTypeArgs.push({ isUnbounded: false, type: typeArg.type }); + } + } + }); + + return specializeTupleClass(concreteSubtype, tupleTypeArgs); }); } @@ -2410,3 +2456,17 @@ function narrowTypeForCallable( } }); } + +export class Animal {} +export class Dog extends Animal {} + +export class Plant {} +export class Tree extends Plant {} + +export function func1(val: Animal) { + if (val instanceof Tree) { + console.log(val); + } else { + console.log(val); + } +} diff --git a/packages/pyright-internal/src/analyzer/typePrinter.ts b/packages/pyright-internal/src/analyzer/typePrinter.ts index d4ee0a481..8e159ed2c 100644 --- a/packages/pyright-internal/src/analyzer/typePrinter.ts +++ b/packages/pyright-internal/src/analyzer/typePrinter.ts @@ -675,10 +675,15 @@ function printTypeInternal( } if (type.details.isParamSpec) { + const paramSpecText = _getReadableTypeVarName( + type, + (printTypeFlags & PrintTypeFlags.PythonSyntax) !== 0 + ); + if (type.paramSpecAccess) { - return `${type.details.name}.${type.paramSpecAccess}`; + return `${paramSpecText}.${type.paramSpecAccess}`; } - return `${_getReadableTypeVarName(type, (printTypeFlags & PrintTypeFlags.PythonSyntax) !== 0)}`; + return paramSpecText; } let typeVarName = _getReadableTypeVarName(type, (printTypeFlags & PrintTypeFlags.PythonSyntax) !== 0); diff --git a/packages/pyright-internal/src/analyzer/typeUtils.ts b/packages/pyright-internal/src/analyzer/typeUtils.ts index f3b2c650a..47c6ffe30 100644 --- a/packages/pyright-internal/src/analyzer/typeUtils.ts +++ b/packages/pyright-internal/src/analyzer/typeUtils.ts @@ -111,13 +111,17 @@ export const enum ClassMemberLookupFlags { // If this flag is set, the instance variables are skipped. SkipInstanceVariables = 1 << 3, + // By default, both class and instance variables are searched. + // If this flag is set, the class variables are skipped. + SkipClassVariables = 1 << 4, + // By default, the first symbol is returned even if it has only // an inferred type associated with it. If this flag is set, // the search looks only for symbols with declared types. - DeclaredTypesOnly = 1 << 4, + DeclaredTypesOnly = 1 << 5, // Skip the 'type' base class in particular. - SkipTypeBaseClass = 1 << 5, + SkipTypeBaseClass = 1 << 6, } export const enum ClassIteratorFlags { @@ -194,6 +198,11 @@ export const enum AssignTypeFlags { // default type arguments (typically "Unknown"). This flag skips // this step. AllowUnspecifiedTypeArguments = 1 << 11, + + // PEP 544 says that if the dest type is a type[Proto] class, + // the source must be a "concrete" (non-protocol) class. This + // flag skips this check. + IgnoreProtocolAssignmentCheck = 1 << 12, } export interface ApplyTypeVarOptions { @@ -343,15 +352,17 @@ export function makeInferenceContext( // Calls a callback for each subtype and combines the results // into a final type. It performs no memory allocations if the // transformed type is the same as the original. -export function mapSubtypes(type: Type, callback: (type: Type) => Type | undefined): Type { +export function mapSubtypes(type: Type, callback: (type: Type) => Type | undefined, sortSubtypes = false): Type { if (isUnion(type)) { - for (let i = 0; i < type.subtypes.length; i++) { - const subtype = type.subtypes[i]; + const subtypes = sortSubtypes ? sortTypes(type.subtypes) : type.subtypes; + + for (let i = 0; i < subtypes.length; i++) { + const subtype = subtypes[i]; const transformedType = callback(subtype); // Avoid doing any memory allocations until a change is detected. if (subtype !== transformedType) { - const typesToCombine: Type[] = type.subtypes.slice(0, i); + const typesToCombine: Type[] = subtypes.slice(0, i); // Create a helper lambda that accumulates transformed subtypes. const accumulateSubtype = (newSubtype: Type | undefined) => { @@ -362,8 +373,8 @@ export function mapSubtypes(type: Type, callback: (type: Type) => Type | undefin accumulateSubtype(transformedType); - for (i++; i < type.subtypes.length; i++) { - accumulateSubtype(callback(type.subtypes[i])); + for (i++; i < subtypes.length; i++) { + accumulateSubtype(callback(subtypes[i])); } const newType = combineTypes(typesToCombine); @@ -394,7 +405,12 @@ export function sortTypes(types: Type[]): Type[] { }); } -function compareTypes(a: Type, b: Type): number { +function compareTypes(a: Type, b: Type, recursionCount = 0): number { + if (recursionCount > maxTypeRecursionCount) { + return 0; + } + recursionCount++; + if (a.category !== b.category) { return b.category - a.category; } @@ -502,7 +518,32 @@ function compareTypes(a: Type, b: Type): number { // Sort by class name. const aName = a.details.name; const bName = (b as ClassType).details.name; - return aName < bName ? -1 : aName === bName ? 0 : 1; + + if (aName < bName) { + return -1; + } else if (aName > bName) { + return 1; + } + + // Sort by type argument count. + const aTypeArgCount = a.typeArguments ? a.typeArguments.length : 0; + const bTypeArgCount = bClass.typeArguments ? bClass.typeArguments.length : 0; + + if (aTypeArgCount < bTypeArgCount) { + return -1; + } else if (aTypeArgCount > bTypeArgCount) { + return 1; + } + + // Sort by type argument. + for (let i = 0; i < aTypeArgCount; i++) { + const typeComparison = compareTypes(a.typeArguments![i], bClass.typeArguments![i], recursionCount); + if (typeComparison !== 0) { + return typeComparison; + } + } + + return 0; } case TypeCategory.Module: { @@ -1404,40 +1445,42 @@ export function* getClassMemberIterator( } // Next look at class members. - const symbol = memberFields.get(memberName); - if (symbol && symbol.isClassMember()) { - const hasDeclaredType = symbol.hasTypedDeclarations(); - if (!declaredTypesOnly || hasDeclaredType) { - let isInstanceMember = symbol.isInstanceMember(); - let isClassMember = true; - - // For data classes and typed dicts, variables that are declared - // within the class are treated as instance variables. This distinction - // is important in cases where a variable is a callable type because - // we don't want to bind it to the instance like we would for a - // class member. - const isDataclass = ClassType.isDataClass(specializedMroClass); - const isTypedDict = ClassType.isTypedDictClass(specializedMroClass); - if (hasDeclaredType && (isDataclass || isTypedDict)) { - const decls = symbol.getDeclarations(); - if (decls.length > 0 && decls[0].type === DeclarationType.Variable) { - isInstanceMember = true; - isClassMember = isDataclass; + if ((flags & ClassMemberLookupFlags.SkipClassVariables) === 0) { + const symbol = memberFields.get(memberName); + if (symbol && symbol.isClassMember()) { + const hasDeclaredType = symbol.hasTypedDeclarations(); + if (!declaredTypesOnly || hasDeclaredType) { + let isInstanceMember = symbol.isInstanceMember(); + let isClassMember = true; + + // For data classes and typed dicts, variables that are declared + // within the class are treated as instance variables. This distinction + // is important in cases where a variable is a callable type because + // we don't want to bind it to the instance like we would for a + // class member. + const isDataclass = ClassType.isDataClass(specializedMroClass); + const isTypedDict = ClassType.isTypedDictClass(specializedMroClass); + if (hasDeclaredType && (isDataclass || isTypedDict)) { + const decls = symbol.getDeclarations(); + if (decls.length > 0 && decls[0].type === DeclarationType.Variable) { + isInstanceMember = true; + isClassMember = isDataclass; + } } - } - const cm: ClassMember = { - symbol, - isInstanceMember, - isClassMember, - isClassVar: symbol.isClassVar(), - classType: specializedMroClass, - isTypeDeclared: hasDeclaredType, - skippedUndeclaredType, - }; - yield cm; - } else { - skippedUndeclaredType = true; + const cm: ClassMember = { + symbol, + isInstanceMember, + isClassMember, + isClassVar: symbol.isClassVar(), + classType: specializedMroClass, + isTypeDeclared: hasDeclaredType, + skippedUndeclaredType, + }; + yield cm; + } else { + skippedUndeclaredType = true; + } } } } @@ -1727,7 +1770,10 @@ export function specializeClassType(type: ClassType): ClassType { const typeParams = ClassType.getTypeParameters(type); typeParams.forEach((typeParam) => { - typeVarContext.setTypeVarType(typeParam, UnknownType.create()); + typeVarContext.setTypeVarType( + typeParam, + applySolvedTypeVars(typeParam.details.defaultType ?? UnknownType.create(), typeVarContext) + ); }); return applySolvedTypeVars(type, typeVarContext) as ClassType; @@ -3147,10 +3193,27 @@ class TypeVarTransformer { // _pendingTypeVarTransformations set. if (!this._isTypeVarScopePending(type.scopeId)) { if (type.details.isParamSpec) { - if (!type.paramSpecAccess) { - const paramSpecValue = this.transformParamSpec(type, recursionCount); - if (paramSpecValue) { - replacementType = convertParamSpecValueToType(paramSpecValue); + let paramSpecWithoutAccess = type; + + if (type.paramSpecAccess) { + paramSpecWithoutAccess = TypeVarType.cloneForParamSpecAccess(type, /* access */ undefined); + } + + const paramSpecValue = this.transformParamSpec(paramSpecWithoutAccess, recursionCount); + if (paramSpecValue) { + const paramSpecType = convertParamSpecValueToType(paramSpecValue); + + if (type.paramSpecAccess) { + if (isParamSpec(paramSpecType)) { + replacementType = TypeVarType.cloneForParamSpecAccess( + paramSpecType, + type.paramSpecAccess + ); + } else { + replacementType = UnknownType.create(); + } + } else { + replacementType = paramSpecType; } } } else { @@ -3768,19 +3831,6 @@ class ApplySolvedTypeVarsTransformer extends TypeVarTransformer { if (typeVar.scopeId && this._typeVarContext.hasSolveForScope(typeVar.scopeId)) { let replacement = signatureContext.getTypeVarType(typeVar, !!this._options.useNarrowBoundOnly); - // If the type is unknown, see if there's a known wide bound that we can use. - if ( - replacement && - isUnknown(replacement) && - !this._options.useNarrowBoundOnly && - this._options.unknownIfNotFound - ) { - const entry = signatureContext.getTypeVar(typeVar); - if (entry?.wideBound) { - replacement = entry?.wideBound; - } - } - // If there was no narrow bound but there is a wide bound that // contains literals or a TypeVar, we'll use the wide bound even if // "useNarrowBoundOnly" is specified. diff --git a/packages/pyright-internal/src/analyzer/typedDicts.ts b/packages/pyright-internal/src/analyzer/typedDicts.ts index f16062e12..475137035 100644 --- a/packages/pyright-internal/src/analyzer/typedDicts.ts +++ b/packages/pyright-internal/src/analyzer/typedDicts.ts @@ -127,7 +127,7 @@ export function createTypedDictType( ) { usingDictSyntax = true; - getTypedDictFieldsFromDictSyntax(evaluator, entriesArg.valueExpression, classFields); + getTypedDictFieldsFromDictSyntax(evaluator, entriesArg.valueExpression, classFields, /* isInline */ false); } else if (entriesArg.name) { const entrySet = new Set(); for (let i = 1; i < argList.length; i++) { @@ -222,7 +222,7 @@ export function createTypedDictTypeInlined( classType.details.baseClasses.push(typedDictClass); computeMroLinearization(classType); - getTypedDictFieldsFromDictSyntax(evaluator, dictNode, classType.details.fields); + getTypedDictFieldsFromDictSyntax(evaluator, dictNode, classType.details.fields, /* isInline */ true); synthesizeTypedDictClassMethods(evaluator, dictNode, classType, /* isClassFinal */ true); return classType; @@ -405,7 +405,7 @@ export function synthesizeTypedDictClassMethods( return getOverload; } - function createPopMethods(keyType: Type, valueType: Type) { + function createPopMethods(keyType: Type, valueType: Type, isEntryRequired: boolean) { const keyParam: FunctionParameter = { category: ParameterCategory.Simple, name: 'k', @@ -423,14 +423,28 @@ export function synthesizeTypedDictClassMethods( FunctionType.addParameter(popOverload2, keyParam); popOverload2.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(node); const defaultTypeVar = createDefaultTypeVar(popOverload2); + + let defaultParamType: Type; + let returnType: Type; + + if (isEntryRequired) { + // If the entry is required, the type of the default param doesn't matter + // because the type will always come from the value. + defaultParamType = AnyType.create(); + returnType = valueType; + } else { + defaultParamType = combineTypes([valueType, defaultTypeVar]); + returnType = defaultParamType; + } + FunctionType.addParameter(popOverload2, { category: ParameterCategory.Simple, name: 'default', hasDeclaredType: true, - type: defaultTypeVar, + type: defaultParamType, hasDefault: true, }); - popOverload2.details.declaredReturnType = combineTypes([valueType, defaultTypeVar]); + popOverload2.details.declaredReturnType = returnType; return [popOverload1, popOverload2]; } @@ -507,31 +521,19 @@ export function synthesizeTypedDictClassMethods( createGetMethod(nameLiteralType, entry.valueType, /* includeDefault */ false, entry.isRequired) ); - if (entry.isRequired) { - getOverloads.push( - createGetMethod( - nameLiteralType, - entry.valueType, - /* includeDefault */ true, - /* isEntryRequired */ true, - /* defaultTypeMatchesField */ true - ) - ); - } else { - getOverloads.push( - createGetMethod( - nameLiteralType, - entry.valueType, - /* includeDefault */ true, - /* isEntryRequired */ false, - /* defaultTypeMatchesField */ false - ) - ); - } + getOverloads.push( + createGetMethod( + nameLiteralType, + entry.valueType, + /* includeDefault */ true, + /* isEntryRequired */ entry.isRequired, + /* defaultTypeMatchesField */ entry.isRequired + ) + ); // Add a pop method if the entry is not required. if (!entry.isRequired && !entry.isReadOnly) { - appendArray(popOverloads, createPopMethods(nameLiteralType, entry.valueType)); + appendArray(popOverloads, createPopMethods(nameLiteralType, entry.valueType, entry.isRequired)); } if (!entry.isReadOnly) { @@ -664,7 +666,8 @@ export function getTypedDictMembersForClass(evaluator: TypeEvaluator, classType: function getTypedDictFieldsFromDictSyntax( evaluator: TypeEvaluator, entryDict: DictionaryNode, - classFields: SymbolTable + classFields: SymbolTable, + isInline: boolean ) { const entrySet = new Set(); const fileInfo = AnalyzerNodeInfo.getFileInfo(entryDict); @@ -700,7 +703,7 @@ function getTypedDictFieldsFromDictSyntax( node: entry.keyExpression, path: fileInfo.filePath, typeAnnotationNode: entry.valueExpression, - isRuntimeTypeExpression: true, + isRuntimeTypeExpression: !isInline, range: convertOffsetsToRange( entry.keyExpression.start, TextRange.getEnd(entry.keyExpression), @@ -716,7 +719,7 @@ function getTypedDictFieldsFromDictSyntax( // Set the type in the type cache for the dict node so it doesn't // get evaluated again. - evaluator.setTypeForNode(entryDict); + evaluator.setTypeResultForNode(entryDict, { type: UnknownType.create() }); } function getTypedDictMembersForClassRecursive( diff --git a/packages/pyright-internal/src/analyzer/types.ts b/packages/pyright-internal/src/analyzer/types.ts index 63d593958..239d1f28d 100644 --- a/packages/pyright-internal/src/analyzer/types.ts +++ b/packages/pyright-internal/src/analyzer/types.ts @@ -1632,10 +1632,14 @@ export namespace FunctionType { }), ]; - if (!newFunction.details.docString) { + if (newFunction.details.docString === undefined) { newFunction.details.docString = paramSpecValue.details.docString; } + if (newFunction.details.deprecatedMessage === undefined) { + newFunction.details.deprecatedMessage = paramSpecValue.details.deprecatedMessage; + } + newFunction.details.flags = (paramSpecValue.details.flags & (FunctionTypeFlags.ClassMethod | @@ -1715,6 +1719,17 @@ export namespace FunctionType { return newFunction; } + export function cloneWithDeprecatedMessage(type: FunctionType, deprecatedMessage?: string): FunctionType { + const newFunction = TypeBase.cloneType(type); + + // Make a shallow clone of the details. + newFunction.details = { ...type.details }; + + newFunction.details.deprecatedMessage = deprecatedMessage; + + return newFunction; + } + // Creates a new function based on a solved ParamSpec. The input type is assumed to // have a signature that ends in "*args: P.args, **kwargs: P.kwargs". These will be // replaced by the parameters in the ParamSpec. diff --git a/packages/pyright-internal/src/common/configOptions.ts b/packages/pyright-internal/src/common/configOptions.ts index 32310db2f..0fb791c19 100644 --- a/packages/pyright-internal/src/common/configOptions.ts +++ b/packages/pyright-internal/src/common/configOptions.ts @@ -25,6 +25,7 @@ import { getFileSpec, isDirectory, normalizePath, + realCasePath, resolvePaths, } from './pathUtils'; import { latestStablePythonVersion, PythonVersion, versionFromString, versionToString } from './pythonVersion'; @@ -1255,14 +1256,14 @@ export class ConfigOptions { // Auto-detect the common scenario where the sources are under the src folder const srcPath = resolvePaths(this.projectRoot, pathConsts.src); if (fs.existsSync(srcPath) && !fs.existsSync(resolvePaths(srcPath, '__init__.py'))) { - paths.push(srcPath); + paths.push(realCasePath(srcPath, fs)); } } if (extraPaths && extraPaths.length > 0) { for (const p of extraPaths) { const path = resolvePaths(this.projectRoot, p); - paths.push(path); + paths.push(realCasePath(path, fs)); if (isDirectory(fs, path)) { appendArray(paths, getPathsFromPthFiles(fs, path)); } diff --git a/packages/pyright-internal/src/common/extensibility.ts b/packages/pyright-internal/src/common/extensibility.ts index ac7aef397..9e82cd26b 100644 --- a/packages/pyright-internal/src/common/extensibility.ts +++ b/packages/pyright-internal/src/common/extensibility.ts @@ -25,6 +25,7 @@ import { Range } from './textRange'; import { SymbolTable } from '../analyzer/symbol'; import { Diagnostic } from '../common/diagnostic'; import { IPythonMode } from '../analyzer/sourceFile'; +import { ServiceKey } from './serviceProvider'; export interface LanguageServiceExtension { // empty @@ -74,6 +75,11 @@ export interface SourceFileInfo { readonly shadowedBy: readonly SourceFileInfo[]; } +export interface ServiceProvider { + tryGet(key: ServiceKey): T | undefined; + get(key: ServiceKey): T; +} + // Readonly wrapper around a Program. Makes sure it doesn't mutate the program. export interface ProgramView { readonly id: string; @@ -83,6 +89,7 @@ export interface ProgramView { readonly configOptions: ConfigOptions; readonly importResolver: ImportResolver; readonly fileSystem: ReadOnlyFileSystem; + readonly serviceProvider: ServiceProvider; owns(file: string): boolean; getSourceFileInfoList(): readonly SourceFileInfo[]; diff --git a/packages/pyright-internal/src/common/pathUtils.ts b/packages/pyright-internal/src/common/pathUtils.ts index 780c1874b..58b0beb0e 100644 --- a/packages/pyright-internal/src/common/pathUtils.ts +++ b/packages/pyright-internal/src/common/pathUtils.ts @@ -13,17 +13,11 @@ import { URI } from 'vscode-uri'; import { Char } from './charCodes'; import { some } from './collectionUtils'; -import { compareValues, Comparison, GetCanonicalFileName, identity } from './core'; +import { GetCanonicalFileName, identity } from './core'; import { randomBytesHex } from './crypto'; import * as debug from './debug'; import { FileSystem, ReadOnlyFileSystem, Stats } from './fileSystem'; -import { - compareStringsCaseInsensitive, - compareStringsCaseSensitive, - equateStringsCaseInsensitive, - equateStringsCaseSensitive, - getStringComparer, -} from './stringUtils'; +import { equateStringsCaseInsensitive, equateStringsCaseSensitive } from './stringUtils'; let _fsCaseSensitivity: boolean | undefined = undefined; let _underTest: boolean = false; @@ -268,24 +262,6 @@ export function combinePaths(pathString: string, ...paths: (string | undefined)[ return pathString; } -/** - * Compare two paths using the provided case sensitivity. - */ -export function comparePaths(a: string, b: string, ignoreCase?: boolean): Comparison; -export function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; -export function comparePaths(a: string, b: string, currentDirectory?: string | boolean, ignoreCase?: boolean) { - a = normalizePath(a); - b = normalizePath(b); - - if (typeof currentDirectory === 'string') { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } else if (typeof currentDirectory === 'boolean') { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, getStringComparer(ignoreCase)); -} - /** * Determines whether a `parent` path contains a `child` path using the provide case sensitivity. */ @@ -507,20 +483,6 @@ export function getRelativePathComponentsFromDirectory( return pathComponents; } -/** - * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. - */ -export function comparePathsCaseSensitive(a: string, b: string) { - return comparePathsWorker(a, b, compareStringsCaseSensitive); -} - -/** - * Performs a case-insensitive comparison of two paths. - */ -export function comparePathsCaseInsensitive(a: string, b: string) { - return comparePathsWorker(a, b, compareStringsCaseInsensitive); -} - export function ensureTrailingDirectorySeparator(pathString: string): string { if (!hasTrailingDirectorySeparator(pathString)) { return pathString + path.sep; @@ -573,6 +535,10 @@ export function stripFileExtension(fileName: string, multiDotExtension = false) return fileName.substr(0, fileName.length - ext.length); } +export function realCasePath(pathString: string, fileSystem: ReadOnlyFileSystem): string { + return normalizePath(fileSystem.realCasePath(pathString)); +} + export function normalizePath(pathString: string): string { return normalizeSlashes(path.normalize(pathString)); } @@ -607,7 +573,7 @@ export function tryStat(fs: ReadOnlyFileSystem, path: string): Stats | undefined export function tryRealpath(fs: ReadOnlyFileSystem, path: string): string | undefined { try { - return fs.realpathSync(path); + return fs.realCasePath(path); } catch (e: any) { return undefined; } @@ -807,54 +773,6 @@ export function isDiskPathRoot(path: string) { return rootLength > 0 && rootLength === path.length; } -//// Path Comparisons -function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) { - if (a === b) { - return Comparison.EqualTo; - } - if (a === undefined) { - return Comparison.LessThan; - } - if (b === undefined) { - return Comparison.GreaterThan; - } - - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - const aRoot = a.substring(0, getRootLength(a)); - const bRoot = b.substring(0, getRootLength(b)); - const result = compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== Comparison.EqualTo) { - return result; - } - - // check path for these segments: '', '.'. '..' - const escapedSeparator = getRegexEscapedSeparator(); - const relativePathSegmentRegExp = new RegExp(`(^|${escapedSeparator}).{0,2}($|${escapedSeparator})`); - - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - const aRest = a.substring(aRoot.length); - const bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - const aComponents = getPathComponents(a); - const bComponents = getPathComponents(b); - const sharedLength = Math.min(aComponents.length, bComponents.length); - for (let i = 1; i < sharedLength; i++) { - const result = componentComparer(aComponents[i], bComponents[i]); - if (result !== Comparison.EqualTo) { - return result; - } - } - - return compareValues(aComponents.length, bComponents.length); -} - function getAnyExtensionFromPathWorker( path: string, extensions: string | readonly string[], @@ -943,7 +861,7 @@ function fileSystemEntryExists(fs: ReadOnlyFileSystem, path: string, entryKind: } export function convertUriToPath(fs: ReadOnlyFileSystem, uriString: string): string { - return fs.getMappedFilePath(extractPathFromUri(uriString)); + return realCasePath(fs.getMappedFilePath(extractPathFromUri(uriString)), fs); } export function extractPathFromUri(uriString: string) { @@ -955,7 +873,7 @@ export function extractPathFromUri(uriString: string) { // If this is a DOS-style path with a drive letter, remove // the leading slash. if (convertedPath.match(/^\\[a-zA-Z]:\\/)) { - convertedPath = convertedPath.substr(1); + convertedPath = convertedPath.slice(1); } return convertedPath; @@ -965,17 +883,6 @@ export function convertPathToUri(fs: ReadOnlyFileSystem, path: string): string { return fs.getUri(fs.getOriginalFilePath(path)); } -// For file systems that are case-insensitive, returns a lowercase -// version of the path. For case-sensitive file systems, leaves the -// path as is. -export function normalizePathCase(fs: FileSystem, path: string) { - if (isFileSystemCaseSensitive(fs)) { - return path; - } - - return path.toLowerCase(); -} - export function setTestingMode(underTest: boolean) { _underTest = underTest; } diff --git a/packages/pyright-internal/src/common/realFileSystem.ts b/packages/pyright-internal/src/common/realFileSystem.ts index b90253980..bdc6d6b30 100644 --- a/packages/pyright-internal/src/common/realFileSystem.ts +++ b/packages/pyright-internal/src/common/realFileSystem.ts @@ -22,7 +22,7 @@ import { FileWatcherProvider, nullFileWatcherProvider, } from './fileWatcher'; -import { getRootLength } from './pathUtils'; +import { combinePaths, getDirectoryPath, getFileName, getRootLength } from './pathUtils'; // Automatically remove files created by tmp at process exit. tmp.setGracefulCleanup(); @@ -235,11 +235,21 @@ class RealFileSystem implements FileSystem { } readdirSync(path: string): string[] { - return yarnFS.readdirSync(path); + return yarnFS.readdirSync(path).map((entry) => { + // Make sure the entry name is the real case. + const fullPath = combinePaths(path, entry); + const realPath = this.realCasePath(fullPath); + return getFileName(realPath); + }); } readdirEntriesSync(path: string): fs.Dirent[] { return yarnFS.readdirSync(path, { withFileTypes: true }).map((entry): fs.Dirent => { + // Make sure the entry name is the real case. + const fullPath = combinePaths(path, entry.name); + const realPath = this.realCasePath(fullPath); + (entry.name as any) = getFileName(realPath); + // Treat zip/egg files as directories. // See: https://github.com/yarnpkg/berry/blob/master/packages/vscode-zipfs/sources/ZipFSProvider.ts if (hasZipExtension(entry.name)) { @@ -300,7 +310,11 @@ class RealFileSystem implements FileSystem { } realpathSync(path: string) { - return yarnFS.realpathSync(path); + try { + return yarnFS.realpathSync(path); + } catch (e: any) { + return path; + } } getModulePath(): string { @@ -356,24 +370,23 @@ class RealFileSystem implements FileSystem { realCasePath(path: string): string { try { - // If it doesn't exist in the real FS, return path as it is. + // If it doesn't exist in the real FS, try going up a level and combining it. if (!fs.existsSync(path)) { + if (getRootLength(path) <= 0) { + return path; + } + return combinePaths(this.realCasePath(getDirectoryPath(path)), getFileName(path)); + } + + // If it does exist, skip this for symlinks. + const stat = fs.statSync(path); + if (stat.isSymbolicLink()) { return path; } // realpathSync.native will return casing as in OS rather than // trying to preserve casing given. - const realPath = fs.realpathSync.native(path); - - // path is not rooted, return as it is - const rootLength = getRootLength(realPath); - if (rootLength <= 0) { - return realPath; - } - - // path is rooted, make sure we lower case the root part - // to follow vscode's behavior. - return realPath.substr(0, rootLength).toLowerCase() + realPath.substr(rootLength); + return fs.realpathSync.native(path); } catch (e: any) { // Return as it is, if anything failed. this._console.log(`Failed to get real file system casing for ${path}: ${e}`); diff --git a/packages/pyright-internal/src/languageServerBase.ts b/packages/pyright-internal/src/languageServerBase.ts index 5bdf4f8ed..0567b35ef 100644 --- a/packages/pyright-internal/src/languageServerBase.ts +++ b/packages/pyright-internal/src/languageServerBase.ts @@ -76,6 +76,7 @@ import { import { ResultProgressReporter, attachWorkDone } from 'vscode-languageserver/lib/common/progress'; import { TextDocument } from 'vscode-languageserver-textdocument'; +import { formatBufferWithYapf } from '../../pyright-yapf'; import { AnalysisResults } from './analyzer/analysis'; import { BackgroundAnalysisProgram, InvalidatedReason } from './analyzer/backgroundAnalysisProgram'; import { CacheManager } from './analyzer/cacheManager'; @@ -109,6 +110,7 @@ import { Host } from './common/host'; import { fromLSPAny } from './common/lspUtils'; import { convertPathToUri, deduplicateFolders, getDirectoryPath, getFileName, isFile } from './common/pathUtils'; import { ProgressReportTracker, ProgressReporter } from './common/progressReporter'; +import { ServiceProvider } from './common/serviceProvider'; import { DocumentRange, Position, Range } from './common/textRange'; import { UriParser } from './common/uriParser'; import { AnalyzerServiceExecutor } from './languageService/analyzerServiceExecutor'; @@ -120,14 +122,12 @@ import { DocumentSymbolProvider } from './languageService/documentSymbolProvider import { HoverProvider } from './languageService/hoverProvider'; import { canNavigateToFile } from './languageService/navigationUtils'; import { ReferencesProvider } from './languageService/referencesProvider'; +import { RenameProvider } from './languageService/renameProvider'; import { SignatureHelpProvider } from './languageService/signatureHelpProvider'; +import { WorkspaceSymbolProvider } from './languageService/workspaceSymbolProvider'; import { Localizer, setLocaleOverride } from './localization/localize'; import { SupportUriToPathMapping } from './pyrightFileSystem'; import { InitStatus, WellKnownWorkspaceKinds, Workspace, WorkspaceFactory } from './workspaceFactory'; -import { RenameProvider } from './languageService/renameProvider'; -import { WorkspaceSymbolProvider } from './languageService/workspaceSymbolProvider'; -import { formatBufferWithYapf } from '../../pyright-yapf'; -import { ServiceProvider } from './common/serviceProvider'; export interface ServerSettings { venvPath?: string | undefined; diff --git a/packages/pyright-internal/src/languageService/completionProvider.ts b/packages/pyright-internal/src/languageService/completionProvider.ts index c28fae51d..dbf7d6e05 100644 --- a/packages/pyright-internal/src/languageService/completionProvider.ts +++ b/packages/pyright-internal/src/languageService/completionProvider.ts @@ -124,6 +124,8 @@ import { } from './completionProviderUtils'; import { DocumentSymbolCollector } from './documentSymbolCollector'; import { getAutoImportText, getDocumentationPartsForTypeAndDecl } from './tooltipUtils'; +import { ImportResult } from '../analyzer/importResult'; +import { Localizer } from '../localization/localize'; namespace Keywords { const base: string[] = [ @@ -258,8 +260,8 @@ interface QuoteInfo { quoteCharacter: string; } -export const autoImportDetail = 'Auto-import'; -export const dictionaryKeyDetail = 'Dictionary key'; +export const autoImportDetail = Localizer.Completion.autoImportDetail(); +export const indexValueDetail = Localizer.Completion.indexValueDetail(); // We'll use a somewhat-arbitrary cutoff value here to determine // whether it's sufficiently similar. @@ -2400,12 +2402,12 @@ export class CompletionProvider { quoteInfo, postText, completionMap, - dictionaryKeyDetail + indexValueDetail ); } else { this.addNameToCompletions(key, CompletionItemKind.Constant, priorWord, completionMap, { sortText: this._makeSortText(SortCategory.LiteralValue, key), - itemDetail: dictionaryKeyDetail, + itemDetail: indexValueDetail, }); } } @@ -2729,6 +2731,8 @@ export class CompletionProvider { const parseResults = this.program.getParseResults(resolvedPath); if (!parseResults) { + // Add the implicit imports. + this._addImplicitImportsToCompletion(importInfo, importFromNode, priorWord, completionMap); return completionMap; } @@ -2754,6 +2758,16 @@ export class CompletionProvider { ); // Add the implicit imports. + this._addImplicitImportsToCompletion(importInfo, importFromNode, priorWord, completionMap); + return completionMap; + } + + private _addImplicitImportsToCompletion( + importInfo: ImportResult, + importFromNode: ImportFromNode, + priorWord: string, + completionMap: CompletionMap + ) { importInfo.implicitImports.forEach((implImport) => { if (!importFromNode.imports.find((imp) => imp.name.value === implImport.name)) { this.addNameToCompletions(implImport.name, CompletionItemKind.Module, priorWord, completionMap, { @@ -2761,8 +2775,6 @@ export class CompletionProvider { }); } }); - - return completionMap; } private _findMatchingKeywords(keywordList: string[], partialMatch: string): string[] { diff --git a/packages/pyright-internal/src/localization/localize.ts b/packages/pyright-internal/src/localization/localize.ts index 32a84227f..af4f23fff 100644 --- a/packages/pyright-internal/src/localization/localize.ts +++ b/packages/pyright-internal/src/localization/localize.ts @@ -322,6 +322,8 @@ export namespace Localizer { new ParameterizedString<{ name: string }>(getRawString('Diagnostic.constantRedefinition')); export const constructorNoArgs = () => new ParameterizedString<{ type: string }>(getRawString('Diagnostic.constructorNoArgs')); + export const coroutineInConditionalExpression = () => + getRawString('Diagnostic.coroutineInConditionalExpression'); export const constructorParametersMismatch = () => new ParameterizedString<{ classType: string }>(getRawString('Diagnostic.constructorParametersMismatch')); export const containmentAlwaysFalse = () => @@ -373,6 +375,8 @@ export namespace Localizer { new ParameterizedString<{ name: string }>(getRawString('Diagnostic.deprecatedConstructor')); export const deprecatedFunction = () => new ParameterizedString<{ name: string }>(getRawString('Diagnostic.deprecatedFunction')); + export const deprecatedMethod = () => + new ParameterizedString<{ name: string; className: string }>(getRawString('Diagnostic.deprecatedMethod')); export const deprecatedType = () => new ParameterizedString<{ version: string; replacement: string }>( getRawString('Diagnostic.deprecatedType') @@ -680,8 +684,6 @@ export namespace Localizer { new ParameterizedString<{ name: string; newIndex: number; prevIndex: number }>( getRawString('Diagnostic.overloadReturnTypeMismatch') ); - export const overloadWithImplementation = () => - new ParameterizedString<{ name: string }>(getRawString('Diagnostic.overloadWithImplementation')); export const overloadWithoutImplementation = () => new ParameterizedString<{ name: string }>(getRawString('Diagnostic.overloadWithoutImplementation')); export const overriddenMethodNotFound = () => @@ -1244,9 +1246,13 @@ export namespace Localizer { export const overloadSignature = () => getRawString('DiagnosticAddendum.overloadSignature'); export const overloadNotAssignable = () => new ParameterizedString<{ name: string }>(getRawString('DiagnosticAddendum.overloadNotAssignable')); - export const overloadWithImplementation = () => getRawString('DiagnosticAddendum.overloadWithImplementation'); export const overriddenMethod = () => getRawString('DiagnosticAddendum.overriddenMethod'); export const overriddenSymbol = () => getRawString('DiagnosticAddendum.overriddenSymbol'); + export const overrideIsInvariant = () => getRawString('DiagnosticAddendum.overrideIsInvariant'); + export const overrideInvariantMismatch = () => + new ParameterizedString<{ overrideType: string; baseType: string }>( + getRawString('DiagnosticAddendum.overrideInvariantMismatch') + ); export const overrideNoOverloadMatches = () => getRawString('DiagnosticAddendum.overrideNoOverloadMatches'); export const overrideNotClassMethod = () => getRawString('DiagnosticAddendum.overrideNotClassMethod'); export const overrideNotInstanceMethod = () => getRawString('DiagnosticAddendum.overrideNotInstanceMethod'); @@ -1352,6 +1358,8 @@ export namespace Localizer { new ParameterizedString<{ type: string; name: string }>( getRawString('DiagnosticAddendum.typeConstrainedTypeVar') ); + export const typedDictBaseClass = () => + new ParameterizedString<{ type: string }>(getRawString('DiagnosticAddendum.typedDictBaseClass')); export const typedDictFieldMissing = () => new ParameterizedString<{ name: string; type: string }>( getRawString('DiagnosticAddendum.typedDictFieldMissing') @@ -1460,4 +1468,9 @@ export namespace Localizer { getRawString('CodeAction.renameShadowedFile') ); } + + export namespace Completion { + export const autoImportDetail = () => getRawString('Completion.autoImportDetail'); + export const indexValueDetail = () => getRawString('Completion.indexValueDetail'); + } } diff --git a/packages/pyright-internal/src/localization/package.nls.cs.json b/packages/pyright-internal/src/localization/package.nls.cs.json index 629c63053..67b691b16 100644 --- a/packages/pyright-internal/src/localization/package.nls.cs.json +++ b/packages/pyright-internal/src/localization/package.nls.cs.json @@ -10,6 +10,10 @@ "organizeImports": "Uspořádat direktivy Import", "renameShadowedFile": "Přejmenovat „{oldFile}“ na „{newFile}“" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "Metodu {method} není možné volat, protože je abstraktní", "annotatedParamCountMismatch": "Počet poznámek parametrů se neshoduje: očekával(o/y) se {expected}, ale přijal(o/y) se {received}.", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Přetížené metody musí být všechny abstraktní nebo ne", "overloadImplementationMismatch": "Přetížená implementace není konzistentní se signaturou přetížení {index}", "overloadReturnTypeMismatch": "Přetížení {prevIndex} pro {name} se překrývá s přetížením {newIndex} a vrací nekompatibilní typ", - "overloadWithImplementation": "{name} je označené jako přetížení, ale zahrnuje implementaci", "overloadWithoutImplementation": "„{name}“ je označen(é/o) jako přetížení, ale není zadaná žádná implementace", "overriddenMethodNotFound": "Metoda „{name}“ je označená jako přepsání, ale neexistuje žádná základní metoda se stejným názvem", "overrideDecoratorMissing": "Metoda „{name}“ není označená jako přepsání, ale přepisuje metodu ve třídě „{className}“", @@ -417,7 +420,7 @@ "superCallArgCount": "Pro volání „super“ se očekávaly maximálně dva argumenty", "superCallFirstArg": "Jako první argument pro volání super se očekával typ třídy, ale přijal se {type}", "superCallSecondArg": "Druhý argument volání super musí být objekt nebo třída odvozená z typu {type}", - "superCallZeroArgForm": "Forma nulového argumentu volání super je platná pouze v rámci třídy", + "superCallZeroArgForm": "Forma nulového argumentu „super“ volání je platná pouze v rámci metody.", "symbolIsPossiblyUnbound": "{name} je pravděpodobně nevázané", "symbolIsUnbound": "Název {name} je nevázaný", "symbolIsUndefined": "{name} není definované", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "Výraz typu {sourceType} není možné přiřadit deklarovanému typu {destType}", "typeAssignmentMismatchWildcard": "Symbol importu {name} má typ {sourceType}, který nejde přiřadit deklarovanému typu {destType}.", "typeCallNotAllowed": "Volání type() by se nemělo používat v poznámce typu", + "typeCheckOnly": "Název {name} je označený jako @type_check_only a dá se použít jenom v poznámkách typu", "typeCommentDeprecated": "Použití komentářů typu je zastaralé místo toho použít anotaci typu", "typeExpectedClass": "Očekával se výraz typu, ale přijal se {type}", "typeGuardArgCount": "Za TypeGuard byl očekáván jeden argument typu", @@ -641,7 +645,6 @@ "orPatternMissingName": "Chybějící názvy: {name}", "overloadNotAssignable": "Nejméně jedno přetížení {name} není možné přiřadit", "overloadSignature": "Tady je definován podpis přetížení", - "overloadWithImplementation": "Tělo přetížení funkce by mělo být ...", "overriddenMethod": "Přepsaná metoda", "overriddenSymbol": "Přepsaný symbol", "overrideNoOverloadMatches": "Signatura přetížení v přepsání není kompatibilní se základní metodou", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Zobrazit deklaraci proměnné", "tupleAssignmentMismatch": "Typ „{type}“ není kompatibilní s cílovou řazenou kolekcí členů", "tupleEntryTypeMismatch": "Položka řazené kolekce členů {entry} je nesprávného typu", - "tupleSizeMismatch": "Neshoda velikosti elementu; očekávaný počet: {expected}, počet, který byl přijat: {received}", + "tupleSizeIndeterminate": "Neshoda velikosti řazené kolekce členů; Očekávalo se {expected}, ale přijalo se neurčité.", + "tupleSizeMismatch": "Neshoda velikosti řazené kolekce členů; Očekávalo se {expected}, ale přijalo se {received}.", "typeAssignmentMismatch": "Typ {sourceType} se nedá přiřadit k typu {destType}", "typeBound": "Typ {sourceType} je nekompatibilní s vázaným typem {destType} pro proměnnou typu {name}", "typeConstrainedTypeVar": "Typ {type} není kompatibilní s proměnnou omezeného typu {name}", diff --git a/packages/pyright-internal/src/localization/package.nls.de.json b/packages/pyright-internal/src/localization/package.nls.de.json index cfd392538..c3ef9535f 100644 --- a/packages/pyright-internal/src/localization/package.nls.de.json +++ b/packages/pyright-internal/src/localization/package.nls.de.json @@ -10,6 +10,10 @@ "organizeImports": "Import-Direktiven organisieren", "renameShadowedFile": "\"{oldFile}\" in \"{newFile}\" umbenennen" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "Die Methode \"{method}\" kann nicht aufgerufen werden, da sie abstrakt ist.", "annotatedParamCountMismatch": "Nicht übereinstimmende Parameteranmerkungsanzahl: {expected} erwartet, aber {received} empfangen", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Überladene Methoden müssen alle abstrakt sein oder nicht.", "overloadImplementationMismatch": "Die überladene Implementierung ist nicht konsistent mit der Signatur der Überladung {index}", "overloadReturnTypeMismatch": "Überladung {prevIndex} für \"{name}\" überlappt {newIndex} und gibt einen inkompatiblen Typ zurück.", - "overloadWithImplementation": "\"{name}\" ist als Überladung markiert, enthält jedoch eine Implementierung.", "overloadWithoutImplementation": "\"{name}\" ist als Überladen markiert, es wurde jedoch keine Implementierung bereitgestellt.", "overriddenMethodNotFound": "Die Methode \"{name}\" ist als Überschreibung markiert, aber es ist keine Basismethode mit demselben Namen vorhanden.", "overrideDecoratorMissing": "Die Methode \"{name}\" ist nicht als Überschreibung markiert, überschreibt jedoch eine Methode in der Klasse \"{className}\"", @@ -417,7 +420,7 @@ "superCallArgCount": "Es werden nicht mehr als zwei Argumente für den Superaufruf erwartet.", "superCallFirstArg": "Klassentyp als erstes Argument für super-Aufruf erwartet, aber \"{type}\" empfangen", "superCallSecondArg": "Das zweite Argument für den \"super\"-Aufruf muss ein Objekt oder eine Klasse sein, das bzw. die von \"{type}\" abgeleitet wird.", - "superCallZeroArgForm": "Die Nullargumentform des super-Aufrufs ist nur innerhalb einer Klasse gültig.", + "superCallZeroArgForm": "Zero-argument form of \"super\" call is valid only within a method", "symbolIsPossiblyUnbound": "\"{name}\" ist möglicherweise ungebunden.", "symbolIsUnbound": "\"{name}\" ist ungebunden.", "symbolIsUndefined": "\"{name}\" ist nicht definiert.", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "Ein Ausdruck vom Typ \"{sourceType}\" kann nicht dem deklarierten Typ \"{destType}\" zugewiesen werden.", "typeAssignmentMismatchWildcard": "Das Importsymbol \"{name}\" weist den Typ \"{sourceType}\" auf, der dem deklarierten Typ \"{destType}\" nicht zugewiesen werden kann.", "typeCallNotAllowed": "Der type()-Aufruf darf nicht in der Typanmerkung verwendet werden.", + "typeCheckOnly": "\"{name}\" is marked as @type_check_only and can be used only in type annotations", "typeCommentDeprecated": "Die Verwendung von Typkommentaren ist veraltet; verwenden Sie stattdessen Typanmerkung", "typeExpectedClass": "Typausdruck erwartet, aber \"{type}\" empfangen", "typeGuardArgCount": "Nach \"TypeGuard\" wurde ein einzelnes Typargument erwartet.", @@ -641,7 +645,6 @@ "orPatternMissingName": "Fehlende Namen: {name}", "overloadNotAssignable": "Mindestens eine Überladung von \"{name}\" kann nicht zugewiesen werden.", "overloadSignature": "Die Überladungssignatur ist hier definiert.", - "overloadWithImplementation": "Der Text einer Funktionsüberladung muss \"...\" sein.", "overriddenMethod": "Überschriebene Methode", "overriddenSymbol": "Außer Kraft gesetztes Symbol", "overrideNoOverloadMatches": "Keine Überladungssignatur in Überschreibung ist mit der Basismethode kompatibel.", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Siehe Variablendeklaration", "tupleAssignmentMismatch": "Der Typ \"{type}\" ist nicht mit dem Zieltupel kompatibel.", "tupleEntryTypeMismatch": "Der Tupeleintrag {entry} ist ein falscher Typ.", - "tupleSizeMismatch": "Elementgrößenkonflikt: {expected} erwartet, aber {received} empfangen", + "tupleSizeIndeterminate": "Tuple size mismatch; expected {expected} but received indeterminate", + "tupleSizeMismatch": "Tuple size mismatch; expected {expected} but received {received}", "typeAssignmentMismatch": "Der Typ \"{sourceType}\" kann dem Typ \"{destType}\" nicht zugewiesen werden.", "typeBound": "Der Typ \"{sourceType}\" ist nicht mit dem gebundenen Typ \"{destType}\" für die Typvariablen \"{name}\" kompatibel.", "typeConstrainedTypeVar": "Der Typ \"{type}\" ist mit der eingeschränkten Typvariablen nicht kompatibel \"{name}\"", diff --git a/packages/pyright-internal/src/localization/package.nls.en-us.json b/packages/pyright-internal/src/localization/package.nls.en-us.json index b35c6ca56..8df008c64 100644 --- a/packages/pyright-internal/src/localization/package.nls.en-us.json +++ b/packages/pyright-internal/src/localization/package.nls.en-us.json @@ -78,6 +78,7 @@ "continueInFinally": "\"continue\" cannot be used within a finally clause", "continueOutsideLoop": "\"continue\" can be used only within a loop", "constructorNoArgs": "Expected no arguments to \"{type}\" constructor", + "coroutineInConditionalExpression": "Conditional expression references coroutine which always evaluates to True", "dataClassBaseClassFrozen": "A non-frozen class cannot inherit from a class that is frozen", "dataClassBaseClassNotFrozen": "A frozen class cannot inherit from a class that is not frozen", "dataClassConverterFunction": "Argument of type \"{argType}\" is not a valid converter for field \"{fieldName}\" of type \"{fieldType}\"", @@ -98,7 +99,8 @@ "defaultValueNotAllowed": "Parameter with \"*\" or \"**\" cannot have default value", "deprecatedClass": "The class \"{name}\" is deprecated", "deprecatedConstructor": "The constructor for class \"{name}\" is deprecated", - "deprecatedFunction": "This function \"{name}\" is deprecated", + "deprecatedFunction": "The function \"{name}\" is deprecated", + "deprecatedMethod": "The method \"{name}\" in class \"{className}\" is deprecated", "deprecatedType": "This type is deprecated as of Python {version}; use \"{replacement}\" instead", "delTargetExpr": "Expression cannot be deleted", "dictExpandIllegalInComprehension": "Dictionary expansion not allowed in comprehension", @@ -213,8 +215,8 @@ "implicitStringConcat": "Implicit string concatenation not allowed", "importCycleDetected": "Cycle detected in import chain", "importDepthExceeded": "Import chain depth exceeded {depth}", - "importResolveFailure": "Import \"{importName}\" could not be found in the \"{venv}\" environment.", - "importSourceResolveFailure": "Import \"{importName}\" could not be resolved from source in the \"{venv}\" environment.", + "importResolveFailure": "Import \"{importName}\" could not be resolved", + "importSourceResolveFailure": "Import \"{importName}\" could not be resolved from source", "importSymbolUnknown": "\"{name}\" is unknown import symbol", "incompatibleMethodOverride": "Method \"{name}\" overrides class \"{className}\" in an incompatible manner", "inconsistentIndent": "Unindent amount does not match previous indent", @@ -312,7 +314,6 @@ "overloadAbstractMismatch": "Overloaded methods must all be abstract or not", "overloadImplementationMismatch": "Overloaded implementation is not consistent with signature of overload {index}", "overloadReturnTypeMismatch": "Overload {prevIndex} for \"{name}\" overlaps overload {newIndex} and returns an incompatible type", - "overloadWithImplementation": "\"{name}\" is marked as overload, but it includes an implementation", "overloadWithoutImplementation": "\"{name}\" is marked as overload, but no implementation is provided", "overriddenMethodNotFound": "Method \"{name}\" is marked as override, but no base method of same name is present", "overrideDecoratorMissing": "Method \"{name}\" is not marked as override but is overriding a method in class \"{className}\"", @@ -631,9 +632,10 @@ "orPatternMissingName": "Missing names: {name}", "overloadSignature": "Overload signature is defined here", "overloadNotAssignable": "One or more overloads of \"{name}\" is not assignable", - "overloadWithImplementation": "The body of a function overload should be \"...\"", "overriddenMethod": "Overridden method", "overriddenSymbol": "Overridden symbol", + "overrideIsInvariant": "Variable is mutable so its type is invariant", + "overrideInvariantMismatch": "Override type \"{overrideType}\" is not the same as base type \"{baseType}\"", "overrideNoOverloadMatches": "No overload signature in override is compatible with base method", "overrideNotClassMethod": "Base method is declared as a classmethod but override is not", "overrideNotInstanceMethod": "Base method is declared as an instance method but override is not", @@ -680,6 +682,7 @@ "typeAssignmentMismatch": "Type \"{sourceType}\" cannot be assigned to type \"{destType}\"", "typeBound": "Type \"{sourceType}\" is incompatible with bound type \"{destType}\" for type variable \"{name}\"", "typeConstrainedTypeVar": "Type \"{type}\" is incompatible with constrained type variable \"{name}\"", + "typedDictBaseClass": "Class \"{type}\" is not a TypedDict", "typedDictFieldMissing": "\"{name}\" is missing from \"{type}\"", "typedDictFieldNotReadOnly": "\"{name}\" is not read-only in \"{type}\"", "typedDictFieldNotRequired": "\"{name}\" is not required in \"{type}\"", @@ -723,5 +726,9 @@ "findingReferences": "Finding references", "organizeImports": "Organize Imports", "renameShadowedFile": "Rename \"{oldFile}\" to \"{newFile}\"" + }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" } } diff --git a/packages/pyright-internal/src/localization/package.nls.es.json b/packages/pyright-internal/src/localization/package.nls.es.json index 2dab668e5..d06d81ef4 100644 --- a/packages/pyright-internal/src/localization/package.nls.es.json +++ b/packages/pyright-internal/src/localization/package.nls.es.json @@ -10,6 +10,10 @@ "organizeImports": "Organizar Importaciones", "renameShadowedFile": "Cambie el nombre de \"{oldFile}\" a \"{newFile}\"" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "El método \"{method}\" no puede ser llamado porque es abstracto", "annotatedParamCountMismatch": "El recuento de anotaciones del parámetro no coincide: se esperaba {expected}, pero se recibió {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Todos los métodos sobrecargados deben ser abstractos o no", "overloadImplementationMismatch": "La implementación de la sobrecarga no es consistente con la firma de la sobrecarga {index}", "overloadReturnTypeMismatch": "La sobrecarga {prevIndex} para \" {name}\" se superpone con la sobrecarga {newIndex} y devuelve un tipo incompatible", - "overloadWithImplementation": "\"{name}\" está marcado como sobrecarga, pero incluye una implementación", "overloadWithoutImplementation": "\"{name}\" está marcado como sobrecarga, pero no se proporciona ninguna implementación.", "overriddenMethodNotFound": "El método \"{name}\" está marcado como invalidación, pero no existe ningún método base con el mismo nombre", "overrideDecoratorMissing": "El método \"{name}\" no está marcado como invalidación, pero está reemplazando un método de la clase \"{className}\"", @@ -417,7 +420,7 @@ "superCallArgCount": "No se esperaban más de dos argumentos para la llamada \"super\"", "superCallFirstArg": "Se esperaba el tipo de clase como primer argumento de la llamada a \"super\" pero se recibió \"{type}\"", "superCallSecondArg": "El segundo argumento de la llamada a \"super\" debe ser un objeto o clase que derive de \"{type}\"", - "superCallZeroArgForm": "La forma sin argumentos de la llamada \"super\" sólo es válida dentro de una clase", + "superCallZeroArgForm": "La forma sin argumentos de la llamada \"super\" sólo es válida dentro de un método", "symbolIsPossiblyUnbound": "\"{name}\" está posiblemente desvinculado", "symbolIsUnbound": "\"{name}\" está sin consolidar", "symbolIsUndefined": "\"{name}\" no está definido", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "La expresión del tipo \"{sourceType}\" no puede asignarse al tipo declarado \"{destType}\"", "typeAssignmentMismatchWildcard": "El símbolo de importación \"{name}\" tiene el tipo \"{sourceType}\", que no se puede asignar al tipo declarado \"{destType}\"", "typeCallNotAllowed": "la llamada a type() no debe utilizarse en la anotación de tipo", + "typeCheckOnly": "\"{name}\" está marcado como @type_check_only y solo se puede usar en anotaciones de tipo", "typeCommentDeprecated": "El uso de comentarios de tipo está obsoleto; utilice en su lugar anotaciones de tipo.", "typeExpectedClass": "Se esperaba una expresión de tipo pero se ha recibido \"{type}\"", "typeGuardArgCount": "Se esperaba un único argumento de tipo después de \"TypeGuard\".", @@ -641,7 +645,6 @@ "orPatternMissingName": "Nombres que faltan: {name}", "overloadNotAssignable": "Una o más sobrecargas de \"{name}\" no es asignable", "overloadSignature": "Aquí se define la firma de la sobrecarga", - "overloadWithImplementation": "El cuerpo de una sobrecarga de función debe ser \"...\".", "overriddenMethod": "Método reemplazado", "overriddenSymbol": "Símbolo anulado", "overrideNoOverloadMatches": "Ninguna firma de sobrecarga en anulación es compatible con el método base", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "declaración de variable out", "tupleAssignmentMismatch": "El tipo \"{type}\" no es compatible con la tupla de destino", "tupleEntryTypeMismatch": "La entrada {entry} de la tupla es de tipo incorrecto", - "tupleSizeMismatch": "Tamaño de elemento no coincidente; esperado {expected} pero recibido {received}", + "tupleSizeIndeterminate": "El tamaño de la tupla no coincide; se esperaba {expected} pero se recibió uno indeterminado", + "tupleSizeMismatch": "El tamaño de la tupla no coincide; se esperaba {expected} pero se recibió {received}", "typeAssignmentMismatch": "El tipo \"{sourceType}\" no puede asignarse al tipo \"{destType}\"", "typeBound": "El tipo \"{sourceType}\" es incompatible con el tipo \"{destType}\" vinculado para la variable de tipo \"{name}\"", "typeConstrainedTypeVar": "El tipo \"{type}\" no es compatible con la variable de tipo restringido \"{name}\"", diff --git a/packages/pyright-internal/src/localization/package.nls.fr.json b/packages/pyright-internal/src/localization/package.nls.fr.json index 10359c94c..232286c1e 100644 --- a/packages/pyright-internal/src/localization/package.nls.fr.json +++ b/packages/pyright-internal/src/localization/package.nls.fr.json @@ -10,6 +10,10 @@ "organizeImports": "Organiser les importations", "renameShadowedFile": "Renommez \"{oldFile}\" en \"{newFile}\"" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "Impossible d’appeler la méthode « {method} », car elle est abstraite", "annotatedParamCountMismatch": "Non-concordance du nombre d'annotations de paramètre : attendu {expected} mais reçu {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Les méthodes surchargées doivent toutes être abstraites ou non", "overloadImplementationMismatch": "L’implémentation surchargée n’est pas cohérente avec la signature de la surcharge {index}", "overloadReturnTypeMismatch": "La surcharge {prevIndex} pour « {name} » chevauche la surcharge {newIndex} et retourne un type incompatible", - "overloadWithImplementation": "« {name} » est marqué comme surcharge, mais il inclut une implémentation", "overloadWithoutImplementation": "\"{name}\" est marqué comme surcharge, mais aucune implémentation n'est fournie", "overriddenMethodNotFound": "La méthode \"{name}\" est marquée comme prioritaire, mais aucune méthode de base du même nom n'est présente", "overrideDecoratorMissing": "La méthode \"{name}\" n'est pas marquée comme override mais remplace une méthode dans la classe \"{className}\"", @@ -417,7 +420,7 @@ "superCallArgCount": "Pas plus de deux arguments attendus pour l'appel \"super\"", "superCallFirstArg": "Type de classe attendu en tant que premier argument de l’appel « super », mais « {type} » reçu", "superCallSecondArg": "Le deuxième argument de l’appel « super » doit être un objet ou une classe dérivé de « {type} »", - "superCallZeroArgForm": "La forme d’argument zéro de l’appel « super » est valide uniquement dans une classe", + "superCallZeroArgForm": "La forme sans argument d'appel \"super\" n'est valide que dans une méthode", "symbolIsPossiblyUnbound": "« {name} » est peut-être indépendant", "symbolIsUnbound": "« {name} » est indépendant", "symbolIsUndefined": "« {name} » n’est pas défini", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "Impossible d’affecter l’expression de type « {sourceType} » au type déclaré « {destType} »", "typeAssignmentMismatchWildcard": "Le symbole d’importation « {name} » a le type « {sourceType} », qui ne peut pas être affecté au type déclaré « {destType} »", "typeCallNotAllowed": "l’appel type() ne doit pas être utilisé dans l’annotation de type", + "typeCheckOnly": "\"{name}\" est marqué comme @type_check_only et ne peut être utilisé que dans les annotations de type", "typeCommentDeprecated": "L’utilisation de commentaires de type est déconseillée ; utiliser l’annotation de type à la place", "typeExpectedClass": "Expression de type attendue mais « {type} » reçue", "typeGuardArgCount": "Argument de type unique attendu après « TypeGuard »", @@ -641,7 +645,6 @@ "orPatternMissingName": "Noms manquants : {name}", "overloadNotAssignable": "Une ou plusieurs surcharges de « {name} » ne sont pas assignables", "overloadSignature": "La signature de surcharge est définie ici", - "overloadWithImplementation": "Le corps d’une surcharge de fonction doit être « ... »", "overriddenMethod": "Méthode substituée", "overriddenSymbol": "Symbole substitué", "overrideNoOverloadMatches": "Aucune signature de surcharge dans le remplacement n’est compatible avec la méthode de base", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Voir déclaration de variable", "tupleAssignmentMismatch": "Le type \"{type}\" est incompatible avec le tuple cible", "tupleEntryTypeMismatch": "Le type de l’entrée de tuple {entry} est incorrect", - "tupleSizeMismatch": "Incompatibilité de taille d’élément ; {expected} attendu, mais {received} reçu", + "tupleSizeIndeterminate": "Incompatibilité de taille de tuple ; attendu {expected} mais reçu pour une durée indéterminée", + "tupleSizeMismatch": "Incompatibilité de taille de tuple ; attendu {expected} mais reçu {received}", "typeAssignmentMismatch": "Impossible d’affecter le type « {sourceType} » au type « {destType} »", "typeBound": "Le type « {sourceType} » n’est pas compatible avec le type lié « {destType} » pour la variable de type « {name} »", "typeConstrainedTypeVar": "Le «{type}» de type n’est pas compatible avec les «{name}» de variable de type contrainte", diff --git a/packages/pyright-internal/src/localization/package.nls.it.json b/packages/pyright-internal/src/localization/package.nls.it.json index 1a1642190..c28afc939 100644 --- a/packages/pyright-internal/src/localization/package.nls.it.json +++ b/packages/pyright-internal/src/localization/package.nls.it.json @@ -10,6 +10,10 @@ "organizeImports": "Organizza importazioni", "renameShadowedFile": "Rinomina \"{oldFile}\" in \"{newFile}\"" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "Impossibile chiamare il metodo \"{method}\" perché è astratto", "annotatedParamCountMismatch": "Numero di annotazioni dei parametro non corrispondente: previsto {expected} ma ricevuto {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "I metodi di overload devono essere tutti astratti o no", "overloadImplementationMismatch": "L'implementazione di overload non è coerente con la firma dell'overload {index}", "overloadReturnTypeMismatch": "L'overload {prevIndex} per \"{name}\" si sovrappone all'overload {newIndex} e restituisce un tipo incompatibile", - "overloadWithImplementation": "\"{name}\" è contrassegnato come overload, ma include un'implementazione", "overloadWithoutImplementation": "\"{name}\" è contrassegnato come overload, ma non viene fornita alcuna implementazione", "overriddenMethodNotFound": "Il metodo \"{name}\" è contrassegnato come override, ma non è presente alcun metodo di base con lo stesso nome", "overrideDecoratorMissing": "Il metodo \"{name}\" non è contrassegnato come override, ma esegue l'override di un metodo nella classe \"{className}\"", @@ -417,7 +420,7 @@ "superCallArgCount": "Non sono previsti più di due argomenti per la chiamata \"super\".", "superCallFirstArg": "È previsto un tipo di classe come primo argomento della chiamata \"super\", ma è stato ricevuto \"{type}\"", "superCallSecondArg": "Il secondo argomento della chiamata \"super\" deve essere un oggetto o una classe che deriva da \"{type}\"", - "superCallZeroArgForm": "La forma dell'argomento zero della chiamata \"super\" è valida solo all'interno di una classe", + "superCallZeroArgForm": "Il modulo zero-argument della chiamata \"super\" è valido solo all'interno di un metodo", "symbolIsPossiblyUnbound": "\"{name}\" potrebbe non essere associato", "symbolIsUnbound": "\"{name}\" non associato", "symbolIsUndefined": "\"{name}\" non è definito", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "Impossibile assegnare l'espressione di tipo \"{sourceType}\" al tipo dichiarato \"{destType}\"", "typeAssignmentMismatchWildcard": "Il simbolo di importazione \"{name}\" ha il tipo \"{sourceType}\", che non può essere assegnato al tipo dichiarato \"{destType}\"", "typeCallNotAllowed": "la chiamata type() non deve essere usata nell'annotazione di tipo", + "typeCheckOnly": "\"{name}\" è contrassegnato come @type_check_only e può essere utilizzato solo nelle annotazioni tipo", "typeCommentDeprecated": "L'uso dei commenti di tipo è deprecato. Usare l'annotazione di tipo", "typeExpectedClass": "È prevista un'espressione di tipo ma è stato ricevuto \"{type}\"", "typeGuardArgCount": "È previsto un singolo argomento di tipo dopo \"TypeGuard\"", @@ -641,7 +645,6 @@ "orPatternMissingName": "Nomi mancanti: {name}", "overloadNotAssignable": "Uno o più overload di \"{name}\" non sono assegnabili", "overloadSignature": "La firma di overload è definita qui", - "overloadWithImplementation": "Il corpo di un overload di funzione deve essere \"...\"", "overriddenMethod": "Metodo sottoposto a override", "overriddenSymbol": "Simbolo sottoposto a override", "overrideNoOverloadMatches": "Nessuna firma di overload nell'override è compatibile con il metodo di base", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Vedere la dichiarazione di variabile", "tupleAssignmentMismatch": "Il tipo \"{type}\" non è compatibile con la tupla di destinazione", "tupleEntryTypeMismatch": "Il tipo della voce di tupla {entry} non è corretto", - "tupleSizeMismatch": "Dimensioni dell'elemento non corrispondenti; previsto {expected} ma ricevuto {received}", + "tupleSizeIndeterminate": "Dimensioni tupla non corrispondenti; previsto {expected} ma ricevuto indeterminato", + "tupleSizeMismatch": "Dimensioni tupla non corrispondenti; previsto {expected} ma ricevuto {received}", "typeAssignmentMismatch": "impossibile assegnare il tipo \"{sourceType}\" al tipo \"{destType}\"", "typeBound": "Il tipo \"{sourceType}\" non è compatibile con il tipo associato \"{destType}\" per la variabile di tipo \"{name}\"", "typeConstrainedTypeVar": "Il tipo \"{type}\" non è compatibile con la variabile di tipo vincolato \"{name}\"", diff --git a/packages/pyright-internal/src/localization/package.nls.ja.json b/packages/pyright-internal/src/localization/package.nls.ja.json index 2fb666814..c63dcaaf1 100644 --- a/packages/pyright-internal/src/localization/package.nls.ja.json +++ b/packages/pyright-internal/src/localization/package.nls.ja.json @@ -10,6 +10,10 @@ "organizeImports": "インポートを整理", "renameShadowedFile": "\"{oldFile}\" の名前を \"{newFile}\" に変更します" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "メソッド \"{method}\" は抽象型であるため、呼び出すことができません", "annotatedParamCountMismatch": "パラメーター注釈数の不一致: {expected} が必要ですが、{received} を受信しました", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "オーバーロードされたメソッドはすべて抽象である必要があります。", "overloadImplementationMismatch": "オーバーロードされた実装がオーバーロード {index} のシグネチャと一致しません", "overloadReturnTypeMismatch": "\"{name}\" のオーバーロード {prevIndex} はオーバーロード {newIndex} と重複し、互換性のない型を返します", - "overloadWithImplementation": "\"{name}\" はオーバーロードとしてマークされていますが、実装が含まれています", "overloadWithoutImplementation": "\"{name}\" はオーバーロードとしてマークされていますが、実装は提供されていません", "overriddenMethodNotFound": "メソッド \"{name}\" はオーバーライドとしてマークされていますが、同じ名前の基本メソッドが存在しません", "overrideDecoratorMissing": "メソッド \"{name}\" はオーバーライドとしてマークされていませんが、クラス \"{className}\" のメソッドをオーバーライドしています", @@ -417,7 +420,7 @@ "superCallArgCount": "\"super\" 呼び出しには 2 つ以下の引数が必要です", "superCallFirstArg": "\"super\" 呼び出しの最初の引数としてクラス型が必要ですが、\"{type}\" を受け取りました", "superCallSecondArg": "\"super\" 呼び出しの 2 番目の引数は、\"{type}\" から派生したオブジェクトまたはクラスである必要があります", - "superCallZeroArgForm": "\"super\" 呼び出しの 0 引数形式は、クラス内でのみ有効です", + "superCallZeroArgForm": "\"super\" 呼び出しの 0 引数形式は、メソッド内でのみ有効です", "symbolIsPossiblyUnbound": "\"{name}\" はバインドされていない可能性があります", "symbolIsUnbound": "\"{name}\" はバインドされていません", "symbolIsUndefined": "\"{name}\" が定義されていません", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "型 \"{sourceType}\" の式を宣言された型 \"{destType}\" に割り当てることはできません", "typeAssignmentMismatchWildcard": "宣言された型 \"{destType}\" に割り当てできないシンボル \"{name}\" のインポートに型 \"{sourceType}\" があります", "typeCallNotAllowed": "type() 呼び出しは型注釈で使用しないでください", + "typeCheckOnly": "\"{name}\" は@type_check_onlyとしてマークされており、型注釈でのみ使用できます", "typeCommentDeprecated": "型コメントの使用は非推奨です。代わりに型注釈を使用してください", "typeExpectedClass": "型式が必要ですが、\"{type}\" を受け取りました", "typeGuardArgCount": "\"TypeGuard\" の後に 1 つの型引数が必要です", @@ -641,7 +645,6 @@ "orPatternMissingName": "名前がありません: {name}", "overloadNotAssignable": "\"{name}\" の 1 つ以上のオーバーロードが割り当て可能ではありません", "overloadSignature": "オーバーロードシグネチャはここで定義されています", - "overloadWithImplementation": "関数オーバーロードの本体は \"...\" である必要があります。", "overriddenMethod": "オーバーライドされたメソッド", "overriddenSymbol": "オーバーライドされたシンボル", "overrideNoOverloadMatches": "オーバーライドのオーバーロード シグネチャが基本メソッドと互換性がありません", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "変数宣言を参照してください", "tupleAssignmentMismatch": "型 \"{type}\" はターゲット タプルと互換性がありません", "tupleEntryTypeMismatch": "タプル エントリ {entry} の型が正しくありません", - "tupleSizeMismatch": "要素のサイズが一致しません。{expected} が必要ですが、{received} を受信しました", + "tupleSizeIndeterminate": "タプル サイズが一致しません。{expected} が必要ですが、受け取りは不確定です", + "tupleSizeMismatch": "タプルのサイズが一致しません。{expected} が必要ですが、{received} を受信しました", "typeAssignmentMismatch": "型 \"{sourceType}\" を型 \"{destType}\" に割り当てることはできません", "typeBound": "型 \"{sourceType}\" は、型変数 \"{name}\" のバインドされた型 \"{destType}\" と互換性がありません", "typeConstrainedTypeVar": "型 \"{type}\" は制約付き型変数 \"{name}\" と互換性がありません", diff --git a/packages/pyright-internal/src/localization/package.nls.ko.json b/packages/pyright-internal/src/localization/package.nls.ko.json index 5cfde1662..060d36717 100644 --- a/packages/pyright-internal/src/localization/package.nls.ko.json +++ b/packages/pyright-internal/src/localization/package.nls.ko.json @@ -10,6 +10,10 @@ "organizeImports": "가져오기 구성", "renameShadowedFile": "‘{oldFile}’에서 ‘{newFile}’(으)로 이름 바꾸기" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "\"{method}\" 메서드는 추상이므로 호출할 수 없습니다.", "annotatedParamCountMismatch": "매개 변수 주석 개수가 일치하지 않습니다. {expected}이)(가) 필요하지만 {received}을(를) 받았습니다.", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "오버로드된 메서드는 모두 추상이거나 모두 추상이 아니어야 합니다.", "overloadImplementationMismatch": "오버로드된 구현이 오버로드 {index}의 시그니처와 일치하지 않습니다.", "overloadReturnTypeMismatch": "\"{name}\"에 대한 {prevIndex} 오버로드가 오버로드 {newIndex}과(와) 겹치고 호환되지 않는 형식을 반환합니다.", - "overloadWithImplementation": "\"{name}\"이(가) 오버로드로 표시되었지만 구현이 포함되어 있습니다.", "overloadWithoutImplementation": "‘{name}’이(가) 오버로드로 표시되어 있지만 구현이 제공되지 않았습니다.", "overriddenMethodNotFound": "‘{name}’ 메서드가 재정의로 표시되어 있지만 이름이 같은 기본 메서드가 없습니다.", "overrideDecoratorMissing": "‘{name}’ 메서드가 재정의로 표시되지 않았지만 ‘{className}’ 클래스에서 메서드를 재정의하고 있습니다.", @@ -417,7 +420,7 @@ "superCallArgCount": "‘super’ 호출에는 인수가 2개 이하여야 합니다.", "superCallFirstArg": "\"super\" 호출에 대한 첫 번째 인수로 클래스 형식이 필요하지만 \"{type}\"을(를) 받았습니다.", "superCallSecondArg": "\"super\" 호출에 대한 두 번째 인수는 \"{type}\"에서 파생된 개체 또는 클래스여야 합니다.", - "superCallZeroArgForm": "\"super\" 호출의 인수가 0인 형식은 클래스 내에서만 유효합니다.", + "superCallZeroArgForm": "\"super\" 호출의 인수가 0인 형식은 메서드 내에서만 유효합니다.", "symbolIsPossiblyUnbound": "\"{name}\"은(는) 바인딩되지 않은 것일 수 있습니다.", "symbolIsUnbound": "\"{name}\"의 바인딩이 해제되었습니다.", "symbolIsUndefined": "\"{name}\"이(가) 정의되지 않았습니다.", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "\"{sourceType}\" 형식의 식을 선언된 형식 \"{destType}\"에 할당할 수 없습니다.", "typeAssignmentMismatchWildcard": "가져오기 기호 \"{name}\"에 선언된 형식 \"{destType}\"에 할당할 수 없는 \"{sourceType}\" 형식이 있습니다.", "typeCallNotAllowed": "type() 호출은 형식 주석에 사용하면 안 됩니다.", + "typeCheckOnly": "\"{name}\"이(가) @type_check_only로 표시되어 있으므로 형식 주석에서만 사용할 수 있습니다.", "typeCommentDeprecated": "형식 주석의 사용은 더 이상 사용되지 않습니다. 대신 형식 주석 사용", "typeExpectedClass": "형식 식이 필요하지만 \"{type}\"을(를) 받았습니다.", "typeGuardArgCount": "\"TypeGuard\" 뒤에 단일 형식 인수가 필요합니다.", @@ -641,7 +645,6 @@ "orPatternMissingName": "누락된 이름: {name}", "overloadNotAssignable": "\"{name}\"의 오버로드를 하나 이상 할당할 수 없습니다.", "overloadSignature": "오버로드 서명은 여기에 정의되어 있습니다.", - "overloadWithImplementation": "함수 오버로드의 본문은 \"...\"이어야 합니다.", "overriddenMethod": "재정의된 메서드", "overriddenSymbol": "재정의된 기호", "overrideNoOverloadMatches": "재정의의 오버로드 서명이 기본 메서드와 호환되지 않습니다.", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "변수 선언 보기", "tupleAssignmentMismatch": "‘{type}’ 형식이 대상 튜플과 호환되지 않습니다.", "tupleEntryTypeMismatch": "튜플 항목 {entry}이(가) 잘못된 형식입니다.", - "tupleSizeMismatch": "요소 크기 불일치: {expected}이(가) 필요하지만 {received}을(를) 받았습니다.", + "tupleSizeIndeterminate": "튜플 크기 불일치: {expected}이(가) 필요하지만 미정을 받았습니다.", + "tupleSizeMismatch": "튜플 크기 불일치: {expected}이(가) 필요하지만 {received}을(를) 받았습니다.", "typeAssignmentMismatch": "\"{sourceType}\" 형식은 \"{destType}\" 형식에 할당할 수 없습니다.", "typeBound": "형식 변수 \"{name}\"에 대해 형식 \"{sourceType}\"이(가) 바인딩된 형식 \"{destType}\"과(와) 호환되지 않습니다.", "typeConstrainedTypeVar": "\"{type}\" 형식이 제한된 형식 변수 \"{name}\"과(와) 호환되지 않습니다.", diff --git a/packages/pyright-internal/src/localization/package.nls.pl.json b/packages/pyright-internal/src/localization/package.nls.pl.json index 5ff40851a..954556a3a 100644 --- a/packages/pyright-internal/src/localization/package.nls.pl.json +++ b/packages/pyright-internal/src/localization/package.nls.pl.json @@ -10,6 +10,10 @@ "organizeImports": "Organizuj dyrektywy Import", "renameShadowedFile": "Zmień nazwę „{oldFile}” na „{newFile}”" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "Nie można wywołać metody „{method}”, ponieważ jest abstrakcyjna", "annotatedParamCountMismatch": "Niezgodność liczby adnotacji parametru; oczekiwano {expected}, a uzyskano {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Przeciążone metody muszą być abstrakcyjne lub nieabstrakcyjne", "overloadImplementationMismatch": "Przeciążone wdrożenie jest niespójne z sygnaturą przeciążenia {index}", "overloadReturnTypeMismatch": "Przeciążenie {prevIndex} dla nazwy „{name}” nakłada się na przeciążenie {newIndex} i zwraca niezgodny typ", - "overloadWithImplementation": "Nazwa „{name}” jest oznaczona jako przeciążona, ale zawiera wdrożenie", "overloadWithoutImplementation": "Element „{name}” jest oznaczony jako przeciążony, ale nie podano implementacji", "overriddenMethodNotFound": "Metoda „{name}” jest oznaczona jako zastąpienie, ale nie istnieje metoda bazowa o tej samej nazwie", "overrideDecoratorMissing": "Metoda „{name}” nie jest oznaczona jako zastąpienie, ale zastępuje metodę w klasie „{className}”", @@ -417,7 +420,7 @@ "superCallArgCount": "Oczekiwano nie więcej niż dwóch argumentów wywołania „super”", "superCallFirstArg": "Oczekiwano typu klasy jako pierwszego argumentu wywołania „super”, ale otrzymano „{type}”", "superCallSecondArg": "Drugi argument wywołania „super” musi być obiektem lub klasą wywodzącą się z typu „{type}”", - "superCallZeroArgForm": "Forma bez argumentów wywołania „super” jest prawidłowa tylko w obrębie klasy", + "superCallZeroArgForm": "Forma bez argumentów wywołania „super” jest prawidłowa tylko w ramach metody", "symbolIsPossiblyUnbound": "Nazwa „{name}” jest prawdopodobnie niepowiązana", "symbolIsUnbound": "Nazwa „{name}” jest niepowiązana", "symbolIsUndefined": "Nazwa „{name}” nie jest zdefiniowana", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "Wyrażenie typu „{sourceType}” nie może być przypisane do zadeklarowanego typu „{destType}”", "typeAssignmentMismatchWildcard": "Symbol importu „{name}” ma typ „{sourceType}”, którego nie można przypisać do zadeklarowanego typu „{destType}”", "typeCallNotAllowed": "Wywołanie type() nie powinno być używane w adnotacji typu", + "typeCheckOnly": "Nazwa „{name}” jest oznaczona jako @type_check_only i może być używana tylko w adnotacjach typu", "typeCommentDeprecated": "Używanie komentarzy typu jest przestarzałe; zamiast tego użyj adnotacji typu", "typeExpectedClass": "Oczekiwano wyrażenia typu, ale otrzymano „{type}”", "typeGuardArgCount": "Oczekiwano pojedynczego argumentu typu po „TypeGuard”", @@ -641,7 +645,6 @@ "orPatternMissingName": "Brak nazw: {name}", "overloadNotAssignable": "Nie można przypisać jednego lub więcej przeciążeń „{name}”.", "overloadSignature": "Sygnatura przeciążenia jest zdefiniowana tutaj", - "overloadWithImplementation": "Treść przeciążenia funkcji powinna mieć postać „...”", "overriddenMethod": "Przesłonięta metoda", "overriddenSymbol": "Przesłonięty symbol", "overrideNoOverloadMatches": "Żadna sygnatura przeciążenia w przesłonięciu nie jest zgodna z metodą bazową", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Zobacz deklarację zmiennej", "tupleAssignmentMismatch": "Typ „{type}” jest niezgodny z docelową krotką", "tupleEntryTypeMismatch": "Wpis krotki {entry} jest nieprawidłowego typu", - "tupleSizeMismatch": "Niezgodność rozmiaru elementu; oczekiwano {expected}, ale otrzymano {received}", + "tupleSizeIndeterminate": "Niezgodność rozmiaru krotki; oczekiwano {expected}, ale otrzymano nieokreślony", + "tupleSizeMismatch": "Niezgodność rozmiaru krotki; oczekiwano {expected}, ale otrzymano {received}", "typeAssignmentMismatch": "Nie można przypisać typu „{sourceType}” do typu „{destType}”", "typeBound": "Typ „{sourceType}” jest niezgodny z typem powiązanym „{destType}” dla zmiennej typu „{name}”", "typeConstrainedTypeVar": "Typ „{type}” jest niezgodny ze zmienną typu ograniczonego „{name}”", diff --git a/packages/pyright-internal/src/localization/package.nls.pt-br.json b/packages/pyright-internal/src/localization/package.nls.pt-br.json index c174e7fc2..b2fa56b51 100644 --- a/packages/pyright-internal/src/localization/package.nls.pt-br.json +++ b/packages/pyright-internal/src/localization/package.nls.pt-br.json @@ -10,6 +10,10 @@ "organizeImports": "Organizar as importações", "renameShadowedFile": "Renomear \"{oldFile}\" para \"{newFile}\"" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "O método \"{method}\" não pode ser chamado porque é abstrato", "annotatedParamCountMismatch": "Incompatibilidade de contagem de anotações de parâmetro: esperado {expected}, mas recebido {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Os métodos sobrecarregados devem ser abstratos ou não", "overloadImplementationMismatch": "A implementação sobrecarregada não é consistente com a assinatura da sobrecarga {index}", "overloadReturnTypeMismatch": "A sobrecarga {prevIndex} para \"{name}\" sobrepõe a sobrecarga {newIndex} e retorna um tipo incompatível", - "overloadWithImplementation": "\"{name}\" está marcado como sobrecarga, mas inclui uma implementação", "overloadWithoutImplementation": "\"{name}\" está marcado como sobrecarga, mas nenhuma implementação foi fornecida", "overriddenMethodNotFound": "O método \"{name}\" está marcado como substituição, mas nenhum método base de mesmo nome está presente", "overrideDecoratorMissing": "O método \"{name}\" não está marcado como substituição, mas está substituindo um método na classe \"{className}\"", @@ -417,7 +420,7 @@ "superCallArgCount": "Não mais que dois argumentos eram esperados para a chamada \"super\"", "superCallFirstArg": "Tipo de classe esperado como o primeiro argumento para a chamada \"super\", mas recebeu \"{type}\"", "superCallSecondArg": "O segundo argumento para a chamada \"super\" deve ser objeto ou classe que deriva de \"{type}\"", - "superCallZeroArgForm": "A forma de argumento zero de chamada \"super\" é válida somente dentro de uma classe", + "superCallZeroArgForm": "A forma de chamada \"super\" com argumento zero é válida apenas dentro de um método", "symbolIsPossiblyUnbound": "\"{name}\" possivelmente não está associado", "symbolIsUnbound": "\"{name}\" não está associado", "symbolIsUndefined": "\"{name}\" não está definido", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "A expressão do tipo \"{sourceType}\" não pode ser atribuída ao tipo declarado \"{destType}\"", "typeAssignmentMismatchWildcard": "O símbolo de importação \"{name}\" tem o tipo \"{sourceType}\", que não pode ser atribuído ao tipo declarado \"{destType}\"", "typeCallNotAllowed": "A chamada type() não deve ser usada na anotação de tipo", + "typeCheckOnly": "\"{name}\" está marcado como @type_check_only e pode ser usado apenas em anotações de tipo", "typeCommentDeprecated": "O uso de comentários de tipo foi preterido. Use anotação de tipo em vez disso", "typeExpectedClass": "Expressão de tipo esperada, mas recebeu \"{type}\"", "typeGuardArgCount": "Argumento de tipo único esperado após \"TypeGuard\"", @@ -641,7 +645,6 @@ "orPatternMissingName": "Nomes ausentes: {name}", "overloadNotAssignable": "Uma ou mais sobrecargas de \"{name}\" não podem ser atribuídas", "overloadSignature": "A assinatura de sobrecarga é definida aqui", - "overloadWithImplementation": "O corpo de uma sobrecarga de função deve ser \"...\"", "overriddenMethod": "Método substituído", "overriddenSymbol": "Símbolo substituído", "overrideNoOverloadMatches": "Nenhuma assinatura de sobrecarga na substituição é compatível com o método base", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Consulte a declaração de variável", "tupleAssignmentMismatch": "O tipo \"{type}\" é incompatível com a tupla de destino", "tupleEntryTypeMismatch": "A entrada de tupla {entry} é do tipo incorreto", - "tupleSizeMismatch": "Incompatibilidade de tamanho do elemento. Esperava-se {expected}, mas recebeu {received}", + "tupleSizeIndeterminate": "Incompatibilidade de tamanho de tupla; esperado {expected} mas recebido indeterminado", + "tupleSizeMismatch": "Incompatibilidade de tamanho de tupla; esperado {expected} mas recebido {received}", "typeAssignmentMismatch": "O tipo \"{sourceType}\" não pode ser atribuído ao tipo \"{destType}\"", "typeBound": "O tipo \"{sourceType}\" é incompatível com o tipo associado \"{destType}\" para a variável de tipo \"{name}\"", "typeConstrainedTypeVar": "O tipo \"{type}\" é incompatível com a variável de tipo restrita \"{name}\"", diff --git a/packages/pyright-internal/src/localization/package.nls.qps-ploc.json b/packages/pyright-internal/src/localization/package.nls.qps-ploc.json index 827862887..a6c3d5c5b 100644 --- a/packages/pyright-internal/src/localization/package.nls.qps-ploc.json +++ b/packages/pyright-internal/src/localization/package.nls.qps-ploc.json @@ -10,6 +10,10 @@ "organizeImports": "[KhOyl][นั้Ørgæñïzë ÏmpørtsẤğ倪İЂҰนั้ढूँ]", "renameShadowedFile": "[E02Ab][นั้Rëñæmë \"{ølðFïlë}\" tø \"{ñëwFïlë}\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]" }, + "Completion": { + "autoImportDetail": "[WdNQG][นั้Ƶtø-ïmpørtẤğ倪İนั้ढूँ]", + "indexValueDetail": "[mX94Q][นั้Ïñðëx vælµëẤğ倪İนั้ढूँ]" + }, "Diagnostic": { "abstractMethodInvocation": "[fE8MD][นั้Mëthøð \"{mëthøð}\" çæññøt þë çællëð þëçæµsë ït ïs æþstræçtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]", "annotatedParamCountMismatch": "[VZvZc][นั้Pæræmëtër æññøtætïøñ çøµñt mïsmætçh: ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "[54DCM][นั้Øvërløæðëð mëthøðs mµst æll þë æþstræçt ør ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]", "overloadImplementationMismatch": "[dXlXE][นั้Øvërløæðëð ïmplëmëñtætïøñ ïs ñøt çøñsïstëñt wïth sïgñætµrë øf øvërløæð {ïñðëx}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]", "overloadReturnTypeMismatch": "[6BN74][นั้Øvërløæð {prëvÏñðëx} før \"{ñæmë}\" øvërlæps øvërløæð {ñëwÏñðëx} æñð rëtµrñs æñ ïñçømpætïþlë tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]", - "overloadWithImplementation": "[jYBzA][นั้\"{ñæmë}\" ïs mærkëð æs øvërløæð, þµt ït ïñçlµðës æñ ïmplëmëñtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", "overloadWithoutImplementation": "[mn33a][นั้\"{ñæmë}\" ïs mærkëð æs øvërløæð, þµt ñø ïmplëmëñtætïøñ ïs prøvïðëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", "overriddenMethodNotFound": "[YKdBy][นั้Mëthøð \"{ñæmë}\" ïs mærkëð æs øvërrïðë, þµt ñø þæsë mëthøð øf sæmë ñæmë ïs prësëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]", "overrideDecoratorMissing": "[2BnJq][นั้Mëthøð \"{ñæmë}\" ïs ñøt mærkëð æs øvërrïðë þµt ïs øvërrïðïñg æ mëthøð ïñ çlæss \"{çlæssÑæmë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]", @@ -417,7 +420,7 @@ "superCallArgCount": "[iLYq6][นั้Ëxpëçtëð ñø mørë thæñ twø ærgµmëñts tø \"sµpër\" çællẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]", "superCallFirstArg": "[HSEvD][นั้Ëxpëçtëð çlæss tÿpë æs fïrst ærgµmëñt tø \"sµpër\" çæll þµt rëçëïvëð \"{tÿpë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]", "superCallSecondArg": "[dKoHi][นั้§ëçøñð ærgµmëñt tø \"sµpër\" çæll mµst þë øþjëçt ør çlæss thæt ðërïvës frøm \"{tÿpë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]", - "superCallZeroArgForm": "[0XO27][นั้Zërø-ærgµmëñt førm øf \"sµpër\" çæll ïs vælïð øñlÿ wïthïñ æ çlæssẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", + "superCallZeroArgForm": "[0XO27][นั้Zërø-ærgµmëñt førm øf \"sµpër\" çæll ïs vælïð øñlÿ wïthïñ æ mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", "symbolIsPossiblyUnbound": "[cUgue][นั้\"{ñæmë}\" ïs pøssïþlÿ µñþøµñðẤğ倪İЂҰक्र्तिृนั้ढूँ]", "symbolIsUnbound": "[zhGl5][นั้\"{ñæmë}\" ïs µñþøµñðẤğ倪İЂҰक्นั้ढूँ]", "symbolIsUndefined": "[qCm6F][นั้\"{ñæmë}\" ïs ñøt ðëfïñëðẤğ倪İЂҰक्र्นั้ढूँ]", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "[wwjSP][นั้Ëxprëssïøñ øf tÿpë \"{søµrçëTÿpë}\" çæññøt þë æssïgñëð tø ðëçlærëð tÿpë \"{ðëstTÿpë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]", "typeAssignmentMismatchWildcard": "[qdgVA][นั้Ïmpørt sÿmþøl \"{ñæmë}\" hæs tÿpë \"{søµrçëTÿpë}\", whïçh çæññøt þë æssïgñëð tø ðëçlærëð tÿpë \"{ðëstTÿpë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", "typeCallNotAllowed": "[OGMmG][นั้tÿpë() çæll shøµlð ñøt þë µsëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]", + "typeCheckOnly": "[cSmKj][นั้\"{ñæmë}\" ïs mærkëð æs @tÿpë_çhëçk_øñlÿ æñð çæñ þë µsëð øñlÿ ïñ tÿpë æññøtætïøñsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]", "typeCommentDeprecated": "[SRhVz][นั้Üsë øf tÿpë çømmëñts ïs ðëprëçætëð; µsë tÿpë æññøtætïøñ ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", "typeExpectedClass": "[r0pdu][นั้Ëxpëçtëð tÿpë ëxprëssïøñ þµt rëçëïvëð \"{tÿpë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]", "typeGuardArgCount": "[Zl47K][นั้Ëxpëçtëð æ sïñglë tÿpë ærgµmëñt æftër \"TÿpëGµærð\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]", @@ -641,7 +645,6 @@ "orPatternMissingName": "[kgiPM][นั้Mïssïñg ñæmës: {ñæmë}Ấğ倪İЂҰक्นั้ढूँ]", "overloadNotAssignable": "[BA2kK][นั้Øñë ør mørë øvërløæðs øf \"{ñæmë}\" ïs ñøt æssïgñæþlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]", "overloadSignature": "[NPzwf][นั้Øvërløæð sïgñætµrë ïs ðëfïñëð hërëẤğ倪İЂҰक्र्तिृまนั้ढूँ]", - "overloadWithImplementation": "[G5f4V][นั้Thë þøðÿ øf æ fµñçtïøñ øvërløæð shøµlð þë \"...\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]", "overriddenMethod": "[CcUB2][นั้Øvërrïððëñ mëthøðẤğ倪İЂҰक्นั้ढूँ]", "overriddenSymbol": "[cvpXz][นั้Øvërrïððëñ sÿmþølẤğ倪İЂҰक्นั้ढूँ]", "overrideNoOverloadMatches": "[vG14w][นั้Ñø øvërløæð sïgñætµrë ïñ øvërrïðë ïs çømpætïþlë wïth þæsë mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "[M3EiY][นั้§ëë værïæþlë ðëçlærætïøñẤğ倪İЂҰक्र्นั้ढूँ]", "tupleAssignmentMismatch": "[aLGep][นั้Tÿpë \"{tÿpë}\" ïs ïñçømpætïþlë wïth tærgët tµplëẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]", "tupleEntryTypeMismatch": "[ny8Sn][นั้Tµplë ëñtrÿ {ëñtrÿ} ïs ïñçørrëçt tÿpëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]", - "tupleSizeMismatch": "[F2Yc7][นั้Ëlëmëñt sïzë mïsmætçh; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", + "tupleSizeIndeterminate": "[8QDbp][นั้Tµplë sïzë mïsmætçh; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð ïñðëtërmïñætëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", + "tupleSizeMismatch": "[F2Yc7][นั้Tµplë sïzë mïsmætçh; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]", "typeAssignmentMismatch": "[VF9B4][นั้Tÿpë \"{søµrçëTÿpë}\" çæññøt þë æssïgñëð tø tÿpë \"{ðëstTÿpë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]", "typeBound": "[AIZri][นั้Tÿpë \"{søµrçëTÿpë}\" ïs ïñçømpætïþlë wïth þøµñð tÿpë \"{ðëstTÿpë}\" før tÿpë værïæþlë \"{ñæmë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]", "typeConstrainedTypeVar": "[qHztb][นั้Tÿpë \"{tÿpë}\" ïs ïñçømpætïþlë wïth çøñstræïñëð tÿpë værïæþlë \"{ñæmë}\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]", diff --git a/packages/pyright-internal/src/localization/package.nls.ru.json b/packages/pyright-internal/src/localization/package.nls.ru.json index f45706dde..c378ddce3 100644 --- a/packages/pyright-internal/src/localization/package.nls.ru.json +++ b/packages/pyright-internal/src/localization/package.nls.ru.json @@ -10,6 +10,10 @@ "organizeImports": "Упорядочение импорта", "renameShadowedFile": "Переименовать \"{oldFile}\" в \"{newFile}\"" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "Метод \"{method}\" не может быть вызван, так как является абстрактным", "annotatedParamCountMismatch": "Несоответствие числа аннотаций параметра: ожидается {expected}, но получено {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Все перегруженные методы должны быть абстрактными или не абстрактными", "overloadImplementationMismatch": "Перегруженная реализация не согласована с сигнатурой перегрузки {index}", "overloadReturnTypeMismatch": "Перегрузка {prevIndex} для \"{name}\" перекрывает перегрузку {newIndex} и возвращает несовместимый тип", - "overloadWithImplementation": "\"{name}\" помечен как перегруженный, но содержит реализацию", "overloadWithoutImplementation": "\"{name}\" помечен как перегруженный, но реализация не предоставлена", "overriddenMethodNotFound": "Метод \"{name}\" помечен как переопределение, но базового метода с таким же именем нет.", "overrideDecoratorMissing": "Метод \"{name}\" не помечен в качестве переопределения, но переопределяет метод в классе \"{className}\"", @@ -417,7 +420,7 @@ "superCallArgCount": "Ожидается не более двух аргументов для вызова \"super\"", "superCallFirstArg": "В качестве первого аргумента для вызова \"super\" ожидался тип класса, но получен \"{type}\"", "superCallSecondArg": "Второй аргумент для вызова \"super\" должен быть объектом или классом, производным от \"{type}\"", - "superCallZeroArgForm": "Форма вызова \"super\" с нулевым аргументом допустима только внутри класса", + "superCallZeroArgForm": "Форма вызова \"super\" с нулевым аргументом допустима только внутри метода", "symbolIsPossiblyUnbound": "Элемент \"{name}\", возможно, не привязан", "symbolIsUnbound": "Элемент \"{name}\" не привязан", "symbolIsUndefined": "\"{name}\" не определено", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "Выражение типа \"{sourceType}\" нельзя присвоить объявленному типу \"{destType}\"", "typeAssignmentMismatchWildcard": "Символ импорта \"{name}\" имеет тип \"{sourceType}\", который не может быть назначен объявленному типу \"{destType}\"", "typeCallNotAllowed": "Вызов type() не разрешен в заметках типа", + "typeCheckOnly": "\"{name}\" помечено как @type_check_only и может использоваться только в заметках с типом", "typeCommentDeprecated": "Комментарии типа больше не рекомендуются к использованию; вместо них используйте заметки типа", "typeExpectedClass": "Ожидалось выражение типа, но получено \"{type}\"", "typeGuardArgCount": "После \"TypeGuard\" ожидается один аргумент типа", @@ -641,7 +645,6 @@ "orPatternMissingName": "Отсутствуют имена: {name}", "overloadNotAssignable": "Одна или несколько перегрузок \"{name}\" не подлежат присвоению", "overloadSignature": "Здесь определена сигнатура перегрузки", - "overloadWithImplementation": "Тело перегрузки функции должно представлять собой \"...\"", "overriddenMethod": "Переопределенный метод", "overriddenSymbol": "Переопределенный символ", "overrideNoOverloadMatches": "В переопределении нет сигнатуры перегрузки, совместимой с базовым методом", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Просмотреть объявление переменной", "tupleAssignmentMismatch": "Тип \"{type}\" несовместим с целевым кортежем", "tupleEntryTypeMismatch": "Запись кортежа {entry} имеет неверный тип", - "tupleSizeMismatch": "Несоответствие размеров элемента: ожидается \"{expected}\", но получено \"{received}\"", + "tupleSizeIndeterminate": "Несоответствие размеров кортежа: ожидается \"{expected}\", но получено неопределенное значение", + "tupleSizeMismatch": "Несоответствие размеров кортежа: ожидается \"{expected}\", но получено \"{received}\"", "typeAssignmentMismatch": "Тип \"{sourceType}\" нельзя присвоить типу \"{destType}\"", "typeBound": "Тип \"{sourceType}\" несовместим с привязанным типом \"{destType}\" для переменной типа \"{name}\"", "typeConstrainedTypeVar": "Тип \"{type}\" несовместим с переменной ограниченного типа \"{name}\"", diff --git a/packages/pyright-internal/src/localization/package.nls.tr.json b/packages/pyright-internal/src/localization/package.nls.tr.json index f1ab2a018..ba96a49f0 100644 --- a/packages/pyright-internal/src/localization/package.nls.tr.json +++ b/packages/pyright-internal/src/localization/package.nls.tr.json @@ -10,6 +10,10 @@ "organizeImports": "İçeri Aktarmaları Düzenle", "renameShadowedFile": "\"{oldFile}\" dosyasını \"{newFile}\" olarak yeniden adlandır" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "\"{method}\" metodu soyut olduğundan çağrılamaz", "annotatedParamCountMismatch": "Parametre ek açıklama sayısı uyuşmazlığı: {expected} bekleniyordu ancak {received} alındı", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "Aşırı yüklenmiş metotların tümü soyut olmalı veya tümü olmamalıdır", "overloadImplementationMismatch": "Aşırı yüklenmiş uygulama, {index} aşırı yükleme imzası ile tutarlı değil", "overloadReturnTypeMismatch": "\"{name}\" için {prevIndex} aşırı yüklemesi {newIndex} aşırı yüklemesi ile çakışıyor ve uyumsuz bir tür döndürüyor", - "overloadWithImplementation": "\"{name}\" aşırı yükleme olarak işaretlenmiş, ancak bir uygulama içeriyor", "overloadWithoutImplementation": "\"{name}\" aşırı yük olarak işaretlendi, ancak uygulama sağlanmadı", "overriddenMethodNotFound": "\"{name}\" metodu geçersiz kılma olarak işaretlendi, ancak aynı ada sahip bir temel metot yok", "overrideDecoratorMissing": "\"{name}\" metodu geçersiz kılma olarak işaretlenmedi ancak \"{className}\" sınıfındaki bir metodu geçersiz kılıyor", @@ -417,7 +420,7 @@ "superCallArgCount": "\"super\" çağrısı için ikiden fazla bağımsız değişken beklenmiyordu", "superCallFirstArg": "\"super\" çağrısının ilk bağımsız değişkeni olarak sınıf türü bekleniyordu ancak \"{type}\" alındı", "superCallSecondArg": "\"super\" çağrısının ikinci bağımsız değişkeni, \"{type}\" türünden türetilen nesne veya sınıf olmalıdır", - "superCallZeroArgForm": "\"super\" çağrısının zero-argument biçimi yalnızca bir sınıf içinde geçerlidir", + "superCallZeroArgForm": "\"super\" çağrısının zero-argument biçimi yalnızca bir metot içinde geçerlidir", "symbolIsPossiblyUnbound": "\"{name}\" büyük olasılıkla bağlı değil", "symbolIsUnbound": "\"{name}\" bağlı değil", "symbolIsUndefined": "\"{name}\" tanımlanmadı", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "\"{sourceType}\" türündeki ifade, \"{destType}\" bildirilen türüne atanamaz", "typeAssignmentMismatchWildcard": "\"{name}\" içeri aktarma sembolü \"{sourceType}\" türüne sahip ve bu tür, \"{destType}\" bildirilen türüne atanamaz", "typeCallNotAllowed": "Tür ek açıklamasında type() çağrısı kullanılmamalıdır", + "typeCheckOnly": "\"{name}\", @type_check_only olarak işaretlendi ve yalnızca tür ek açıklamalarında kullanılabilir", "typeCommentDeprecated": "Tür açıklamalarının kullanımı kullanım dışı; bunun yerine tür ek açıklaması kullanın", "typeExpectedClass": "Tür ifadesi bekleniyordu ancak \"{type}\" alındı", "typeGuardArgCount": "\"TypeGuard\" sonrasında tek bir tür bağımsız değişken bekleniyordu", @@ -641,7 +645,6 @@ "orPatternMissingName": "Eksik adlar: {name}", "overloadNotAssignable": "Bir veya daha fazla \"{name}\" aşırı yüklemesi atanabilir değil", "overloadSignature": "Aşırı yükleme imzası burada tanımlı", - "overloadWithImplementation": "İşlev aşırı yüklemesinin gövdesi \"...\" olmalıdır", "overriddenMethod": "Geçersiz kılınan metot", "overriddenSymbol": "Geçersiz kılınan simge", "overrideNoOverloadMatches": "Geçersiz kılmadaki hiçbir aşırı yükleme imzası temel metotla uyumlu değil", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "Değişken bildirimine bakın", "tupleAssignmentMismatch": "\"{type}\" türü hedef demet ile uyumsuz", "tupleEntryTypeMismatch": "{entry} demet girdisi doğru türde değil", - "tupleSizeMismatch": "Öğe boyutu uyuşmuyor; \"{expected}\" bekleniyordu ancak \"{received}\" alındı", + "tupleSizeIndeterminate": "Demet boyutu uyuşmuyor; {expected} bekleniyordu ancak indeterminate alındı", + "tupleSizeMismatch": "Demet boyutu uyuşmuyor; {expected} bekleniyordu ancak {received} alındı", "typeAssignmentMismatch": "\"{sourceType}\" türü \"{destType}\" türüne atanamaz", "typeBound": "\"{sourceType}\" türü, \"{name}\" tür değişkeni için \"{destType}\" bağlı türü ile uyumlu değil", "typeConstrainedTypeVar": "\"{type}\" türü, \"{name}\" kısıtlanmış tür değişkeni değişkeniyle uyumlu değil", diff --git a/packages/pyright-internal/src/localization/package.nls.zh-cn.json b/packages/pyright-internal/src/localization/package.nls.zh-cn.json index dc083f2f2..464c81637 100644 --- a/packages/pyright-internal/src/localization/package.nls.zh-cn.json +++ b/packages/pyright-internal/src/localization/package.nls.zh-cn.json @@ -10,6 +10,10 @@ "organizeImports": "整理 Import", "renameShadowedFile": "将“{oldFile}”重命名为“{newFile}”" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "无法调用方法\"{method}\",因为它是抽象的", "annotatedParamCountMismatch": "参数批注计数不匹配: 应为 {expected},但收到 {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "重载的方法必须全部为抽象方法或不为抽象方法", "overloadImplementationMismatch": "重载实现与重载 {index} 的签名不一致", "overloadReturnTypeMismatch": "“{name}”的重载 {prevIndex} 与重载 {newIndex} 重叠,并返回不兼容的类型", - "overloadWithImplementation": "“{name}”被标记为重载,但它包含一个实现", "overloadWithoutImplementation": "\"{name}\"标记为重载,但未提供实现", "overriddenMethodNotFound": "方法\"{name}\"标记为替代,但不存在同名的基方法", "overrideDecoratorMissing": "方法\"{name}\"未标记为替代,但正在替代类\"{className}\"中的方法", @@ -417,7 +420,7 @@ "superCallArgCount": "“super” 调用应不超过两个参数", "superCallFirstArg": "应将类类型作为“super”调用的第一个参数,但收到“{type}”", "superCallSecondArg": "“super”调用的第二个参数必须是派生自“{type}”的对象或类", - "superCallZeroArgForm": "“super”调用的零参数形式仅在类中有效", + "superCallZeroArgForm": "“Super”调用的零参数形式仅在方法中有效", "symbolIsPossiblyUnbound": "“{name}”可能未绑定", "symbolIsUnbound": "“{name}”未绑定", "symbolIsUndefined": "未定义“{name}”", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "无法将类型“{sourceType}”的表达式分配给声明的类型“{destType}”", "typeAssignmentMismatchWildcard": "导入符号“{name}”的类型为“{sourceType}”,无法将其分配给声明的类型“{destType}”", "typeCallNotAllowed": "type() 调用不应用于类型批注", + "typeCheckOnly": "“{name}”标记为 @type_check_only,并且只能在类型注释中使用", "typeCommentDeprecated": "已弃用类型注释;请改用类型批注", "typeExpectedClass": "应为类型表达式,但收到“{type}”", "typeGuardArgCount": "“TypeGuard”后应为单个类型参数", @@ -641,7 +645,6 @@ "orPatternMissingName": "缺少名称: {name}", "overloadNotAssignable": "无法分配“{name}”的一个或多个重载", "overloadSignature": "此处定义了重载签名", - "overloadWithImplementation": "函数重载的正文应为 “...”", "overriddenMethod": "替代的方法", "overriddenSymbol": "替代符号", "overrideNoOverloadMatches": "替代中没有与基本方法兼容的重载签名", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "查看变量声明", "tupleAssignmentMismatch": "类型\"{type}\"与目标元组不兼容", "tupleEntryTypeMismatch": "元组条目 {entry} 的类型不正确", - "tupleSizeMismatch": "元素大小不匹配;应为 {expected},但收到 {received}", + "tupleSizeIndeterminate": "元组大小不匹配;应为 {expected},但收到不确定的", + "tupleSizeMismatch": "元组大小不匹配;应为 {expected},但收到 {received}", "typeAssignmentMismatch": "无法将类型“{sourceType}”分配给类型“{destType}”", "typeBound": "类型\"{sourceType}\"与类型变量\"{destType}\"的绑定类型\"{name}\"不兼容", "typeConstrainedTypeVar": "类型\"{type}\"与受约束的类型变量\"{name}\"不兼容", diff --git a/packages/pyright-internal/src/localization/package.nls.zh-tw.json b/packages/pyright-internal/src/localization/package.nls.zh-tw.json index 0c2d6a679..86dbf8867 100644 --- a/packages/pyright-internal/src/localization/package.nls.zh-tw.json +++ b/packages/pyright-internal/src/localization/package.nls.zh-tw.json @@ -10,6 +10,10 @@ "organizeImports": "整理匯入", "renameShadowedFile": "將 \"{oldFile}\" 重新命名為 \"{newFile}\"" }, + "Completion": { + "autoImportDetail": "Auto-import", + "indexValueDetail": "Index value" + }, "Diagnostic": { "abstractMethodInvocation": "不能呼叫方法 \"{method}\",因為它是抽象", "annotatedParamCountMismatch": "參數註釋計數不符: 應為 {expected},但收到 {received}", @@ -323,7 +327,6 @@ "overloadAbstractMismatch": "多載方法必須全為抽象或不抽象", "overloadImplementationMismatch": "多載的實作與多載 {index} 的簽章不一致", "overloadReturnTypeMismatch": "\"{name}\" 的多載 {prevIndex} 與多載 {newIndex} 重疊,並傳回不相容的類型", - "overloadWithImplementation": "\"{name}\" 標示為多載,但包含實作", "overloadWithoutImplementation": "\"{name}\" 標示為多載,但未提供實作", "overriddenMethodNotFound": "方法 \"{name}\" 已標示為覆寫,但不存在相同名稱的基底方法", "overrideDecoratorMissing": "方法 \"{name}\" 未標示為覆寫,但正在覆寫類別 \"{className}\" 中的方法", @@ -417,7 +420,7 @@ "superCallArgCount": "\"super\" 呼叫不應有兩個以上的引數", "superCallFirstArg": "預期的類別類型為 \"super\" 呼叫的第一個引數,但收到 \"{type}\"", "superCallSecondArg": "\"super\" 呼叫的第二個引數必須是衍生自 \"{type}\" 的物件或類別", - "superCallZeroArgForm": "\"super\" 呼叫的零引數形式只在類別內有效", + "superCallZeroArgForm": "\"super\" 呼叫的零引數形式只在方法內有效", "symbolIsPossiblyUnbound": "\"{name}\" 可能未繫結", "symbolIsUnbound": "\"{name}\" 未繫結", "symbolIsUndefined": "\"{name}\" 未定義", @@ -452,6 +455,7 @@ "typeAssignmentMismatch": "類型 \"{sourceType}\" 的運算式不能指派至宣告的類型 \"{destType}\"", "typeAssignmentMismatchWildcard": "匯入符號 \"{name}\" 具有類型 \"{sourceType}\",無法指派給宣告的類型 \"{destType}\"", "typeCallNotAllowed": "不應在類型註釋中使用 type() 呼叫", + "typeCheckOnly": "\"{name}\" 已標示為 @type_check_only,只能在型別註釋中使用", "typeCommentDeprecated": "使用類型註解已取代; 請改為使用類型註釋", "typeExpectedClass": "預期為類型運算式,但收到 \"{type}\"", "typeGuardArgCount": "預期 \"TypeGuard\" 之後為單一類型引數", @@ -641,7 +645,6 @@ "orPatternMissingName": "遺失名稱: {name}", "overloadNotAssignable": "\"{name}\" 的一或多個多載無法指派", "overloadSignature": "多載簽章在這裡定義", - "overloadWithImplementation": "函式多載的本文應為 \"...\"", "overriddenMethod": "覆寫方法", "overriddenSymbol": "覆寫的符號", "overrideNoOverloadMatches": "覆寫中沒有任何多載簽章與基底方法相容", @@ -685,7 +688,8 @@ "seeVariableDeclaration": "請參閱變數宣告", "tupleAssignmentMismatch": "型別 \"{type}\" 與目標元組不相容", "tupleEntryTypeMismatch": "Tuple 項目 {entry} 的類型不正確", - "tupleSizeMismatch": "元素大小不符; 預期為 {expected} 但收到 {received}", + "tupleSizeIndeterminate": "元組大小不符; 預期為 {expected},但收到不確定的大小", + "tupleSizeMismatch": "元組大小不符; 預期為 {expected},但收到 {received}", "typeAssignmentMismatch": "類型 \"{sourceType}\" 不能指派至類型 \"{destType}\"", "typeBound": "類型 \"{sourceType}\" 與類型變數 \"{name}\" 的繫結類型 \"{destType}\" 不相容", "typeConstrainedTypeVar": "類型 \"{type}\" 與限制類型變數 \"{name}\" 不相容", diff --git a/packages/pyright-internal/src/server.ts b/packages/pyright-internal/src/server.ts index 57806d5bc..de19f2e40 100644 --- a/packages/pyright-internal/src/server.ts +++ b/packages/pyright-internal/src/server.ts @@ -29,15 +29,15 @@ import { expandPathVariables } from './common/envVarUtils'; import { FileBasedCancellationProvider } from './common/fileBasedCancellationUtils'; import { FullAccessHost } from './common/fullAccessHost'; import { Host } from './common/host'; -import { resolvePaths } from './common/pathUtils'; +import { realCasePath, resolvePaths } from './common/pathUtils'; import { ProgressReporter } from './common/progressReporter'; import { WorkspaceFileWatcherProvider, createFromRealFileSystem } from './common/realFileSystem'; +import { ServiceProvider } from './common/serviceProvider'; +import { createServiceProvider } from './common/serviceProviderExtensions'; import { LanguageServerBase, ServerSettings } from './languageServerBase'; import { CodeActionProvider } from './languageService/codeActionProvider'; -import { Workspace } from './workspaceFactory'; import { PyrightFileSystem } from './pyrightFileSystem'; -import { ServiceProvider } from './common/serviceProvider'; -import { createServiceProvider } from './common/serviceProviderExtensions'; +import { Workspace } from './workspaceFactory'; const maxAnalysisTimeInForeground = { openFilesTimeInMs: 50, noOpenFilesTimeInMs: 200 }; @@ -58,11 +58,12 @@ export class PyrightServer extends LanguageServerBase { const fileSystem = createFromRealFileSystem(console, fileWatcherProvider); const pyrightFs = new PyrightFileSystem(fileSystem); const serviceProvider = createServiceProvider(pyrightFs, console); + const realPathRoot = realCasePath(rootDirectory, pyrightFs); super( { productName: 'pyright-extended', - rootDirectory, + rootDirectory: realPathRoot, version, serviceProvider, fileWatcherHandler: fileWatcherProvider, diff --git a/packages/pyright-internal/src/tests/checker.test.ts b/packages/pyright-internal/src/tests/checker.test.ts index 6a6c0f445..0740cf1d9 100644 --- a/packages/pyright-internal/src/tests/checker.test.ts +++ b/packages/pyright-internal/src/tests/checker.test.ts @@ -551,11 +551,11 @@ test('Deprecated2', () => { const configOptions = new ConfigOptions('.'); const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['deprecated2.py'], configOptions); - TestUtils.validateResults(analysisResults1, 0, 0, 0, undefined, undefined, 6); + TestUtils.validateResults(analysisResults1, 0, 0, 0, undefined, undefined, 12); configOptions.diagnosticRuleSet.reportDeprecated = 'error'; const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['deprecated2.py'], configOptions); - TestUtils.validateResults(analysisResults2, 6); + TestUtils.validateResults(analysisResults2, 12); }); test('Deprecated3', () => { diff --git a/packages/pyright-internal/src/tests/completions.test.ts b/packages/pyright-internal/src/tests/completions.test.ts index cbf8ba6dc..47cb19700 100644 --- a/packages/pyright-internal/src/tests/completions.test.ts +++ b/packages/pyright-internal/src/tests/completions.test.ts @@ -1245,3 +1245,33 @@ test('TypeDict literal values', async () => { }, }); }); + +test('import from completion for namespace package', async () => { + const code = ` +// @filename: test.py +//// from nest1 import [|/*marker*/|] + +// @filename: nest1/nest2/__init__.py +//// # empty + +// @filename: nest1/module.py +//// # empty + `; + + const state = parseAndGetTestState(code).state; + + await state.verifyCompletion('included', 'markdown', { + ['marker']: { + completions: [ + { + label: 'nest2', + kind: CompletionItemKind.Module, + }, + { + label: 'module', + kind: CompletionItemKind.Module, + }, + ], + }, + }); +}); diff --git a/packages/pyright-internal/src/tests/config.test.ts b/packages/pyright-internal/src/tests/config.test.ts index 5869ad834..56d216862 100644 --- a/packages/pyright-internal/src/tests/config.test.ts +++ b/packages/pyright-internal/src/tests/config.test.ts @@ -14,7 +14,7 @@ import { CommandLineOptions } from '../common/commandLineOptions'; import { ConfigOptions, ExecutionEnvironment } from '../common/configOptions'; import { ConsoleInterface, NullConsole } from '../common/console'; import { NoAccessHost } from '../common/host'; -import { combinePaths, getBaseFileName, normalizePath, normalizeSlashes } from '../common/pathUtils'; +import { combinePaths, getBaseFileName, normalizePath, normalizeSlashes, realCasePath } from '../common/pathUtils'; import { PythonVersion } from '../common/pythonVersion'; import { createFromRealFileSystem } from '../common/realFileSystem'; import { TestFileSystem } from './harness/vfs/filesystem'; @@ -42,7 +42,7 @@ test('FindFilesWithConfigFile', () => { assert.strictEqual(configOptions.include.length, 1, `failed creating options from ${cwd}`); assert.strictEqual( normalizeSlashes(configOptions.projectRoot), - normalizeSlashes(combinePaths(cwd, commandLineOptions.configFilePath)) + realCasePath(combinePaths(cwd, commandLineOptions.configFilePath), service.fs) ); const fileList = service.test_getFileNamesFromFileSpecs(); @@ -133,7 +133,7 @@ test('SomeFileSpecsAreInvalid', () => { assert.strictEqual(configOptions.exclude.length, 1); assert.strictEqual( normalizeSlashes(configOptions.projectRoot), - normalizeSlashes(combinePaths(cwd, commandLineOptions.configFilePath)) + realCasePath(combinePaths(cwd, commandLineOptions.configFilePath), service.fs) ); const fileList = service.test_getFileNamesFromFileSpecs(); @@ -222,7 +222,7 @@ test('AutoSearchPathsOn', () => { const configOptions = service.test_getConfigOptions(commandLineOptions); - const expectedExtraPaths = [normalizePath(combinePaths(cwd, 'src'))]; + const expectedExtraPaths = [realCasePath(combinePaths(cwd, 'src'), service.fs)]; assert.deepStrictEqual(configOptions.defaultExtraPaths, expectedExtraPaths); }); @@ -282,8 +282,8 @@ test('AutoSearchPathsOnAndExtraPaths', () => { const configOptions = service.test_getConfigOptions(commandLineOptions); const expectedExtraPaths: string[] = [ - normalizePath(combinePaths(cwd, 'src')), - normalizePath(combinePaths(cwd, 'src', '_vendored')), + realCasePath(combinePaths(cwd, 'src'), service.fs), + realCasePath(combinePaths(cwd, 'src', '_vendored'), service.fs), ]; assert.deepStrictEqual(configOptions.defaultExtraPaths, expectedExtraPaths); diff --git a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.complex.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.complex.fourslash.ts index c9fcb2f8e..3de099e74 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.complex.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.complex.fourslash.ts @@ -33,31 +33,31 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"ifKey"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"ifKey"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"capturedKey"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"capturedKey"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"capturedInsideOfMethod"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"capturedInsideOfMethod"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"reassignedKey"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"reassignedKey"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, diff --git a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.expression.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.expression.fourslash.ts index a145ca86a..9e1eea266 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.expression.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.expression.fourslash.ts @@ -34,20 +34,20 @@ await helper.verifyCompletion('included', 'markdown', { marker1: { completions: [ - { label: '1', kind: Consts.CompletionItemKind.Constant, detail: 'Dictionary key' }, - { label: '2', kind: Consts.CompletionItemKind.Constant, detail: 'Dictionary key' }, + { label: '1', kind: Consts.CompletionItemKind.Constant, detail: Consts.IndexValueDetail }, + { label: '2', kind: Consts.CompletionItemKind.Constant, detail: Consts.IndexValueDetail }, ], }, marker2: { completions: [ - { label: '(1, 2)', kind: Consts.CompletionItemKind.Constant, detail: 'Dictionary key' }, - { label: '(2, 3)', kind: Consts.CompletionItemKind.Constant, detail: 'Dictionary key' }, + { label: '(1, 2)', kind: Consts.CompletionItemKind.Constant, detail: Consts.IndexValueDetail }, + { label: '(2, 3)', kind: Consts.CompletionItemKind.Constant, detail: Consts.IndexValueDetail }, ], }, marker3: { completions: [ - { label: '1 + 2', kind: Consts.CompletionItemKind.Constant, detail: 'Dictionary key' }, - { label: '2 + 3', kind: Consts.CompletionItemKind.Constant, detail: 'Dictionary key' }, + { label: '1 + 2', kind: Consts.CompletionItemKind.Constant, detail: Consts.IndexValueDetail }, + { label: '2 + 3', kind: Consts.CompletionItemKind.Constant, detail: Consts.IndexValueDetail }, ], }, marker4: { @@ -56,18 +56,20 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker4'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key2"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker4'), newText: '"key2"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, marker5: { - completions: [{ label: 'C.key', kind: Consts.CompletionItemKind.Constant, detail: 'Dictionary key' }], + completions: [ + { label: 'C.key', kind: Consts.CompletionItemKind.Constant, detail: Consts.IndexValueDetail }, + ], }, }); } diff --git a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.literalTypes.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.literalTypes.fourslash.ts index 91eb2d7f4..53be9cb14 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.literalTypes.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.literalTypes.fourslash.ts @@ -58,13 +58,13 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key2"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"key2"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -74,13 +74,13 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker2'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key2"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker2'), newText: '"key2"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -90,12 +90,12 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker3'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '1', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -105,13 +105,13 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker4'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key2"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker4'), newText: '"key2"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -120,12 +120,12 @@ { label: 'True', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: 'False', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -134,12 +134,12 @@ { label: 'MyEnum.red', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: 'MyEnum.blue', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -148,12 +148,12 @@ { label: 'b"key"', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: 'b"key2"', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, diff --git a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.simple.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.simple.fourslash.ts index 16f57c169..73af2b192 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.simple.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.simple.fourslash.ts @@ -49,7 +49,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -59,7 +59,7 @@ label: "'key'", kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker2'), newText: "'key'" }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -69,7 +69,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker3'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -79,7 +79,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker4'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -89,19 +89,19 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker5'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key2"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker5'), newText: '"key2"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key3"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker5'), newText: '"key3"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -111,19 +111,19 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker6'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key2"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker6'), newText: '"key2"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key3"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker6'), newText: '"key3"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -133,7 +133,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker7'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -143,7 +143,7 @@ label: "'key'", kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker8'), newText: "'key'" }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, diff --git a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.stringLiterals.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.stringLiterals.fourslash.ts index 285083232..97f13dcc6 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.stringLiterals.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.stringLiterals.fourslash.ts @@ -42,7 +42,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -52,7 +52,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker2'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -62,7 +62,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker3'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -72,7 +72,7 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker4'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -81,13 +81,13 @@ { label: 'name', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"key2"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker5'), newText: '"key2"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -98,7 +98,7 @@ label: '"keyString"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker6'), newText: '"keyString"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -108,12 +108,12 @@ label: '"key"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker7'), newText: '"key"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '1 + 2', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, diff --git a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.symbols.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.symbols.fourslash.ts index a0e7db725..f319f49f5 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.symbols.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.dictionary.keys.symbols.fourslash.ts @@ -25,7 +25,7 @@ label: '"key-1"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: '"key-1"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -35,7 +35,7 @@ label: '"key\\"yo\\""', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker2'), newText: '"key\\"yo\\""' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -45,7 +45,7 @@ label: '"hello"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker3'), newText: '"hello"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, diff --git a/packages/pyright-internal/src/tests/fourslash/completions.fstring.stringLiteral.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.fstring.stringLiteral.fourslash.ts index 2f3bf274b..eae83a9e1 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.fstring.stringLiteral.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.fstring.stringLiteral.fourslash.ts @@ -67,7 +67,7 @@ { label: "'name'", kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, textEdit: { range: helper.getPositionRange('marker4'), newText: "'name'" }, }, ], @@ -77,7 +77,7 @@ { label: '"name"', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, textEdit: { range: helper.getPositionRange('marker5'), newText: '"name"' }, }, ], @@ -87,7 +87,7 @@ { label: '"name"', kind: Consts.CompletionItemKind.Constant, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, textEdit: { range: helper.getPositionRange('marker6'), newText: '"name"' }, }, ], diff --git a/packages/pyright-internal/src/tests/fourslash/completions.indexer.keys.getitem.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/completions.indexer.keys.getitem.fourslash.ts index fd30981f7..c88e81ed3 100644 --- a/packages/pyright-internal/src/tests/fourslash/completions.indexer.keys.getitem.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/completions.indexer.keys.getitem.fourslash.ts @@ -27,13 +27,13 @@ label: "'a'", kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: "'a'" }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: "'b'", kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker1'), newText: "'b'" }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, @@ -43,13 +43,13 @@ label: '"a"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker2'), newText: '"a"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, { label: '"b"', kind: Consts.CompletionItemKind.Constant, textEdit: { range: helper.getPositionRange('marker2'), newText: '"b"' }, - detail: 'Dictionary key', + detail: Consts.IndexValueDetail, }, ], }, diff --git a/packages/pyright-internal/src/tests/fourslash/diagnostics.missingModuleSource.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/diagnostics.missingModuleSource.fourslash.ts index 9a5d53eb5..e0940efec 100644 --- a/packages/pyright-internal/src/tests/fourslash/diagnostics.missingModuleSource.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/diagnostics.missingModuleSource.fourslash.ts @@ -34,35 +34,35 @@ helper.verifyDiagnostics({ marker1: { category: 'warning', - message: 'Import "myLib.module" could not be resolved from source in the "python" environment.', + message: 'Import "myLib.module" could not be resolved from source', }, marker2: { category: 'warning', - message: 'Import "myLib.module" could not be resolved from source in the "python" environment.', + message: 'Import "myLib.module" could not be resolved from source', }, marker3: { category: 'warning', - message: 'Import "myLib.module" could not be resolved from source in the "python" environment.', + message: 'Import "myLib.module" could not be resolved from source', }, marker4: { category: 'warning', - message: 'Import ".conflict.module2" could not be resolved from source in the "python" environment.', + message: 'Import ".conflict.module2" could not be resolved from source', }, marker5: { category: 'warning', - message: 'Import ".conflict.module2" could not be resolved from source in the "python" environment.', + message: 'Import ".conflict.module2" could not be resolved from source', }, marker6: { category: 'warning', - message: 'Import "myLib.module" could not be resolved from source in the "python" environment.', + message: 'Import "myLib.module" could not be resolved from source', }, marker7: { category: 'warning', - message: 'Import "myLib.module" could not be resolved from source in the "python" environment.', + message: 'Import "myLib.module" could not be resolved from source', }, marker8: { category: 'warning', - message: 'Import ".conflict.module2" could not be resolved from source in the "python" environment.', + message: 'Import ".conflict.module2" could not be resolved from source', }, }); } diff --git a/packages/pyright-internal/src/tests/fourslash/fourslash.ts b/packages/pyright-internal/src/tests/fourslash/fourslash.ts index 429cfb9ee..ea9813142 100644 --- a/packages/pyright-internal/src/tests/fourslash/fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/fourslash.ts @@ -447,4 +447,6 @@ declare namespace Consts { } export type InlayHintKind = 1 | 2; + + export const IndexValueDetail = 'Index value'; } diff --git a/packages/pyright-internal/src/tests/fourslash/importnotresolved.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/importnotresolved.fourslash.ts index 261076ed2..36c2e54f3 100644 --- a/packages/pyright-internal/src/tests/fourslash/importnotresolved.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/importnotresolved.fourslash.ts @@ -8,6 +8,6 @@ //// helper.verifyDiagnostics({ - marker1: { category: 'error', message: `Import "notexistant" could not be found in the "python" environment.` }, - marker2: { category: 'error', message: `Import "django" could not be found in the "python" environment.` }, + marker1: { category: 'error', message: `Import "notexistant" could not be resolved` }, + marker2: { category: 'error', message: `Import "django" could not be resolved` }, }); diff --git a/packages/pyright-internal/src/tests/fourslash/missingModuleSource.fourslash.ts b/packages/pyright-internal/src/tests/fourslash/missingModuleSource.fourslash.ts index 2bc17eaaf..4e5b23d2e 100644 --- a/packages/pyright-internal/src/tests/fourslash/missingModuleSource.fourslash.ts +++ b/packages/pyright-internal/src/tests/fourslash/missingModuleSource.fourslash.ts @@ -12,6 +12,6 @@ helper.verifyDiagnostics({ marker1: { category: 'warning', - message: 'Import "pkg1234" could not be resolved from source in the "python" environment.', + message: 'Import "pkg1234" could not be resolved from source', }, }); diff --git a/packages/pyright-internal/src/tests/harness/fourslash/testState.Consts.ts b/packages/pyright-internal/src/tests/harness/fourslash/testState.Consts.ts index 450ded77b..3af0882d4 100644 --- a/packages/pyright-internal/src/tests/harness/fourslash/testState.Consts.ts +++ b/packages/pyright-internal/src/tests/harness/fourslash/testState.Consts.ts @@ -10,6 +10,7 @@ */ import * as lsp from 'vscode-languageserver'; +import { indexValueDetail } from '../../../languageService/completionProvider'; /* eslint-disable @typescript-eslint/no-unused-vars */ export namespace Consts { @@ -27,4 +28,6 @@ export namespace Consts { export import CompletionItemKind = lsp.CompletionItemKind; export import InlayHintKind = lsp.InlayHintKind; + + export const IndexValueDetail = indexValueDetail; } diff --git a/packages/pyright-internal/src/tests/harness/fourslash/testState.ts b/packages/pyright-internal/src/tests/harness/fourslash/testState.ts index 59af73bbf..23f828a5b 100644 --- a/packages/pyright-internal/src/tests/harness/fourslash/testState.ts +++ b/packages/pyright-internal/src/tests/harness/fourslash/testState.ts @@ -39,7 +39,6 @@ import { DiagnosticCategory } from '../../../common/diagnostic'; import { FileEditAction } from '../../../common/editAction'; import { combinePaths, - comparePaths, convertPathToUri, getDirectoryPath, getFileExtension, @@ -97,6 +96,7 @@ import { createVfsInfoFromFourSlashData, getMarkerByName, getMarkerName, getMark import { verifyWorkspaceEdit } from './workspaceEditTestUtils'; import { ServiceProvider } from '../../../common/serviceProvider'; import { createServiceProvider } from '../../../common/serviceProviderExtensions'; +import { compareStringsCaseInsensitive, compareStringsCaseSensitive } from '../../../common/stringUtils'; export interface TextChange { span: TextRange; @@ -1507,8 +1507,10 @@ export class TestState { } protected getFileContent(fileName: string): string { - const files = this.testData.files.filter( - (f) => comparePaths(f.fileName, fileName, this.testFS.ignoreCase) === Comparison.EqualTo + const files = this.testData.files.filter((f) => + this.testFS.ignoreCase + ? compareStringsCaseInsensitive(f.fileName, fileName) === Comparison.EqualTo + : compareStringsCaseSensitive(f.fileName, fileName) === Comparison.EqualTo ); return files[0].content; } diff --git a/packages/pyright-internal/src/tests/harness/vfs/filesystem.ts b/packages/pyright-internal/src/tests/harness/vfs/filesystem.ts index 8383a5bc9..7bd402ff9 100644 --- a/packages/pyright-internal/src/tests/harness/vfs/filesystem.ts +++ b/packages/pyright-internal/src/tests/harness/vfs/filesystem.ts @@ -16,6 +16,7 @@ import * as pathUtil from '../../../common/pathUtils'; import { bufferFrom, createIOError } from '../utils'; import { Metadata, SortedMap, closeIterator, getIterator, nextResult } from './../utils'; import { ValidationFlags, validate } from './pathValidation'; +import { compareStringsCaseInsensitive, compareStringsCaseSensitive } from '../../../common/stringUtils'; export const MODULE_PATH = pathUtil.normalizeSlashes('/'); @@ -75,9 +76,7 @@ export class TestFileSystem implements FileSystem { this._id = TestFileSystem._nextId++; const { time = -1, files, meta } = options; this.ignoreCase = ignoreCase; - this.stringComparer = this.ignoreCase - ? pathUtil.comparePathsCaseInsensitive - : pathUtil.comparePathsCaseSensitive; + this.stringComparer = this.ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; this._time = time; if (meta) { @@ -468,7 +467,7 @@ export class TestFileSystem implements FileSystem { for (let i = nextResult(iterator); i; i = nextResult(iterator)) { const [name, node] = i.value; const path = dirname ? pathUtil.combinePaths(dirname, name) : name; - const marker = pathUtil.comparePaths(this._cwd, path, this.ignoreCase) === 0 ? '*' : ' '; + const marker = this.stringComparer(this._cwd, path) === 0 ? '*' : ' '; if (result) { addToResult(path, '\n'); } @@ -788,8 +787,12 @@ export class TestFileSystem implements FileSystem { * NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module. */ realpathSync(path: string) { - const { realpath } = this._walk(this._resolve(path)); - return realpath; + try { + const { realpath } = this._walk(this._resolve(path)); + return realpath; + } catch (e: any) { + return path; + } } /** diff --git a/packages/pyright-internal/src/tests/pathUtils.test.ts b/packages/pyright-internal/src/tests/pathUtils.test.ts index 212166667..4870a9714 100644 --- a/packages/pyright-internal/src/tests/pathUtils.test.ts +++ b/packages/pyright-internal/src/tests/pathUtils.test.ts @@ -10,16 +10,13 @@ import assert from 'assert'; import * as os from 'os'; import * as path from 'path'; +import * as nodefs from 'fs-extra'; -import { Comparison } from '../common/core'; import { expandPathVariables } from '../common/envVarUtils'; import { changeAnyExtension, combinePathComponents, combinePaths, - comparePaths, - comparePathsCaseInsensitive, - comparePathsCaseSensitive, containsPath, convertUriToPath, deduplicateFolders, @@ -44,6 +41,7 @@ import { stripTrailingDirectorySeparator, } from '../common/pathUtils'; import * as vfs from './harness/vfs/filesystem'; +import { createFromRealFileSystem } from '../common/realFileSystem'; test('getPathComponents1', () => { const components = getPathComponents(''); @@ -257,26 +255,6 @@ test('invalid ~ with root', () => { assert.equal(resolvePaths(expandPathVariables('/src', path)), path); }); -test('comparePaths1', () => { - assert.equal(comparePaths('/A/B/C', '\\a\\b\\c'), Comparison.LessThan); -}); - -test('comparePaths2', () => { - assert.equal(comparePaths('/A/B/C', '\\a\\b\\c', true), Comparison.EqualTo); -}); - -test('comparePaths3', () => { - assert.equal(comparePaths('/A/B/C', '/a/c/../b/./c', true), Comparison.EqualTo); -}); - -test('comparePaths4', () => { - assert.equal(comparePaths('/a/b/c', '/a/c/../b/./c', 'current\\path\\', false), Comparison.EqualTo); -}); - -test('comparePaths5', () => { - assert.equal(comparePaths('/a/b/c/', '/a/b/c'), Comparison.EqualTo); -}); - test('containsPath1', () => { assert.equal(containsPath('/a/b/c/', '/a/d/../b/c/./d'), true); }); @@ -337,14 +315,6 @@ test('getRelativePathFromDirectory2', () => { assert.equal(getRelativePathFromDirectory('/a', '/b/c/d', true), normalizeSlashes('../b/c/d')); }); -test('comparePathsCaseSensitive', () => { - assert.equal(comparePathsCaseSensitive('/a/b/C', '/a/b/c'), Comparison.LessThan); -}); - -test('comparePathsCaseInsensitive', () => { - assert.equal(comparePathsCaseInsensitive('/a/b/C', '/a/b/c'), Comparison.EqualTo); -}); - test('isRootedDiskPath1', () => { assert(isRootedDiskPath(normalizeSlashes('C:/a/b'))); }); @@ -416,3 +386,16 @@ test('convert UNC path', () => { // When converting UNC path, server part shouldn't be removed. assert(path.indexOf('server') > 0); }); + +test('Realcase', () => { + const fs = createFromRealFileSystem(); + const cwd = process.cwd(); + const dir = path.join(cwd, 'src', 'tests'); + const entries = nodefs.readdirSync(dir).map((entry) => path.basename(nodefs.realpathSync(path.join(dir, entry)))); + const fsentries = fs.readdirSync(dir); + assert.deepStrictEqual(entries, fsentries); + + const paths = entries.map((entry) => nodefs.realpathSync(path.join(dir, entry))); + const fspaths = fsentries.map((entry) => fs.realCasePath(path.join(dir, entry))); + assert.deepStrictEqual(paths, fspaths); +}); diff --git a/packages/pyright-internal/src/tests/samples/await2.py b/packages/pyright-internal/src/tests/samples/await2.py index 6b3e0724c..af70bd068 100644 --- a/packages/pyright-internal/src/tests/samples/await2.py +++ b/packages/pyright-internal/src/tests/samples/await2.py @@ -2,7 +2,7 @@ # awaited. import asyncio -from typing import Generator, Any +from typing import Generator, Any, NoReturn class MyAwaitable: @@ -16,10 +16,17 @@ async def foo(self) -> int: return await self -async def main() -> None: +async def func1() -> None: p = MyAwaitable() print(await p.foo()) print(await p) -asyncio.run(main()) +async def func2() -> NoReturn: + raise Exception() + + +async def func3(x: int | None): + if x is None: + await func2() + print(x.bit_count()) diff --git a/packages/pyright-internal/src/tests/samples/classes5.py b/packages/pyright-internal/src/tests/samples/classes5.py index 5ca58761d..cfa26dde4 100644 --- a/packages/pyright-internal/src/tests/samples/classes5.py +++ b/packages/pyright-internal/src/tests/samples/classes5.py @@ -49,6 +49,8 @@ class Subclass1(ParentClass1): var2: str + # This should generate an error if reportIncompatibleVariableOverride is + # enabled because the member is mutable, and is therefore invariant. var3: int # This should generate an error. @@ -119,7 +121,7 @@ def __init__(self): class SubclassDeclared2(ParentClass2): - cv_decl_1: int + cv_decl_1: float # This should generate an error if reportIncompatibleVariableOverride # is enabled. @@ -134,6 +136,8 @@ class SubclassDeclared2(ParentClass2): cv_infer_3: float | None def __init__(self): + # This should generate an error if reportIncompatibleVariableOverride + # is enabled because the member is mutable and therefore invariant. self.cv_decl_4: int # This should generate an error if reportIncompatibleVariableOverride @@ -241,6 +245,7 @@ def test3(self) -> int: test4: int test5: Any test6: float + test7: float class PeerClass2: @@ -254,9 +259,10 @@ def test4(self) -> int: test5: int test6: Any + test7: int -# This should generate 3 errors if reportIncompatibleVariableOverride +# This should generate 4 errors if reportIncompatibleVariableOverride # is enabled. class MultipleInheritance1(PeerClass1, PeerClass2): pass diff --git a/packages/pyright-internal/src/tests/samples/comparison2.py b/packages/pyright-internal/src/tests/samples/comparison2.py index a070cf031..bdcf957f8 100644 --- a/packages/pyright-internal/src/tests/samples/comparison2.py +++ b/packages/pyright-internal/src/tests/samples/comparison2.py @@ -67,3 +67,13 @@ def func3(x: DC1): # This should generate an error if reportUnnecessaryComparison is enabled. if x == 42: ... + + +async def func4() -> bool: + return True + + +async def func5() -> None: + # This should generate an error if reportUnnecessaryComparison is enabled. + if func4(): + pass diff --git a/packages/pyright-internal/src/tests/samples/constructor28.py b/packages/pyright-internal/src/tests/samples/constructor28.py index b0d69a535..f84fb1eb4 100644 --- a/packages/pyright-internal/src/tests/samples/constructor28.py +++ b/packages/pyright-internal/src/tests/samples/constructor28.py @@ -4,7 +4,7 @@ # pyright: strict from __future__ import annotations -from typing import Any, Callable, Generic, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, TypeVar, overload T = TypeVar("T") S = TypeVar("S", covariant=True) @@ -76,3 +76,7 @@ def __call__(self, obj: Any) -> Any: func3(ClassD(""), ClassD("")) + + +def func4(a: Iterable[tuple[str, ...]]): + zip(a, zip(*a)) diff --git a/packages/pyright-internal/src/tests/samples/constructor29.py b/packages/pyright-internal/src/tests/samples/constructor29.py new file mode 100644 index 000000000..758518c36 --- /dev/null +++ b/packages/pyright-internal/src/tests/samples/constructor29.py @@ -0,0 +1,18 @@ +# This sample tests the case where a constructor for a generic class is +# called with a bidirectional type inference context that includes a union +# of multiple types that could apply. + +from typing import Mapping + + +d1: dict[str, str] | dict[int, int] = dict() +reveal_type(d1, expected_text="dict[int, int]") + +d2: dict[int, int] | dict[str, str] = dict() +reveal_type(d2, expected_text="dict[int, int]") + +d3: Mapping[int, int] | Mapping[str, str] | int | float = dict() +reveal_type(d3, expected_text="dict[int, int]") + +d4: dict[str, str] | dict[int, int] = dict(a="hi") +reveal_type(d4, expected_text="dict[str, str]") diff --git a/packages/pyright-internal/src/tests/samples/dataclassHash1.py b/packages/pyright-internal/src/tests/samples/dataclassHash1.py index 0ce0a11a3..18d741f08 100644 --- a/packages/pyright-internal/src/tests/samples/dataclassHash1.py +++ b/packages/pyright-internal/src/tests/samples/dataclassHash1.py @@ -55,3 +55,14 @@ def __hash__(self) -> int: v6: Hashable = DC6(0) + + +@dataclass(frozen=True) +class DC7: + a: int + + def __eq__(self, other) -> bool: + return self.a == other.a + + +v7: Hashable = DC7(0) diff --git a/packages/pyright-internal/src/tests/samples/deprecated2.py b/packages/pyright-internal/src/tests/samples/deprecated2.py index a5f2e324b..212a9c7dc 100644 --- a/packages/pyright-internal/src/tests/samples/deprecated2.py +++ b/packages/pyright-internal/src/tests/samples/deprecated2.py @@ -1,5 +1,7 @@ # This sample tests the @typing.deprecated decorator introduced in PEP 702. +from typing import Any, Callable, TypeVar +from contextlib import contextmanager from typing_extensions import deprecated, overload @@ -89,3 +91,81 @@ def __init__(self, x: int | str) -> None: # This should generate an error if reportDeprecated is enabled. ClassD("") + + +@deprecated("Deprecated async function") +async def func3(): + ... + + +async def func4(): + # This should generate an error if reportDeprecated is enabled. + await func3() + + +@overload +def func5(val: int): + ... + + +@overload +def func5(val: str): + ... + + +@deprecated("All overloads are deprecated") +def func5(val: object): + ... + + +# This should generate an error if reportDeprecated is enabled. +func5(1) + +# This should generate an error if reportDeprecated is enabled. +func5("") + + +T = TypeVar("T", bound=Callable[..., Any]) + + +@deprecated("Use different decorator") +@overload +def deco1(value: T) -> T: + ... + + +@overload +def deco1(value: str): + ... + + +def deco1(value: object) -> object: + ... + + +# This should generate an error if reportDeprecated is enabled. +@deco1 +def func6(): + ... + + +@contextmanager +@deprecated("Func is deprecated") +def func7(): + yield + + +# This should generate an error if reportDeprecated is enabled. +with func7(): + ... + + +@deprecated("Func is deprecated") +@contextmanager +def func8(): + yield + + +# This should generate an error if reportDeprecated is enabled. +with func8(): + ... diff --git a/packages/pyright-internal/src/tests/samples/final3.py b/packages/pyright-internal/src/tests/samples/final3.py index 78def229c..ecc4549c5 100644 --- a/packages/pyright-internal/src/tests/samples/final3.py +++ b/packages/pyright-internal/src/tests/samples/final3.py @@ -2,7 +2,7 @@ # introduced in Python 3.8. import typing -from typing import Any, Final +from typing import Any, Final, Protocol foo1: typing.Final = 3 @@ -177,3 +177,7 @@ def __init__(self): def method1(self): # This should generate an error because x is Final. self.x += 1 + + +class ClassC(Protocol): + x: Final[int] diff --git a/packages/pyright-internal/src/tests/samples/generator1.py b/packages/pyright-internal/src/tests/samples/generator1.py index 162e7e6a3..4f647b882 100644 --- a/packages/pyright-internal/src/tests/samples/generator1.py +++ b/packages/pyright-internal/src/tests/samples/generator1.py @@ -95,17 +95,20 @@ def generator8() -> Iterator[dict[str, int]]: # This should generate an error. def generator9() -> int: + # This should generate an error. yield None return 3 # This should generate an error. async def generator10() -> int: + # This should generate an error. yield None # This should generate an error. def generator11() -> list[int]: + # This should generate an error. yield 3 diff --git a/packages/pyright-internal/src/tests/samples/matchMapping1.py b/packages/pyright-internal/src/tests/samples/matchMapping1.py index 5c8b0e91f..ef9eb01b5 100644 --- a/packages/pyright-internal/src/tests/samples/matchMapping1.py +++ b/packages/pyright-internal/src/tests/samples/matchMapping1.py @@ -13,6 +13,14 @@ def test_unknown(value_to_match): reveal_type(value_to_match, expected_text="Unknown") +def test_object(value_to_match: object): + match value_to_match: + case {"hello": a1, **a2}: + reveal_type(a1, expected_text="Unknown") + reveal_type(a2, expected_text="dict[Unknown, Unknown]") + reveal_type(value_to_match, expected_text="object") + + def test_dict(value_to_match: dict[str | int, str | int]): match value_to_match: case {1: a1}: diff --git a/packages/pyright-internal/src/tests/samples/metaclass11.py b/packages/pyright-internal/src/tests/samples/metaclass11.py new file mode 100644 index 000000000..976d6e2c2 --- /dev/null +++ b/packages/pyright-internal/src/tests/samples/metaclass11.py @@ -0,0 +1,29 @@ +# This sample verifies that the type checker allows access +# to instance variables provided by a metaclass. + +from enum import Enum +from typing import Mapping + + +class Meta(type): + var0 = 3 + + def __init__(cls, name, bases, dct): + cls.var1 = "hi" + + +class MyClass(metaclass=Meta): + pass + + +# This should generate an error because var0 isn't +# accessible via an instance of this class. +MyClass().var0 +reveal_type(MyClass.var0, expected_text="int") +MyClass.var0 = 1 + +reveal_type(MyClass().var1, expected_text="str") +reveal_type(MyClass.var1, expected_text="str") + +MyClass.var1 = "hi" +MyClass().var1 = "hi" diff --git a/packages/pyright-internal/src/tests/samples/overload9.py b/packages/pyright-internal/src/tests/samples/overload9.py deleted file mode 100644 index 0c89d9f31..000000000 --- a/packages/pyright-internal/src/tests/samples/overload9.py +++ /dev/null @@ -1,19 +0,0 @@ -# This sample tests that a diagnostic is emitted when an overload -# function contains an implementation. - -from typing import Union, overload - - -@overload -def func1(x: int) -> int: - ... - - -# This should generate an error. -@overload -def func1(x: str) -> str: - return x - - -def func1(x: Union[int, str]) -> Union[int, str]: - return x diff --git a/packages/pyright-internal/src/tests/samples/paramSpec37.py b/packages/pyright-internal/src/tests/samples/paramSpec37.py index 9491acf3f..269d04dd3 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec37.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec37.py @@ -19,10 +19,10 @@ def noop(v: T) -> T: def func1(maker: Callable[P, R]) -> ClassA[R]: def inner(n: int, /, *args: P.args, **kwargs: P.kwargs) -> list[R]: - reveal_type(args, expected_text="P.args") - reveal_type(noop(args), expected_text="P.args") - reveal_type(kwargs, expected_text="P.kwargs") - reveal_type(noop(kwargs), expected_text="P.kwargs") + reveal_type(args, expected_text="P@func1.args") + reveal_type(noop(args), expected_text="P@func1.args") + reveal_type(kwargs, expected_text="P@func1.kwargs") + reveal_type(noop(kwargs), expected_text="P@func1.kwargs") return [maker(*args, **kwargs) for _ in range(n)] diff --git a/packages/pyright-internal/src/tests/samples/paramSpec48.py b/packages/pyright-internal/src/tests/samples/paramSpec48.py new file mode 100644 index 000000000..225c7b1fe --- /dev/null +++ b/packages/pyright-internal/src/tests/samples/paramSpec48.py @@ -0,0 +1,15 @@ +# This sample tests the case where a function with a ParamSpec is called +# with *args and **kwargs that are defined as Any. + +from typing import Any, Callable, Concatenate, ParamSpec + + +P = ParamSpec("P") + + +def func3(f: Callable[Concatenate[int, P], int], *args: Any, **kwargs: Any) -> int: + return f(*args, **kwargs) + + +def func4(f: Callable[Concatenate[int, ...], int], *args: Any, **kwargs: Any) -> int: + return f(*args, **kwargs) diff --git a/packages/pyright-internal/src/tests/samples/tuple1.py b/packages/pyright-internal/src/tests/samples/tuple1.py index 304056221..390e376f3 100644 --- a/packages/pyright-internal/src/tests/samples/tuple1.py +++ b/packages/pyright-internal/src/tests/samples/tuple1.py @@ -174,10 +174,9 @@ def func13( v10 = d[0] - # This should generate one error. v11 = d[1] - # This should generate two errors. + # This should generate an error. v12 = d[2] v13: tuple[()] = () diff --git a/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py b/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py index eaa3b8949..15eb4be15 100644 --- a/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py +++ b/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py @@ -14,7 +14,8 @@ # This should generate an error. v1 = function -# This should generate an error. +# This should generate an error, but it doesn't because +# of a typeshed issue. v2 = isinstance(1, ellipsis) # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py index fe94c4dd6..c998a0212 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py @@ -1,7 +1,7 @@ # This sample exercises the type analyzer's isinstance type narrowing logic. from types import NoneType -from typing import Generic, Sized, TypeVar, Union, Any +from typing import Generic, Protocol, Sized, TypeVar, Union, Any, runtime_checkable S = TypeVar("S") T = TypeVar("T") @@ -179,3 +179,22 @@ class Sub2(Base2[T, T]): def func10(val: Sub2[str] | Base2[str, float]): if isinstance(val, Sub2): reveal_type(val, expected_text="Sub2[str] | Sub2[Unknown]") + + +@runtime_checkable +class Proto1(Protocol): + def f0(self, /) -> None: + ... + + +@runtime_checkable +class Proto2(Proto1, Protocol): + def f1(self, /) -> None: + ... + + +def func11(x: Proto1): + if isinstance(x, Proto2): + reveal_type(x, expected_text="Proto2") + else: + reveal_type(x, expected_text="Proto1") diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance4.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance4.py index 7dc7804d8..427acd9e7 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance4.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance4.py @@ -1,43 +1,45 @@ # This sample checks the handling of callable types that are narrowed # to a particular type using an isinstance type narrowing test. -from typing import Callable, Protocol, Union, runtime_checkable +from typing import Callable, ParamSpec, Protocol, Union, runtime_checkable +P = ParamSpec("P") -class Foo: + +class ClassA: def __call__(self, arg: int, bar: str) -> None: raise NotImplementedError @runtime_checkable -class Bar(Protocol): +class ClassB(Protocol): def __call__(self, arg: int) -> None: raise NotImplementedError @runtime_checkable -class Baz(Protocol): +class ClassC(Protocol): def __call__(self, arg: str) -> None: raise NotImplementedError def check_callable1(val: Union[Callable[[int, str], None], Callable[[int], None]]): - if isinstance(val, Foo): - reveal_type(val, expected_text="Foo") + if isinstance(val, ClassA): + reveal_type(val, expected_text="ClassA") else: # This doesn't get narrowed because `Foo` is not a runtime checkable protocol. reveal_type(val, expected_text="((int, str) -> None) | ((int) -> None)") def check_callable2(val: Union[Callable[[int, str], None], Callable[[int], None]]): - if isinstance(val, Bar): - reveal_type(val, expected_text="Bar") + if isinstance(val, ClassB): + reveal_type(val, expected_text="ClassB") else: reveal_type(val, expected_text="(int, str) -> None") def check_callable3(val: Union[Callable[[int, str], None], Callable[[int], None]]): - if isinstance(val, Baz): + if isinstance(val, ClassC): reveal_type(val, expected_text="Never") else: reveal_type(val, expected_text="((int, str) -> None) | ((int) -> None)") @@ -48,3 +50,10 @@ def check_callable4(val: Union[type, Callable[[int], None]]): reveal_type(val, expected_text="type") else: reveal_type(val, expected_text="(int) -> None") + + +def check_callable5(fn: Callable[P, None]) -> None: + if isinstance(fn, ClassA): + reveal_type(fn, expected_text="ClassA") + else: + reveal_type(fn, expected_text="(**P@check_callable5) -> None") diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingTupleLength1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingTupleLength1.py index 3d1e503ee..0136908c3 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingTupleLength1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingTupleLength1.py @@ -17,14 +17,14 @@ def func1(val: tuple[int] | tuple[int, int] | tuple[str, str]): def func2(val: tuple[int] | tuple[int, ...]): if len(val) == 1: - reveal_type(val, expected_text="tuple[int] | tuple[int, ...]") + reveal_type(val, expected_text="tuple[int]") else: reveal_type(val, expected_text="tuple[int, ...]") if len(val) != 2: reveal_type(val, expected_text="tuple[int] | tuple[int, ...]") else: - reveal_type(val, expected_text="tuple[int, ...]") + reveal_type(val, expected_text="tuple[int, int]") def func3(val: tuple[int] | tuple[()]): @@ -45,3 +45,21 @@ def func4(val: _T1 | _T2) -> _T1 | _T2: reveal_type(val, expected_text="_T2@func4") return val + + +def func5( + val: tuple[int, ...] + | tuple[str] + | tuple[str, str, str] + | tuple[int, *tuple[str, ...], str] + | tuple[int, *tuple[float, ...]] +): + if len(val) == 2: + reveal_type( + val, expected_text="tuple[int, int] | tuple[int, str] | tuple[int, float]" + ) + else: + reveal_type( + val, + expected_text="tuple[int, ...] | tuple[str] | tuple[str, str, str] | tuple[int, *tuple[str, ...], str] | tuple[int, *tuple[float, ...]]", + ) diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefault3.py b/packages/pyright-internal/src/tests/samples/typeVarDefault3.py index d573d33f2..9fc379692 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefault3.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefault3.py @@ -5,23 +5,34 @@ from typing_extensions import TypeVar +T0 = TypeVar("T0", default=object) T1 = TypeVar("T1") T2 = TypeVar("T2", default=str) + # This should generate an error because T1 is after T2. -class ClassA(Generic[T2, T1]): ... +class ClassA(Generic[T2, T1]): + ... + # This should generate an error because T1 is after T2. -class ClassB(dict[T2, T1]): ... +class ClassB(dict[T2, T1]): + ... -class ClassC(dict[T2, T1], Generic[T1, T2]): ... + +class ClassC(dict[T2, T1], Generic[T1, T2]): + ... # This should generate an error because T1 is after T2. def funcA(a: T2, b: T1) -> T1 | T2: ... + # This should generate an error because T1 is after T2. TA_A = dict[T2, T1] +class ClassD(Generic[T0]): + def method1(self, a: T0, b: T1, /) -> T0 | T1: + ... diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass1.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass1.py index 200c427c5..723689c2e 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass1.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass1.py @@ -2,7 +2,7 @@ # In particular, it tests the handling of default TypeVar types for # generic classes. -from typing import Generic +from typing import Generic, Self from typing_extensions import TypeVar, ParamSpec, TypeVarTuple, Unpack @@ -12,7 +12,13 @@ class ClassA1(Generic[T2, T3]): - ... + def method1(self) -> Self: + return self + + +reveal_type( + ClassA1.method1, expected_text="(self: ClassA1[int, str]) -> ClassA1[int, str]" +) def func_a1(a: ClassA1, b: ClassA1[float], c: ClassA1[float, float]): @@ -22,7 +28,14 @@ def func_a1(a: ClassA1, b: ClassA1[float], c: ClassA1[float, float]): class ClassA2(Generic[T1, T2, T3]): - ... + def method1(self) -> Self: + return self + + +reveal_type( + ClassA2[int].method1, + expected_text="(self: ClassA2[int, int, str]) -> ClassA2[int, int, str]", +) def func_a2( diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py index 43d3b0963..4539ac93d 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py @@ -1,7 +1,7 @@ # This sample tests the case where a TypeVar default refers to another # TypeVar in a class declaration. This sample uses classic TypeVar syntax. -# If you make a change to this file, reflect the change in typeVarDefault7 -# which uses PEP 695 syntax. +# If you make a change to this file, reflect the change in +# typeVarDefaultClass3.py, which uses PEP 695 syntax. from typing import Generic, ParamSpec, TypeVar, TypeVarTuple, Unpack diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py index 451523004..2f6eaa6c9 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py @@ -1,10 +1,19 @@ # This sample tests the case where a TypeVar default refers to another # TypeVar in a class declaration. This sample uses PEP 695 syntax. -from typing import Unpack +from typing import Self, Unpack -class ClassA[T1=str, T2=T1](dict[T1, T2]): ... +class ClassA[T1=str, T2=T1](dict[T1, T2]): + def method1(self) -> Self: + return self + +reveal_type( + ClassA[int].method1, expected_text="(self: ClassA[int, int]) -> ClassA[int, int]" +) +reveal_type( + ClassA.method1, expected_text="(self: ClassA[str, str]) -> ClassA[str, str]" +) a1 = ClassA[int]() reveal_type(a1, expected_text="ClassA[int, int]") diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction1.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction1.py index 5b766b832..eda26b69d 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction1.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction1.py @@ -55,3 +55,7 @@ def func3(x: int | Callable[[*Ts], None]) -> tuple[*Ts]: v3_2 = func3(3) reveal_type(v3_2, expected_text="tuple[int, str, float]") + + +P2 = ParamSpec("P2", default=...) +P3 = ParamSpec("P3", default="...") diff --git a/packages/pyright-internal/src/tests/samples/typedDict1.py b/packages/pyright-internal/src/tests/samples/typedDict1.py index f7ff684a1..9ddc356fd 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict1.py +++ b/packages/pyright-internal/src/tests/samples/typedDict1.py @@ -62,3 +62,9 @@ class NotATD: # base classes shouldn't be allowed for TD classes. class TD6(TD3, NotATD): pass + + +# This should generate an error because non-TypeDict +# base classes shouldn't be allowed for TD classes. +class TD7(NotATD, TypedDict): + pass diff --git a/packages/pyright-internal/src/tests/samples/typedDict12.py b/packages/pyright-internal/src/tests/samples/typedDict12.py index 96a68ab36..2bceaf4b1 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict12.py +++ b/packages/pyright-internal/src/tests/samples/typedDict12.py @@ -1,7 +1,7 @@ # This sample tests the synthesized methods get, setdefault # pop, __delitem__, clear, and popitem for a TypedDict. -from typing import TypedDict, Union, final +from typing import TypedDict, final from typing_extensions import NotRequired, Required @@ -20,7 +20,7 @@ class TD2(TD1): v2: str = td1.get("bar", "") -v3: Union[str, int] = td1.get("bar", 3) +v3: str | int = td1.get("bar", 3) v4: str = td1.setdefault("bar", "1") @@ -34,8 +34,8 @@ class TD2(TD1): td1.setdefault("baz", "") v6: str = td1.pop("bar") -v7: str = td1.pop("bar", "none") -v8: Union[str, int] = td1.pop("bar", 3) +v7: str | int = td1.pop("bar", 1) +v8: str | int = td1.pop("bar", 3) # This should generate an error. v9: str = td2.pop("foo") @@ -53,7 +53,7 @@ class TD4(TypedDict): bar: str -C = Union[TD3, TD4] +C = TD3 | TD4 def func1(a: TD3, b: TD4, c: C, s: str) -> int | None: diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py index cad6e53c1..c12179fa4 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py @@ -20,3 +20,7 @@ def method(self) -> Union[*Ts]: reveal_type(a1.method(), expected_text="int | bool | str") reveal_type(a1.x, expected_text="list[int | bool | str]") + + +def func1(t0: tuple[*Ts], t1: tuple[*Ts]): + return all(v0 == v1 for v0, v1 in zip(t0, t1)) diff --git a/packages/pyright-internal/src/tests/testState.test.ts b/packages/pyright-internal/src/tests/testState.test.ts index 3f0fa91de..2836ea2e8 100644 --- a/packages/pyright-internal/src/tests/testState.test.ts +++ b/packages/pyright-internal/src/tests/testState.test.ts @@ -8,7 +8,7 @@ import assert from 'assert'; -import { combinePaths, comparePathsCaseSensitive, getFileName, normalizeSlashes } from '../common/pathUtils'; +import { combinePaths, getFileName, normalizeSlashes } from '../common/pathUtils'; import { compareStringsCaseSensitive } from '../common/stringUtils'; import { Range } from './harness/fourslash/fourSlashTypes'; import { runFourSlashTestContent } from './harness/fourslash/runner'; @@ -261,7 +261,7 @@ test('Markers', () => { .getMarkers() .map((m) => state.getMarkerName(m)) .sort(compareStringsCaseSensitive), - state.getMarkerNames().sort(comparePathsCaseSensitive) + state.getMarkerNames().sort(compareStringsCaseSensitive) ); }); diff --git a/packages/pyright-internal/src/tests/typeEvaluator1.test.ts b/packages/pyright-internal/src/tests/typeEvaluator1.test.ts index 5b945111a..32a630df2 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator1.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator1.test.ts @@ -1239,7 +1239,7 @@ test('Optional2', () => { test('Tuple1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['tuple1.py']); - TestUtils.validateResults(analysisResults, 17); + TestUtils.validateResults(analysisResults, 15); }); test('Tuple2', () => { diff --git a/packages/pyright-internal/src/tests/typeEvaluator2.test.ts b/packages/pyright-internal/src/tests/typeEvaluator2.test.ts index 4d07c4d29..5f011091a 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator2.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator2.test.ts @@ -1320,7 +1320,7 @@ test('Protocol44', () => { test('TypedDict1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typedDict1.py']); - TestUtils.validateResults(analysisResults, 6); + TestUtils.validateResults(analysisResults, 7); }); test('TypedDict2', () => { diff --git a/packages/pyright-internal/src/tests/typeEvaluator3.test.ts b/packages/pyright-internal/src/tests/typeEvaluator3.test.ts index 7c35fc7f2..9843ce275 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator3.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator3.test.ts @@ -33,7 +33,7 @@ test('Ellipsis1', () => { test('Generator1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['generator1.py']); - TestUtils.validateResults(analysisResults, 9); + TestUtils.validateResults(analysisResults, 12); }); test('Generator2', () => { @@ -760,7 +760,7 @@ test('Classes5', () => { // Turn on reportIncompatibleVariableOverride. configOptions.diagnosticRuleSet.reportIncompatibleVariableOverride = 'error'; analysisResults = TestUtils.typeAnalyzeSampleFiles(['classes5.py'], configOptions); - TestUtils.validateResults(analysisResults, 32); + TestUtils.validateResults(analysisResults, 36); }); test('Classes6', () => { @@ -1331,7 +1331,7 @@ test('Comparison2', () => { configOptions.diagnosticRuleSet.reportUnnecessaryComparison = 'error'; const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['comparison2.py'], configOptions); - TestUtils.validateResults(analysisResults2, 10); + TestUtils.validateResults(analysisResults2, 11); }); test('EmptyContainers1', () => { @@ -1537,6 +1537,12 @@ test('Constructor28', () => { TestUtils.validateResults(analysisResults, 0); }); +test('Constructor29', () => { + const analysisResults = TestUtils.typeAnalyzeSampleFiles(['constructor29.py']); + + TestUtils.validateResults(analysisResults, 0); +}); + test('InconsistentConstructor1', () => { const configOptions = new ConfigOptions('.'); diff --git a/packages/pyright-internal/src/tests/typeEvaluator4.test.ts b/packages/pyright-internal/src/tests/typeEvaluator4.test.ts index 3f4c58fd6..aa3ee5857 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator4.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator4.test.ts @@ -91,6 +91,11 @@ test('Metaclass10', () => { TestUtils.validateResults(analysisResults, 0); }); +test('Metaclass11', () => { + const analysisResults = TestUtils.typeAnalyzeSampleFiles(['metaclass11.py']); + TestUtils.validateResults(analysisResults, 1); +}); + test('AssignmentExpr1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['assignmentExpr1.py']); TestUtils.validateResults(analysisResults, 7); @@ -309,11 +314,6 @@ test('Overload8', () => { TestUtils.validateResults(analysisResults, 2); }); -test('Overload9', () => { - const analysisResults = TestUtils.typeAnalyzeSampleFiles(['overload9.py']); - TestUtils.validateResults(analysisResults, 1); -}); - test('Overload10', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['overload10.py']); TestUtils.validateResults(analysisResults, 1); @@ -1074,6 +1074,11 @@ test('ParamSpec47', () => { TestUtils.validateResults(results, 2); }); +test('ParamSpec48', () => { + const results = TestUtils.typeAnalyzeSampleFiles(['paramSpec48.py']); + TestUtils.validateResults(results, 0); +}); + test('ClassVar1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['classVar1.py']); diff --git a/packages/pyright-internal/src/tests/typeEvaluator5.test.ts b/packages/pyright-internal/src/tests/typeEvaluator5.test.ts index 63887fbe7..eb1f50c61 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator5.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator5.test.ts @@ -181,7 +181,7 @@ test('TypeVarDefault2', () => { configOptions.defaultPythonVersion = PythonVersion.V3_13; const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typeVarDefault2.py'], configOptions); - TestUtils.validateResults(analysisResults, 24); + TestUtils.validateResults(analysisResults, 23); }); test('TypeVarDefault3', () => { @@ -350,5 +350,5 @@ test('Async1', () => { test('TypeCheckOnly1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typeCheckOnly1.py']); - TestUtils.validateResults(analysisResults, 5); + TestUtils.validateResults(analysisResults, 4); }); diff --git a/packages/pyright-internal/src/workspaceFactory.ts b/packages/pyright-internal/src/workspaceFactory.ts index 6e9c3460b..152c9dd0f 100644 --- a/packages/pyright-internal/src/workspaceFactory.ts +++ b/packages/pyright-internal/src/workspaceFactory.ts @@ -10,8 +10,6 @@ import { AnalyzerService } from './analyzer/service'; import { ConsoleInterface } from './common/console'; import { createDeferred } from './common/deferred'; import { UriParser } from './common/uriParser'; -import { comparePaths } from './common/pathUtils'; -import { Comparison } from './common/core'; let WorkspaceFactoryIdCounter = 0; @@ -182,12 +180,7 @@ export class WorkspaceFactory { } // If the python path has changed, we may need to move the immutable files to the correct workspace. - if ( - originalPythonPath && - (newPythonPath === undefined || - comparePaths(originalPythonPath, newPythonPath) !== Comparison.EqualTo) && - workspaceInMap - ) { + if (originalPythonPath && newPythonPath !== originalPythonPath && workspaceInMap) { // Potentially move immutable files from one workspace to another. this._moveImmutableFilesToCorrectWorkspace(originalPythonPath, workspaceInMap); } @@ -475,11 +468,7 @@ export class WorkspaceFactory { await bestInstance.isInitialized.promise; // If this best instance doesn't match the pythonPath, then we need to create a new one. - if ( - pythonPath !== undefined && - (bestInstance.pythonPath === undefined || - comparePaths(bestInstance.pythonPath, pythonPath) !== Comparison.EqualTo) - ) { + if (pythonPath !== undefined && bestInstance.pythonPath !== pythonPath) { bestInstance = this._createImmutableCopy(bestInstance, pythonPath); } @@ -491,11 +480,7 @@ export class WorkspaceFactory { let bestInstance = this._getBestWorkspaceForFile(filePath, pythonPath); // If this best instance doesn't match the pythonPath, then we need to create a new one. - if ( - pythonPath !== undefined && - (bestInstance.pythonPath === undefined || - comparePaths(bestInstance.pythonPath, pythonPath) !== Comparison.EqualTo) - ) { + if (pythonPath !== undefined && bestInstance.pythonPath !== pythonPath) { bestInstance = this._createImmutableCopy(bestInstance, pythonPath); } @@ -568,12 +553,14 @@ export class WorkspaceFactory { bestInstance = this._getBestRegularWorkspace(regularWorkspaces, pythonPath); } - // If the regular workspaces don't all have the same length, then try the workspaces that already have the file open or scanned. - if (bestInstance === undefined) { - bestInstance = this._getBestRegularWorkspace( - regularWorkspaces.filter((w) => w.service.hasSourceFile(filePath)), - pythonPath - ); + // If the regular workspaces don't all have the same length or they don't + // actually match on the python path, then try the workspaces that already have the file open or scanned. + if (bestInstance === undefined || bestInstance.pythonPath !== pythonPath) { + bestInstance = + this._getBestRegularWorkspace( + regularWorkspaces.filter((w) => w.service.hasSourceFile(filePath)), + pythonPath + ) || bestInstance; } // If that still didn't work, that must mean we don't have a workspace. Create a default one. diff --git a/packages/pyright-internal/typeshed-fallback/commit.txt b/packages/pyright-internal/typeshed-fallback/commit.txt index 199c5a26c..f0fb58c56 100644 --- a/packages/pyright-internal/typeshed-fallback/commit.txt +++ b/packages/pyright-internal/typeshed-fallback/commit.txt @@ -1 +1 @@ -40c639fcb0e2c2628fff019e4b769fd364c46665 +aef4fa8756d2e13972a495c69a22a20bb66043f9 diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/_ctypes.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/_ctypes.pyi index 25d604218..1f15ac057 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/_ctypes.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/_ctypes.pyi @@ -69,7 +69,7 @@ class _CData(metaclass=_CDataMeta): def __buffer__(self, __flags: int) -> memoryview: ... def __release_buffer__(self, __buffer: memoryview) -> None: ... -class _SimpleCData(Generic[_T], _CData): +class _SimpleCData(_CData, Generic[_T]): value: _T # The TypeVar can be unsolved here, # but we can't use overloads without creating many, many mypy false-positive errors @@ -78,7 +78,7 @@ class _SimpleCData(Generic[_T], _CData): class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -class _Pointer(Generic[_CT], _PointerLike, _CData): +class _Pointer(_PointerLike, _CData, Generic[_CT]): _type_: type[_CT] contents: _CT @overload @@ -122,15 +122,23 @@ class CFuncPtr(_PointerLike, _CData): def __call__(self, *args: Any, **kwargs: Any) -> Any: ... -class _CField: +_GetT = TypeVar("_GetT") +_SetT = TypeVar("_SetT") + +class _CField(Generic[_CT, _GetT, _SetT]): offset: int size: int + @overload + def __get__(self, __instance: None, __owner: type[Any] | None) -> Self: ... + @overload + def __get__(self, __instance: Any, __owner: type[Any] | None) -> _GetT: ... + def __set__(self, __instance: Any, __value: _SetT) -> None: ... class _StructUnionMeta(_CDataMeta): _fields_: Sequence[tuple[str, type[_CData]] | tuple[str, type[_CData], int]] _pack_: int _anonymous_: Sequence[str] - def __getattr__(self, name: str) -> _CField: ... + def __getattr__(self, name: str) -> _CField[Any, Any, Any]: ... class _StructUnionBase(_CData, metaclass=_StructUnionMeta): def __init__(self, *args: Any, **kw: Any) -> None: ... @@ -140,7 +148,7 @@ class _StructUnionBase(_CData, metaclass=_StructUnionMeta): class Union(_StructUnionBase): ... class Structure(_StructUnionBase): ... -class Array(Generic[_CT], _CData): +class Array(_CData, Generic[_CT]): @property @abstractmethod def _length_(self) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/abc.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/abc.pyi index 43893a298..7fe1d09f7 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/abc.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/abc.pyi @@ -40,7 +40,8 @@ class abstractstaticmethod(staticmethod[_P, _R_co]): class abstractproperty(property): __isabstractmethod__: Literal[True] -class ABC(metaclass=ABCMeta): ... +class ABC(metaclass=ABCMeta): + __slots__ = () def get_cache_token() -> object: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/taskgroups.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/taskgroups.pyi index 47d9bb2f6..aec3f1127 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/taskgroups.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/taskgroups.pyi @@ -1,10 +1,11 @@ import sys from contextvars import Context from types import TracebackType -from typing import TypeVar +from typing import Any, TypeVar from typing_extensions import Self from . import _CoroutineLike +from .events import AbstractEventLoop from .tasks import Task if sys.version_info >= (3, 12): @@ -15,6 +16,10 @@ else: _T = TypeVar("_T") class TaskGroup: + _loop: AbstractEventLoop | None + _tasks: set[Task[Any]] + async def __aenter__(self) -> Self: ... async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: ... + def _on_task_done(self, task: Task[object]) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi index f7b6700ae..b6929deb0 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi @@ -2,7 +2,7 @@ import concurrent.futures import sys from collections.abc import Awaitable, Coroutine, Generator, Iterable, Iterator from types import FrameType -from typing import Any, Generic, TextIO, TypeVar, overload +from typing import Any, Generic, Protocol, TextIO, TypeVar, overload from typing_extensions import Literal, TypeAlias from . import _CoroutineLike @@ -14,27 +14,52 @@ if sys.version_info >= (3, 9): if sys.version_info >= (3, 11): from contextvars import Context -__all__ = ( - "Task", - "create_task", - "FIRST_COMPLETED", - "FIRST_EXCEPTION", - "ALL_COMPLETED", - "wait", - "wait_for", - "as_completed", - "sleep", - "gather", - "shield", - "ensure_future", - "run_coroutine_threadsafe", - "current_task", - "all_tasks", - "_register_task", - "_unregister_task", - "_enter_task", - "_leave_task", -) +if sys.version_info >= (3, 12): + __all__ = ( + "Task", + "create_task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + "current_task", + "all_tasks", + "create_eager_task_factory", + "eager_task_factory", + "_register_task", + "_unregister_task", + "_enter_task", + "_leave_task", + ) +else: + __all__ = ( + "Task", + "create_task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + "current_task", + "all_tasks", + "_register_task", + "_unregister_task", + "_enter_task", + "_leave_task", + ) _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -243,12 +268,6 @@ if sys.version_info >= (3, 10): async def sleep(delay: float) -> None: ... @overload async def sleep(delay: float, result: _T) -> _T: ... - @overload - async def wait(fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED") -> tuple[set[_FT], set[_FT]]: ... # type: ignore[misc] - @overload - async def wait( - fs: Iterable[Awaitable[_T]], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" - ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _T: ... else: @@ -257,6 +276,25 @@ else: async def sleep(delay: float, *, loop: AbstractEventLoop | None = None) -> None: ... @overload async def sleep(delay: float, result: _T, *, loop: AbstractEventLoop | None = None) -> _T: ... + async def wait_for(fut: _FutureLike[_T], timeout: float | None, *, loop: AbstractEventLoop | None = None) -> _T: ... + +if sys.version_info >= (3, 11): + @overload + async def wait(fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED") -> tuple[set[_FT], set[_FT]]: ... # type: ignore[misc] + @overload + async def wait( + fs: Iterable[Task[_T]], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... + +elif sys.version_info >= (3, 10): + @overload + async def wait(fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED") -> tuple[set[_FT], set[_FT]]: ... # type: ignore[misc] + @overload + async def wait( + fs: Iterable[Awaitable[_T]], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... + +else: @overload async def wait( # type: ignore[misc] fs: Iterable[_FT], @@ -273,7 +311,6 @@ else: timeout: float | None = None, return_when: str = "ALL_COMPLETED", ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... - async def wait_for(fut: _FutureLike[_T], timeout: float | None, *, loop: AbstractEventLoop | None = None) -> _T: ... if sys.version_info >= (3, 12): _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] @@ -344,5 +381,41 @@ else: def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ... def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... + +if sys.version_info >= (3, 12): + _TaskT_co = TypeVar("_TaskT_co", bound=Task[Any], covariant=True) + + class _CustomTaskConstructor(Protocol[_TaskT_co]): + def __call__( + self, + __coro: _TaskCompatibleCoro[Any], + *, + loop: AbstractEventLoop, + name: str | None, + context: Context | None, + eager_start: bool, + ) -> _TaskT_co: ... + + class _EagerTaskFactoryType(Protocol[_TaskT_co]): + def __call__( + self, + loop: AbstractEventLoop, + coro: _TaskCompatibleCoro[Any], + *, + name: str | None = None, + context: Context | None = None, + ) -> _TaskT_co: ... + + def create_eager_task_factory( + custom_task_constructor: _CustomTaskConstructor[_TaskT_co], + ) -> _EagerTaskFactoryType[_TaskT_co]: ... + def eager_task_factory( + loop: AbstractEventLoop | None, + coro: _TaskCompatibleCoro[_T_co], + *, + name: str | None = None, + context: Context | None = None, + ) -> Task[_T_co]: ... + def _register_task(task: Task[Any]) -> None: ... def _unregister_task(task: Task[Any]) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi index 71cccee16..9a1534005 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi @@ -1120,13 +1120,13 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... @overload - def __or__(self, __value: Mapping[_KT, _VT]) -> dict[_KT, _VT]: ... + def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ... @overload - def __or__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... + def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... @overload - def __ror__(self, __value: Mapping[_KT, _VT]) -> dict[_KT, _VT]: ... + def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ... @overload - def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... + def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... # dict.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... @@ -1905,11 +1905,17 @@ def __import__( ) -> types.ModuleType: ... def __build_class__(__func: Callable[[], _Cell | Any], __name: str, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... -# Actually the type of Ellipsis is , but since it's -# not exposed anywhere under that name, we make it private here. -@final -@type_check_only -class ellipsis: ... +if sys.version_info >= (3, 10): + # In Python 3.10, EllipsisType is exposed publicly in the types module. + @final + class ellipsis: ... + +else: + # Actually the type of Ellipsis is , but since it's + # not exposed anywhere under that name, we make it private here. + @final + @type_check_only + class ellipsis: ... Ellipsis: ellipsis diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/codecs.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/codecs.pyi index c9b6a4a82..f8c92392a 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/codecs.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/codecs.pyi @@ -78,16 +78,16 @@ class _Stream(_WritableStream, _ReadableStream, Protocol): ... # They were much more common in Python 2 than in Python 3. class _Encoder(Protocol): - def __call__(self, input: str, errors: str = ...) -> tuple[bytes, int]: ... # signature of Codec().encode + def __call__(self, __input: str, __errors: str = ...) -> tuple[bytes, int]: ... # signature of Codec().encode class _Decoder(Protocol): - def __call__(self, input: bytes, errors: str = ...) -> tuple[str, int]: ... # signature of Codec().decode + def __call__(self, __input: bytes, __errors: str = ...) -> tuple[str, int]: ... # signature of Codec().decode class _StreamReader(Protocol): - def __call__(self, stream: _ReadableStream, errors: str = ...) -> StreamReader: ... + def __call__(self, __stream: _ReadableStream, __errors: str = ...) -> StreamReader: ... class _StreamWriter(Protocol): - def __call__(self, stream: _WritableStream, errors: str = ...) -> StreamWriter: ... + def __call__(self, __stream: _WritableStream, __errors: str = ...) -> StreamWriter: ... class _IncrementalEncoder(Protocol): def __call__(self, errors: str = ...) -> IncrementalEncoder: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/collections/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/collections/__init__.pyi index 8ceecd1f3..3b8d92f78 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/collections/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/collections/__init__.pyi @@ -96,6 +96,11 @@ class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... @overload def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + if sys.version_info >= (3, 12): + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... class UserList(MutableSequence[_T]): data: list[_T] @@ -402,13 +407,13 @@ class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]): def copy(self) -> Self: ... if sys.version_info >= (3, 9): @overload - def __or__(self, __value: Mapping[_KT, _VT]) -> Self: ... + def __or__(self, __value: dict[_KT, _VT]) -> Self: ... @overload - def __or__(self, __value: Mapping[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... + def __or__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... @overload - def __ror__(self, __value: Mapping[_KT, _VT]) -> Self: ... + def __ror__(self, __value: dict[_KT, _VT]) -> Self: ... @overload - def __ror__(self, __value: Mapping[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... + def __ror__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] @@ -422,6 +427,10 @@ class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... def __contains__(self, key: object) -> bool: ... + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... def __missing__(self, key: _KT) -> _VT: ... # undocumented def __bool__(self) -> bool: ... # Keep ChainMap.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/configparser.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/configparser.pyi index 6f9f78831..e6fedb032 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/configparser.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/configparser.pyi @@ -5,31 +5,53 @@ from re import Pattern from typing import Any, ClassVar, TypeVar, overload from typing_extensions import Literal, TypeAlias -__all__ = [ - "NoSectionError", - "DuplicateOptionError", - "DuplicateSectionError", - "NoOptionError", - "InterpolationError", - "InterpolationDepthError", - "InterpolationMissingOptionError", - "InterpolationSyntaxError", - "ParsingError", - "MissingSectionHeaderError", - "ConfigParser", - "RawConfigParser", - "Interpolation", - "BasicInterpolation", - "ExtendedInterpolation", - "LegacyInterpolation", - "SectionProxy", - "ConverterMapping", - "DEFAULTSECT", - "MAX_INTERPOLATION_DEPTH", -] - -if sys.version_info < (3, 12): - __all__ += ["SafeConfigParser"] +if sys.version_info >= (3, 12): + __all__ = ( + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "LegacyInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + ) +else: + __all__ = [ + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "SafeConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "LegacyInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + ] _Section: TypeAlias = Mapping[str, str] _Parser: TypeAlias = MutableMapping[str, _Section] @@ -128,7 +150,8 @@ class RawConfigParser(_Parser): def read_file(self, f: Iterable[str], source: str | None = None) -> None: ... def read_string(self, string: str, source: str = "") -> None: ... def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = "") -> None: ... - def readfp(self, fp: Iterable[str], filename: str | None = None) -> None: ... + if sys.version_info < (3, 12): + def readfp(self, fp: Iterable[str], filename: str | None = None) -> None: ... # These get* methods are partially applied (with the same names) in # SectionProxy; the stubs should be kept updated together @overload @@ -277,7 +300,11 @@ class InterpolationSyntaxError(InterpolationError): ... class ParsingError(Error): source: str errors: list[tuple[int, str]] - def __init__(self, source: str | None = None, filename: str | None = None) -> None: ... + if sys.version_info >= (3, 12): + def __init__(self, source: str) -> None: ... + else: + def __init__(self, source: str | None = None, filename: str | None = None) -> None: ... + def append(self, lineno: int, line: str) -> None: ... class MissingSectionHeaderError(ParsingError): diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/csv.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/csv.pyi index 139ba7af2..53425fbcc 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/csv.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/csv.pyi @@ -69,10 +69,10 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... -class DictReader(Generic[_T], Iterator[_DictReadMapping[_T | Any, str | Any]]): +class DictReader(Iterator[_DictReadMapping[_T | Any, str | Any]], Generic[_T]): fieldnames: Sequence[_T] | None - restkey: str | None - restval: str | None + restkey: _T | None + restval: str | Any | None reader: _reader dialect: _DialectLike line_num: int @@ -81,8 +81,8 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T | Any, str | Any]]): self, f: Iterable[str], fieldnames: Sequence[_T], - restkey: str | None = None, - restval: str | None = None, + restkey: _T | None = None, + restval: str | Any | None = None, dialect: _DialectLike = "excel", *, delimiter: str = ",", diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/ctypes/wintypes.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/ctypes/wintypes.pyi index 3bd279347..59c7ae3e5 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/ctypes/wintypes.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/ctypes/wintypes.pyi @@ -1,6 +1,7 @@ from ctypes import ( Array, Structure, + _CField, _Pointer, _SimpleCData, c_byte, @@ -20,6 +21,7 @@ from ctypes import ( c_wchar, c_wchar_p, ) +from typing import TypeVar from typing_extensions import TypeAlias BYTE = c_byte @@ -101,39 +103,42 @@ HWND = HANDLE SC_HANDLE = HANDLE SERVICE_STATUS_HANDLE = HANDLE +_CIntLikeT = TypeVar("_CIntLikeT", bound=_SimpleCData[int]) +_CIntLikeField: TypeAlias = _CField[_CIntLikeT, int, _CIntLikeT | int] + class RECT(Structure): - left: LONG - top: LONG - right: LONG - bottom: LONG + left: _CIntLikeField[LONG] + top: _CIntLikeField[LONG] + right: _CIntLikeField[LONG] + bottom: _CIntLikeField[LONG] RECTL = RECT _RECTL = RECT tagRECT = RECT class _SMALL_RECT(Structure): - Left: SHORT - Top: SHORT - Right: SHORT - Bottom: SHORT + Left: _CIntLikeField[SHORT] + Top: _CIntLikeField[SHORT] + Right: _CIntLikeField[SHORT] + Bottom: _CIntLikeField[SHORT] SMALL_RECT = _SMALL_RECT class _COORD(Structure): - X: SHORT - Y: SHORT + X: _CIntLikeField[SHORT] + Y: _CIntLikeField[SHORT] class POINT(Structure): - x: LONG - y: LONG + x: _CIntLikeField[LONG] + y: _CIntLikeField[LONG] POINTL = POINT _POINTL = POINT tagPOINT = POINT class SIZE(Structure): - cx: LONG - cy: LONG + cx: _CIntLikeField[LONG] + cy: _CIntLikeField[LONG] SIZEL = SIZE tagSIZE = SIZE @@ -141,45 +146,45 @@ tagSIZE = SIZE def RGB(red: int, green: int, blue: int) -> int: ... class FILETIME(Structure): - dwLowDateTime: DWORD - dwHighDateTime: DWORD + dwLowDateTime: _CIntLikeField[DWORD] + dwHighDateTime: _CIntLikeField[DWORD] _FILETIME = FILETIME class MSG(Structure): - hWnd: HWND - message: UINT - wParam: WPARAM - lParam: LPARAM - time: DWORD - pt: POINT + hWnd: _CField[HWND, int | None, HWND | int | None] + message: _CIntLikeField[UINT] + wParam: _CIntLikeField[WPARAM] + lParam: _CIntLikeField[LPARAM] + time: _CIntLikeField[DWORD] + pt: _CField[POINT, POINT, POINT] tagMSG = MSG MAX_PATH: int class WIN32_FIND_DATAA(Structure): - dwFileAttributes: DWORD - ftCreationTime: FILETIME - ftLastAccessTime: FILETIME - ftLastWriteTime: FILETIME - nFileSizeHigh: DWORD - nFileSizeLow: DWORD - dwReserved0: DWORD - dwReserved1: DWORD - cFileName: Array[CHAR] - cAlternateFileName: Array[CHAR] + dwFileAttributes: _CIntLikeField[DWORD] + ftCreationTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME] + nFileSizeHigh: _CIntLikeField[DWORD] + nFileSizeLow: _CIntLikeField[DWORD] + dwReserved0: _CIntLikeField[DWORD] + dwReserved1: _CIntLikeField[DWORD] + cFileName: _CField[Array[CHAR], bytes, bytes] + cAlternateFileName: _CField[Array[CHAR], bytes, bytes] class WIN32_FIND_DATAW(Structure): - dwFileAttributes: DWORD - ftCreationTime: FILETIME - ftLastAccessTime: FILETIME - ftLastWriteTime: FILETIME - nFileSizeHigh: DWORD - nFileSizeLow: DWORD - dwReserved0: DWORD - dwReserved1: DWORD - cFileName: Array[WCHAR] - cAlternateFileName: Array[WCHAR] + dwFileAttributes: _CIntLikeField[DWORD] + ftCreationTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME] + nFileSizeHigh: _CIntLikeField[DWORD] + nFileSizeLow: _CIntLikeField[DWORD] + dwReserved0: _CIntLikeField[DWORD] + dwReserved1: _CIntLikeField[DWORD] + cFileName: _CField[Array[WCHAR], str, str] + cAlternateFileName: _CField[Array[WCHAR], str, str] # These pointer type definitions use _Pointer[...] instead of POINTER(...), to allow them # to be used in type annotations. diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/enum.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/enum.pyi index a8ba7bf15..10ea19257 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/enum.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/enum.pyi @@ -33,7 +33,7 @@ if sys.version_info >= (3, 11): "verify", ] -if sys.version_info >= (3, 12): +if sys.version_info >= (3, 11): __all__ += ["pickle_by_enum_name", "pickle_by_global_name"] _EnumMemberT = TypeVar("_EnumMemberT") @@ -119,10 +119,12 @@ class EnumMeta(type): def __len__(self) -> int: ... def __bool__(self) -> Literal[True]: ... def __dir__(self) -> list[str]: ... - # Simple value lookup + + # Overload 1: Value lookup on an already existing enum class (simple case) @overload def __call__(cls: type[_EnumMemberT], value: Any, names: None = None) -> _EnumMemberT: ... - # Functional Enum API + + # Overload 2: Functional API for constructing new enum classes. if sys.version_info >= (3, 11): @overload def __call__( @@ -148,6 +150,18 @@ class EnumMeta(type): type: type | None = None, start: int = 1, ) -> type[Enum]: ... + + # Overload 3 (py312+ only): Value lookup on an already existing enum class (complex case) + # + # >>> class Foo(enum.Enum): + # ... X = 1, 2, 3 + # >>> Foo(1, 2, 3) + # + # + if sys.version_info >= (3, 12): + @overload + def __call__(cls: type[_EnumMemberT], value: Any, *values: Any) -> _EnumMemberT: ... + _member_names_: list[str] # undocumented _member_map_: dict[str, Enum] # undocumented _value2member_map_: dict[Any, Enum] # undocumented @@ -160,6 +174,7 @@ if sys.version_info >= (3, 11): def __set_name__(self, ownerclass: type[Enum], name: str) -> None: ... name: str clsname: str + member: Enum | None _magic_enum_attr = property else: _magic_enum_attr = types.DynamicClassAttribute @@ -188,9 +203,12 @@ class Enum(metaclass=EnumMeta): def __hash__(self) -> int: ... def __format__(self, format_spec: str) -> str: ... def __reduce_ex__(self, proto: Unused) -> tuple[Any, ...]: ... - if sys.version_info >= (3, 12): + if sys.version_info >= (3, 11): def __copy__(self) -> Self: ... def __deepcopy__(self, memo: Any) -> Self: ... + if sys.version_info >= (3, 12): + @classmethod + def __signature__(cls) -> str: ... if sys.version_info >= (3, 11): class ReprEnum(Enum): ... @@ -294,6 +312,6 @@ class auto(IntFlag): def value(self) -> Any: ... def __new__(cls) -> Self: ... -if sys.version_info >= (3, 12): +if sys.version_info >= (3, 11): def pickle_by_global_name(self: Enum, proto: int) -> str: ... def pickle_by_enum_name(self: _EnumMemberT, proto: int) -> tuple[Callable[..., Any], tuple[type[_EnumMemberT], str]]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/functools.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/functools.pyi index 8adc3d822..0d08cdb19 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/functools.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/functools.pyi @@ -33,7 +33,7 @@ _S = TypeVar("_S") _PWrapped = ParamSpec("_PWrapped") _RWrapped = TypeVar("_RWrapped") _PWrapper = ParamSpec("_PWrapper") -_RWapper = TypeVar("_RWapper") +_RWrapper = TypeVar("_RWrapper") @overload def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... @@ -87,23 +87,23 @@ else: ] WRAPPER_UPDATES: tuple[Literal["__dict__"]] -class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWapper]): +class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]): __wrapped__: Callable[_PWrapped, _RWrapped] - def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWapper: ... + def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ... # as with ``Callable``, we'll assume that these attributes exist __name__: str __qualname__: str class _Wrapper(Generic[_PWrapped, _RWrapped]): - def __call__(self, f: Callable[_PWrapper, _RWapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWapper]: ... + def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... if sys.version_info >= (3, 12): def update_wrapper( - wrapper: Callable[_PWrapper, _RWapper], + wrapper: Callable[_PWrapper, _RWrapper], wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Sequence[str] = ("__dict__",), - ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWapper]: ... + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... def wraps( wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), @@ -112,11 +112,11 @@ if sys.version_info >= (3, 12): else: def update_wrapper( - wrapper: Callable[_PWrapper, _RWapper], + wrapper: Callable[_PWrapper, _RWrapper], wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Sequence[str] = ("__dict__",), - ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWapper]: ... + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... def wraps( wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/genericpath.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/genericpath.pyi index 46426b63c..be08f7a3c 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/genericpath.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/genericpath.pyi @@ -1,5 +1,6 @@ import os -from _typeshed import BytesPath, FileDescriptorOrPath, StrPath, SupportsRichComparisonT +import sys +from _typeshed import BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath, SupportsRichComparisonT from collections.abc import Sequence from typing import overload from typing_extensions import Literal, LiteralString @@ -17,6 +18,8 @@ __all__ = [ "sameopenfile", "samestat", ] +if sys.version_info >= (3, 12): + __all__ += ["islink"] # All overloads can return empty string. Ideally, Literal[""] would be a valid # Iterable[T], so that list[T] | Literal[""] could be used as a return @@ -36,6 +39,9 @@ def getsize(filename: FileDescriptorOrPath) -> int: ... def isfile(path: FileDescriptorOrPath) -> bool: ... def isdir(s: FileDescriptorOrPath) -> bool: ... +if sys.version_info >= (3, 12): + def islink(path: StrOrBytesPath) -> bool: ... + # These return float if os.stat_float_times() == True, # but int is a subclass of float. def getatime(filename: FileDescriptorOrPath) -> float: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/gzip.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/gzip.pyi index 1ec8b4b8c..d001849e6 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/gzip.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/gzip.pyi @@ -139,8 +139,10 @@ class GzipFile(_compression.BaseStream): fileobj: _ReadableFileobj | _WritableFileobj | None = None, mtime: float | None = None, ) -> None: ... - @property - def filename(self) -> str: ... + if sys.version_info < (3, 12): + @property + def filename(self) -> str: ... + @property def mtime(self) -> int | None: ... crc: int diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/http/client.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/http/client.pyi index 4b5ed3d8b..3e5e496ab 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/http/client.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/http/client.pyi @@ -169,6 +169,9 @@ class HTTPConnection: ) -> None: ... def getresponse(self) -> HTTPResponse: ... def set_debuglevel(self, level: int) -> None: ... + if sys.version_info >= (3, 12): + def get_proxy_response_headers(self) -> HTTPMessage | None: ... + def set_tunnel(self, host: str, port: int | None = None, headers: Mapping[str, str] | None = None) -> None: ... def connect(self) -> None: ... def close(self) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/http/cookies.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/http/cookies.pyi index e24ef9cbd..3d19bb108 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/http/cookies.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/http/cookies.pyi @@ -49,12 +49,12 @@ class Morsel(dict[str, Any], Generic[_T]): class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): def __init__(self, input: _DataType | None = None) -> None: ... - def value_decode(self, val: str) -> _T: ... - def value_encode(self, val: _T) -> str: ... + def value_decode(self, val: str) -> tuple[_T, str]: ... + def value_encode(self, val: _T) -> tuple[_T, str]: ... def output(self, attrs: list[str] | None = None, header: str = "Set-Cookie:", sep: str = "\r\n") -> str: ... __str__ = output def js_output(self, attrs: list[str] | None = None) -> str: ... def load(self, rawdata: _DataType) -> None: ... def __setitem__(self, key: str, value: str | Morsel[_T]) -> None: ... -class SimpleCookie(BaseCookie[_T], Generic[_T]): ... +class SimpleCookie(BaseCookie[str]): ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/imaplib.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/imaplib.pyi index 7781559c3..a61848c9a 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/imaplib.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/imaplib.pyi @@ -108,9 +108,14 @@ class IMAP4: def print_log(self) -> None: ... class IMAP4_SSL(IMAP4): - keyfile: str - certfile: str - if sys.version_info >= (3, 9): + if sys.version_info < (3, 12): + keyfile: str + certfile: str + if sys.version_info >= (3, 12): + def __init__( + self, host: str = "", port: int = 993, *, ssl_context: SSLContext | None = None, timeout: float | None = None + ) -> None: ... + elif sys.version_info >= (3, 9): def __init__( self, host: str = "", diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/__init__.pyi index 8d73319f8..8506efc01 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/__init__.pyi @@ -1,3 +1,4 @@ +import sys from collections.abc import Mapping, Sequence from importlib.abc import Loader from types import ModuleType @@ -15,6 +16,9 @@ def __import__( # `importlib.import_module` return type should be kept the same as `builtins.__import__` def import_module(name: str, package: str | None = None) -> ModuleType: ... -def find_loader(name: str, path: str | None = None) -> Loader | None: ... + +if sys.version_info < (3, 12): + def find_loader(name: str, path: str | None = None) -> Loader | None: ... + def invalidate_caches() -> None: ... def reload(module: ModuleType) -> ModuleType: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/abc.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/abc.pyi index 4bf46104b..28c33205a 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/abc.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/abc.pyi @@ -20,7 +20,6 @@ from typing_extensions import Literal if sys.version_info >= (3, 11): __all__ = [ "Loader", - "Finder", "MetaPathFinder", "PathEntryFinder", "ResourceLoader", @@ -28,16 +27,19 @@ if sys.version_info >= (3, 11): "ExecutionLoader", "FileLoader", "SourceLoader", - "ResourceReader", - "Traversable", - "TraversableResources", ] -class Finder(metaclass=ABCMeta): ... + if sys.version_info < (3, 12): + __all__ += ["Finder", "ResourceReader", "Traversable", "TraversableResources"] + +if sys.version_info < (3, 12): + class Finder(metaclass=ABCMeta): ... class Loader(metaclass=ABCMeta): def load_module(self, fullname: str) -> types.ModuleType: ... - def module_repr(self, module: types.ModuleType) -> str: ... + if sys.version_info < (3, 12): + def module_repr(self, module: types.ModuleType) -> str: ... + def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... # Not defined on the actual class for backwards-compatibility reasons, # but expected in new code. @@ -68,21 +70,37 @@ class SourceLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): def get_source(self, fullname: str) -> str | None: ... def path_stats(self, path: str) -> Mapping[str, Any]: ... -# Please keep in sync with sys._MetaPathFinder -class MetaPathFinder(Finder): - def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ... - def invalidate_caches(self) -> None: ... - # Not defined on the actual class, but expected to exist. - def find_spec( - self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ... - ) -> ModuleSpec | None: ... - -class PathEntryFinder(Finder): - def find_module(self, fullname: str) -> Loader | None: ... - def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ... - def invalidate_caches(self) -> None: ... - # Not defined on the actual class, but expected to exist. - def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... +# The base classes differ on 3.12: +if sys.version_info >= (3, 12): + # Please keep in sync with sys._MetaPathFinder + class MetaPathFinder(metaclass=ABCMeta): + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ... + ) -> ModuleSpec | None: ... + + class PathEntryFinder(metaclass=ABCMeta): + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... + +else: + # Please keep in sync with sys._MetaPathFinder + class MetaPathFinder(Finder): + def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ... + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ... + ) -> ModuleSpec | None: ... + + class PathEntryFinder(Finder): + def find_module(self, fullname: str) -> Loader | None: ... + def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ... + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): name: str diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/machinery.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/machinery.pyi index f5037da00..1a9680ab3 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/machinery.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/machinery.pyi @@ -31,8 +31,10 @@ class ModuleSpec: class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder - @classmethod - def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + if sys.version_info < (3, 12): + @classmethod + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + @classmethod def find_spec( cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None @@ -47,8 +49,9 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader) @classmethod def get_source(cls, fullname: str) -> None: ... # Loader - @staticmethod - def module_repr(module: types.ModuleType) -> str: ... + if sys.version_info < (3, 12): + @staticmethod + def module_repr(module: types.ModuleType) -> str: ... if sys.version_info >= (3, 10): @staticmethod def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... @@ -62,8 +65,10 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader) class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder - @classmethod - def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + if sys.version_info < (3, 12): + @classmethod + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + @classmethod def find_spec( cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None @@ -78,8 +83,9 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): @classmethod def get_source(cls, fullname: str) -> None: ... # Loader - @staticmethod - def module_repr(m: types.ModuleType) -> str: ... + if sys.version_info < (3, 12): + @staticmethod + def module_repr(m: types.ModuleType) -> str: ... if sys.version_info >= (3, 10): @staticmethod def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... @@ -91,8 +97,10 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): def exec_module(module: types.ModuleType) -> None: ... class WindowsRegistryFinder(importlib.abc.MetaPathFinder): - @classmethod - def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + if sys.version_info < (3, 12): + @classmethod + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + @classmethod def find_spec( cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None @@ -116,8 +124,9 @@ class PathFinder: def find_spec( cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None ) -> ModuleSpec | None: ... - @classmethod - def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + if sys.version_info < (3, 12): + @classmethod + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... SOURCE_SUFFIXES: list[str] DEBUG_BYTECODE_SUFFIXES: list[str] diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/__init__.pyi index 0f8a6f56c..e52756544 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/__init__.pyi @@ -88,6 +88,7 @@ if sys.version_info >= (3, 10): @property def groups(self) -> set[str]: ... +if sys.version_info >= (3, 10) and sys.version_info < (3, 12): class SelectableGroups(dict[str, EntryPoints]): # use as dict is deprecated since 3.10 @classmethod def load(cls, eps: Iterable[EntryPoint]) -> Self: ... @@ -195,6 +196,16 @@ def distributions( if sys.version_info >= (3, 10): def metadata(distribution_name: str) -> PackageMetadata: ... + +else: + def metadata(distribution_name: str) -> Message: ... + +if sys.version_info >= (3, 12): + def entry_points( + *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... + ) -> EntryPoints: ... + +elif sys.version_info >= (3, 10): @overload def entry_points() -> SelectableGroups: ... # type: ignore[misc] @overload @@ -203,7 +214,6 @@ if sys.version_info >= (3, 10): ) -> EntryPoints: ... else: - def metadata(distribution_name: str) -> Message: ... def entry_points() -> dict[str, list[EntryPoint]]: ... def version(distribution_name: str) -> str: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/_meta.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/_meta.pyi index e3504fe40..64fefa9a8 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/_meta.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/metadata/_meta.pyi @@ -1,5 +1,6 @@ +import sys from collections.abc import Iterator -from typing import Any, Protocol, TypeVar +from typing import Any, Protocol, TypeVar, overload _T = TypeVar("_T") @@ -8,15 +9,32 @@ class PackageMetadata(Protocol): def __contains__(self, item: str) -> bool: ... def __getitem__(self, key: str) -> str: ... def __iter__(self) -> Iterator[str]: ... - def get_all(self, name: str, failobj: _T = ...) -> list[Any] | _T: ... @property def json(self) -> dict[str, str | list[str]]: ... + @overload + def get_all(self, name: str, failobj: None = None) -> list[Any] | None: ... + @overload + def get_all(self, name: str, failobj: _T) -> list[Any] | _T: ... + if sys.version_info >= (3, 12): + @overload + def get(self, name: str, failobj: None = None) -> str | None: ... + @overload + def get(self, name: str, failobj: _T) -> _T | str: ... -class SimplePath(Protocol): - def joinpath(self) -> SimplePath: ... - def parent(self) -> SimplePath: ... - def read_text(self) -> str: ... - # There was a bug in `SimplePath` definition in cpython, see #8451 - # Strictly speaking `__div__` was defined in 3.10, not __truediv__, - # but it should have always been `__truediv__`. - def __truediv__(self) -> SimplePath: ... +if sys.version_info >= (3, 12): + class SimplePath(Protocol[_T]): + def joinpath(self) -> _T: ... + @property + def parent(self) -> _T: ... + def read_text(self) -> str: ... + def __truediv__(self, other: _T | str) -> _T: ... + +else: + class SimplePath(Protocol): + def joinpath(self) -> SimplePath: ... + def parent(self) -> SimplePath: ... + def read_text(self) -> str: ... + # There was a bug in `SimplePath` definition in cpython, see #8451 + # Strictly speaking `__div__` was defined in 3.10, not __truediv__, + # but it should have always been `__truediv__`. + def __truediv__(self) -> SimplePath: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/resources/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/resources/__init__.pyi index ba3d9b087..8d6565637 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/resources/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/resources/__init__.pyi @@ -7,6 +7,9 @@ from types import ModuleType from typing import Any, BinaryIO, TextIO from typing_extensions import TypeAlias +if sys.version_info >= (3, 9): + from importlib.abc import Traversable + __all__ = ["Package", "Resource", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] if sys.version_info >= (3, 9): @@ -31,9 +34,13 @@ def is_resource(package: Package, name: str) -> bool: ... def contents(package: Package) -> Iterator[str]: ... if sys.version_info >= (3, 9): - from importlib.abc import Traversable - def files(package: Package) -> Traversable: ... def as_file(path: Traversable) -> AbstractContextManager[Path]: ... +if sys.version_info >= (3, 12): + def files(anchor: Package | None = ...) -> Traversable: ... + +elif sys.version_info >= (3, 9): + def files(package: Package) -> Traversable: ... + if sys.version_info >= (3, 10): from importlib.abc import ResourceReader as ResourceReader diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/util.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/util.pyi index f988eb270..6608f70d4 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/importlib/util.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/importlib/util.pyi @@ -1,5 +1,6 @@ import importlib.abc import importlib.machinery +import sys import types from _typeshed import ReadableBuffer, StrOrBytesPath from collections.abc import Callable @@ -8,9 +9,11 @@ from typing_extensions import ParamSpec _P = ParamSpec("_P") -def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... -def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... -def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... +if sys.version_info < (3, 12): + def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + def resolve_name(name: str, package: str | None) -> str: ... MAGIC_NUMBER: bytes @@ -37,4 +40,4 @@ class LazyLoader(importlib.abc.Loader): def factory(cls, loader: importlib.abc.Loader) -> Callable[..., LazyLoader]: ... def exec_module(self, module: types.ModuleType) -> None: ... -def source_hash(source_bytes: ReadableBuffer) -> int: ... +def source_hash(source_bytes: ReadableBuffer) -> bytes: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/ntpath.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/ntpath.pyi index f1fa137c6..1a58b52de 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/ntpath.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/ntpath.pyi @@ -42,6 +42,9 @@ from posixpath import ( splitext as splitext, supports_unicode_filenames as supports_unicode_filenames, ) + +if sys.version_info >= (3, 12): + from posixpath import isjunction as isjunction, splitroot as splitroot from typing import AnyStr, overload from typing_extensions import LiteralString @@ -85,6 +88,8 @@ __all__ = [ "samestat", "commonpath", ] +if sys.version_info >= (3, 12): + __all__ += ["isjunction", "splitroot"] altsep: LiteralString diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi index 994595aae..961858ce3 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi @@ -388,6 +388,8 @@ class DirEntry(Generic[AnyStr]): def __fspath__(self) -> AnyStr: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... + if sys.version_info >= (3, 12): + def is_junction(self) -> bool: ... @final class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int, int]): @@ -602,7 +604,12 @@ def isatty(__fd: int) -> bool: ... if sys.platform != "win32" and sys.version_info >= (3, 11): def login_tty(__fd: int) -> None: ... -def lseek(__fd: int, __position: int, __how: int) -> int: ... +if sys.version_info >= (3, 11): + def lseek(__fd: int, __position: int, __whence: int) -> int: ... + +else: + def lseek(__fd: int, __position: int, __how: int) -> int: ... + def open(path: StrOrBytesPath, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: ... def pipe() -> tuple[int, int]: ... def read(__fd: int, __length: int) -> bytes: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/pathlib.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/pathlib.pyi index a509ec3af..10ffa4a77 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/pathlib.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/pathlib.pyi @@ -8,6 +8,7 @@ from _typeshed import ( ReadableBuffer, StrOrBytesPath, StrPath, + Unused, ) from collections.abc import Callable, Generator, Iterator, Sequence from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper @@ -38,9 +39,13 @@ class PurePath(PathLike[str]): def suffixes(self) -> list[str]: ... @property def stem(self) -> str: ... - def __new__(cls, *args: StrPath) -> Self: ... + if sys.version_info >= (3, 12): + def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... + def __init__(self, *args: StrPath) -> None: ... + else: + def __new__(cls, *args: StrPath) -> Self: ... + def __hash__(self) -> int: ... - def __eq__(self, other: object) -> bool: ... def __fspath__(self) -> str: ... def __lt__(self, other: PurePath) -> bool: ... def __le__(self, other: PurePath) -> bool: ... @@ -53,7 +58,9 @@ class PurePath(PathLike[str]): def as_uri(self) -> str: ... def is_absolute(self) -> bool: ... def is_reserved(self) -> bool: ... - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 12): + def is_relative_to(self, __other: StrPath, *_deprecated: StrPath) -> bool: ... + elif sys.version_info >= (3, 9): def is_relative_to(self, *other: StrPath) -> bool: ... if sys.version_info >= (3, 12): @@ -61,7 +68,11 @@ class PurePath(PathLike[str]): else: def match(self, path_pattern: str) -> bool: ... - def relative_to(self, *other: StrPath) -> Self: ... + if sys.version_info >= (3, 12): + def relative_to(self, __other: StrPath, *_deprecated: StrPath, walk_up: bool = False) -> Self: ... + else: + def relative_to(self, *other: StrPath) -> Self: ... + def with_name(self, name: str) -> Self: ... if sys.version_info >= (3, 9): def with_stem(self, stem: str) -> Self: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/poplib.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/poplib.pyi index c64e47e8e..808e7e522 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/poplib.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/poplib.pyi @@ -1,5 +1,6 @@ import socket import ssl +import sys from builtins import list as _list # conflicts with a method named "list" from re import Pattern from typing import Any, BinaryIO, NoReturn, overload @@ -51,14 +52,20 @@ class POP3: def stls(self, context: ssl.SSLContext | None = None) -> bytes: ... class POP3_SSL(POP3): - def __init__( - self, - host: str, - port: int = 995, - keyfile: str | None = None, - certfile: str | None = None, - timeout: float = ..., - context: ssl.SSLContext | None = None, - ) -> None: ... - # "context" is actually the last argument, but that breaks LSP and it doesn't really matter because all the arguments are ignored - def stls(self, context: Any = None, keyfile: Any = None, certfile: Any = None) -> NoReturn: ... + if sys.version_info >= (3, 12): + def __init__( + self, host: str, port: int = 995, *, timeout: float = ..., context: ssl.SSLContext | None = None + ) -> None: ... + def stls(self, context: Any = None) -> NoReturn: ... + else: + def __init__( + self, + host: str, + port: int = 995, + keyfile: str | None = None, + certfile: str | None = None, + timeout: float = ..., + context: ssl.SSLContext | None = None, + ) -> None: ... + # "context" is actually the last argument, but that breaks LSP and it doesn't really matter because all the arguments are ignored + def stls(self, context: Any = None, keyfile: Any = None, certfile: Any = None) -> NoReturn: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi index 1945190be..45a8ad7ec 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi @@ -58,6 +58,8 @@ __all__ = [ "relpath", "commonpath", ] +if sys.version_info >= (3, 12): + __all__ += ["isjunction", "splitroot"] supports_unicode_filenames: bool # aliases (also in os) @@ -150,3 +152,10 @@ def isabs(s: StrOrBytesPath) -> bool: ... def islink(path: FileDescriptorOrPath) -> bool: ... def ismount(path: FileDescriptorOrPath) -> bool: ... def lexists(path: FileDescriptorOrPath) -> bool: ... + +if sys.version_info >= (3, 12): + def isjunction(path: StrOrBytesPath) -> bool: ... + @overload + def splitroot(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... + @overload + def splitroot(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr, AnyStr]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/pydoc.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/pydoc.pyi index 7791c977a..1b09bcb05 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/pydoc.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/pydoc.pyi @@ -198,7 +198,7 @@ def render_doc( thing: str | object, title: str = "Python Library Documentation: %s", forceload: bool = ..., renderer: Doc | None = None ) -> str: ... -if sys.version_info >= (3, 12): +if sys.version_info >= (3, 11): def doc( thing: str | object, title: str = "Python Library Documentation: %s", @@ -230,7 +230,7 @@ class Helper: def __call__(self, request: str | Helper | object = ...) -> None: ... def interact(self) -> None: ... def getline(self, prompt: str) -> str: ... - if sys.version_info >= (3, 12): + if sys.version_info >= (3, 11): def help(self, request: Any, is_cli: bool = False) -> None: ... else: def help(self, request: Any) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/smtplib.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/smtplib.pyi index 584fa164f..e584d7f57 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/smtplib.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/smtplib.pyi @@ -128,7 +128,13 @@ class SMTP: def auth_plain(self, challenge: ReadableBuffer | None = None) -> str: ... def auth_login(self, challenge: ReadableBuffer | None = None) -> str: ... def login(self, user: str, password: str, *, initial_response_ok: bool = True) -> _Reply: ... - def starttls(self, keyfile: str | None = None, certfile: str | None = None, context: SSLContext | None = None) -> _Reply: ... + if sys.version_info >= (3, 12): + def starttls(self, *, context: SSLContext | None = None) -> _Reply: ... + else: + def starttls( + self, keyfile: str | None = None, certfile: str | None = None, context: SSLContext | None = None + ) -> _Reply: ... + def sendmail( self, from_addr: str, @@ -152,17 +158,29 @@ class SMTP_SSL(SMTP): keyfile: str | None certfile: str | None context: SSLContext - def __init__( - self, - host: str = "", - port: int = 0, - local_hostname: str | None = None, - keyfile: str | None = None, - certfile: str | None = None, - timeout: float = ..., - source_address: _SourceAddress | None = None, - context: SSLContext | None = None, - ) -> None: ... + if sys.version_info >= (3, 12): + def __init__( + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + *, + timeout: float = ..., + source_address: _SourceAddress | None = None, + context: SSLContext | None = None, + ) -> None: ... + else: + def __init__( + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + keyfile: str | None = None, + certfile: str | None = None, + timeout: float = ..., + source_address: _SourceAddress | None = None, + context: SSLContext | None = None, + ) -> None: ... LMTP_PORT: int diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/sqlite3/dbapi2.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/sqlite3/dbapi2.pyi index 41f731e21..e85f49207 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/sqlite3/dbapi2.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/sqlite3/dbapi2.pyi @@ -351,7 +351,7 @@ class Connection: @overload def cursor(self, cursorClass: None = None) -> Cursor: ... @overload - def cursor(self, cursorClass: Callable[[], _CursorT]) -> _CursorT: ... + def cursor(self, cursorClass: Callable[[Connection], _CursorT]) -> _CursorT: ... def execute(self, sql: str, parameters: _Parameters = ...) -> Cursor: ... def executemany(self, __sql: str, __parameters: Iterable[_Parameters]) -> Cursor: ... def executescript(self, __sql_script: str) -> Cursor: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/ssl.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/ssl.pyi index 1c49b130e..73762cd75 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/ssl.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/ssl.pyi @@ -201,12 +201,13 @@ class Options(enum.IntFlag): OP_NO_RENEGOTIATION: int if sys.version_info >= (3, 8): OP_ENABLE_MIDDLEBOX_COMPAT: int - if sys.platform == "linux": - OP_IGNORE_UNEXPECTED_EOF: int if sys.version_info >= (3, 12): OP_LEGACY_SERVER_CONNECT: int if sys.version_info >= (3, 12) and sys.platform != "linux": OP_ENABLE_KTLS: int + if sys.version_info >= (3, 11): + OP_IGNORE_UNEXPECTED_EOF: int + elif sys.version_info >= (3, 8) and sys.platform == "linux": OP_IGNORE_UNEXPECTED_EOF: int OP_ALL: Options @@ -224,12 +225,13 @@ OP_NO_TICKET: Options OP_NO_RENEGOTIATION: Options if sys.version_info >= (3, 8): OP_ENABLE_MIDDLEBOX_COMPAT: Options - if sys.platform == "linux": - OP_IGNORE_UNEXPECTED_EOF: Options if sys.version_info >= (3, 12): OP_LEGACY_SERVER_CONNECT: Options if sys.version_info >= (3, 12) and sys.platform != "linux": OP_ENABLE_KTLS: Options +if sys.version_info >= (3, 11): + OP_IGNORE_UNEXPECTED_EOF: Options +elif sys.version_info >= (3, 8) and sys.platform == "linux": OP_IGNORE_UNEXPECTED_EOF: Options HAS_NEVER_CHECK_COMMON_NAME: bool diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/tempfile.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/tempfile.pyi index ea0430368..61bcde242 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/tempfile.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/tempfile.pyi @@ -321,7 +321,7 @@ else: dir: GenericPath[AnyStr] | None = None, ) -> IO[Any]: ... -class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): +class _TemporaryFileWrapper(IO[AnyStr], Generic[AnyStr]): file: IO[AnyStr] # io.TextIOWrapper, io.BufferedReader or io.BufferedWriter name: str delete: bool diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/tkinter/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/tkinter/__init__.pyi index a03c48c03..a0a88a8ac 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/tkinter/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/tkinter/__init__.pyi @@ -6,7 +6,7 @@ from enum import Enum from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Generic, NamedTuple, Protocol, TypeVar, overload, type_check_only +from typing import Any, Generic, NamedTuple, TypeVar, overload, type_check_only from typing_extensions import Literal, TypeAlias, TypedDict if sys.version_info >= (3, 9): @@ -720,9 +720,6 @@ class Wm: def wm_withdraw(self) -> None: ... withdraw = wm_withdraw -class _ExceptionReportingCallback(Protocol): - def __call__(self, __exc: type[BaseException], __val: BaseException, __tb: TracebackType | None) -> object: ... - class Tk(Misc, Wm): master: None def __init__( @@ -764,7 +761,7 @@ class Tk(Misc, Wm): config = configure def destroy(self) -> None: ... def readprofile(self, baseName: str, className: str) -> None: ... - report_callback_exception: _ExceptionReportingCallback + report_callback_exception: Callable[[type[BaseException], BaseException, TracebackType | None], object] # Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo # Please keep in sync with _tkinter.TkappType. # Some methods are intentionally missing because they are inherited from Misc instead. diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/turtle.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/turtle.pyi index 80ea40879..36cd5f1f6 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/turtle.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/turtle.pyi @@ -129,6 +129,9 @@ __all__ = [ "Terminator", ] +if sys.version_info >= (3, 12): + __all__ += ["teleport"] + # Note: '_Color' is the alias we use for arguments and _AnyColor is the # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return @@ -648,6 +651,9 @@ def shape(name: None = None) -> str: ... @overload def shape(name: str) -> None: ... +if sys.version_info >= (3, 12): + def teleport(x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... + # Unsafely overlaps when no arguments are provided @overload def shapesize() -> tuple[float, float, float]: ... # type: ignore[misc] diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi index a9bffdf52..2c1ebe6d7 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi @@ -126,6 +126,9 @@ if sys.version_info >= (3, 11): "reveal_type", ] +if sys.version_info >= (3, 12): + __all__ += ["TypeAliasType", "override"] + ContextManager = AbstractContextManager AsyncContextManager = AbstractAsyncContextManager @@ -323,7 +326,9 @@ AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 # Technically in 3.7 this inherited from GenericMeta. But let's not reflect that, since # type checkers tend to assume that Protocols all have the ABCMeta metaclass. -class _ProtocolMeta(ABCMeta): ... +class _ProtocolMeta(ABCMeta): + if sys.version_info >= (3, 12): + def __init__(cls, *args: Any, **kwargs: Any) -> None: ... # Abstract base classes. @@ -945,7 +950,7 @@ if sys.version_info >= (3, 10): def _type_repr(obj: object) -> str: ... if sys.version_info >= (3, 12): - def override(__arg: _F) -> _F: ... + def override(__method: _F) -> _F: ... @_final class TypeAliasType: def __init__( diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/typing_extensions.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/typing_extensions.pyi index 32be3c030..32712a2d9 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/typing_extensions.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/typing_extensions.pyi @@ -149,6 +149,7 @@ __all__ = [ "Collection", "Container", "Dict", + "Doc", "ForwardRef", "FrozenSet", "Generator", @@ -490,6 +491,12 @@ else: def is_protocol(__tp: type) -> bool: ... def get_protocol_members(__tp: type) -> frozenset[str]: ... +class Doc: + documentation: str + def __init__(self, __documentation: str) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + # PEP 705 ReadOnly: _SpecialForm diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/__init__.pyi index 33820c793..f96d6fb18 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/__init__.pyi @@ -65,5 +65,7 @@ if sys.version_info >= (3, 8): if sys.version_info >= (3, 11): __all__ += ["enterModuleContext", "doModuleCleanups"] -def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... +if sys.version_info < (3, 12): + def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... + def __dir__() -> set[str]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/loader.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/loader.pyi index f3850c939..202309ac1 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/loader.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/loader.pyi @@ -1,3 +1,4 @@ +import sys import unittest.case import unittest.suite from collections.abc import Callable, Sequence @@ -18,7 +19,11 @@ class TestLoader: testNamePatterns: list[str] | None suiteClass: _SuiteClass def loadTestsFromTestCase(self, testCaseClass: type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... - def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: Any = None) -> unittest.suite.TestSuite: ... + if sys.version_info >= (3, 12): + def loadTestsFromModule(self, module: ModuleType, *, pattern: str | None = None) -> unittest.suite.TestSuite: ... + else: + def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: str | None = None) -> unittest.suite.TestSuite: ... + def loadTestsFromName(self, name: str, module: ModuleType | None = None) -> unittest.suite.TestSuite: ... def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = None) -> unittest.suite.TestSuite: ... def getTestCaseNames(self, testCaseClass: type[unittest.case.TestCase]) -> Sequence[str]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/main.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/main.pyi index 6d970c920..d29e9a2b8 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/main.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/main.pyi @@ -1,3 +1,4 @@ +import sys import unittest.case import unittest.loader import unittest.result @@ -23,22 +24,43 @@ class TestProgram: progName: str | None warnings: str | None testNamePatterns: list[str] | None - def __init__( - self, - module: None | str | ModuleType = "__main__", - defaultTest: str | Iterable[str] | None = None, - argv: list[str] | None = None, - testRunner: type[_TestRunner] | _TestRunner | None = None, - testLoader: unittest.loader.TestLoader = ..., - exit: bool = True, - verbosity: int = 1, - failfast: bool | None = None, - catchbreak: bool | None = None, - buffer: bool | None = None, - warnings: str | None = None, - *, - tb_locals: bool = False, - ) -> None: ... + if sys.version_info >= (3, 12): + durations: unittest.result._DurationsType | None + def __init__( + self, + module: None | str | ModuleType = "__main__", + defaultTest: str | Iterable[str] | None = None, + argv: list[str] | None = None, + testRunner: type[_TestRunner] | _TestRunner | None = None, + testLoader: unittest.loader.TestLoader = ..., + exit: bool = True, + verbosity: int = 1, + failfast: bool | None = None, + catchbreak: bool | None = None, + buffer: bool | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + durations: unittest.result._DurationsType | None = None, + ) -> None: ... + else: + def __init__( + self, + module: None | str | ModuleType = "__main__", + defaultTest: str | Iterable[str] | None = None, + argv: list[str] | None = None, + testRunner: type[_TestRunner] | _TestRunner | None = None, + testLoader: unittest.loader.TestLoader = ..., + exit: bool = True, + verbosity: int = 1, + failfast: bool | None = None, + catchbreak: bool | None = None, + buffer: bool | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + ) -> None: ... + def usageExit(self, msg: Any = None) -> None: ... def parseArgs(self, argv: list[str]) -> None: ... def createTests(self, from_discovery: bool = False, Loader: unittest.loader.TestLoader | None = None) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/mock.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/mock.pyi index 66120197b..baf025bde 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/mock.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/mock.pyi @@ -106,7 +106,25 @@ class Base: # We subclass with "Any" because mocks are explicitly designed to stand in for other types, # something that can't be expressed with our static type system. class NonCallableMock(Base, Any): - def __new__(__cls, *args: Any, **kw: Any) -> Self: ... + if sys.version_info >= (3, 12): + def __new__( + cls, + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state: Any | None = None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, + **kwargs: Any, + ) -> Self: ... + else: + def __new__(__cls, *args: Any, **kw: Any) -> Self: ... + def __init__( self, spec: list[str] | object | type[object] | None = None, diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/result.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/result.pyi index 8d78bc0f7..dfc505936 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/result.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/result.pyi @@ -1,9 +1,12 @@ +import sys import unittest.case from _typeshed import OptExcInfo from collections.abc import Callable from typing import Any, TextIO, TypeVar +from typing_extensions import TypeAlias _F = TypeVar("_F", bound=Callable[..., Any]) +_DurationsType: TypeAlias = list[tuple[str, float]] STDOUT_LINE: str STDERR_LINE: str @@ -22,6 +25,8 @@ class TestResult: buffer: bool failfast: bool tb_locals: bool + if sys.version_info >= (3, 12): + collectedDurations: _DurationsType def __init__(self, stream: TextIO | None = None, descriptions: bool | None = None, verbosity: int | None = None) -> None: ... def printErrors(self) -> None: ... def wasSuccessful(self) -> bool: ... @@ -37,3 +42,5 @@ class TestResult: def addExpectedFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: ... def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: OptExcInfo | None) -> None: ... + if sys.version_info >= (3, 12): + def addDuration(self, test: unittest.case.TestCase, elapsed: float) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/runner.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/runner.pyi index c0ddcdb49..0033083ac 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/unittest/runner.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/unittest/runner.pyi @@ -1,6 +1,8 @@ +import sys import unittest.case import unittest.result import unittest.suite +from _typeshed import Incomplete from collections.abc import Callable, Iterable from typing import TextIO from typing_extensions import TypeAlias @@ -14,23 +16,57 @@ class TextTestResult(unittest.result.TestResult): separator2: str showAll: bool # undocumented stream: TextIO # undocumented - def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... + if sys.version_info >= (3, 12): + durations: unittest.result._DurationsType | None + def __init__( + self, stream: TextIO, descriptions: bool, verbosity: int, *, durations: unittest.result._DurationsType | None = None + ) -> None: ... + else: + def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... + def getDescription(self, test: unittest.case.TestCase) -> str: ... def printErrorList(self, flavour: str, errors: Iterable[tuple[unittest.case.TestCase, str]]) -> None: ... class TextTestRunner: resultclass: _ResultClassType - def __init__( - self, - stream: TextIO | None = None, - descriptions: bool = True, - verbosity: int = 1, - failfast: bool = False, - buffer: bool = False, - resultclass: _ResultClassType | None = None, - warnings: type[Warning] | None = None, - *, - tb_locals: bool = False, - ) -> None: ... + # TODO: add `_WritelnDecorator` type + # stream: _WritelnDecorator + stream: Incomplete + descriptions: bool + verbosity: int + failfast: bool + buffer: bool + warnings: str | None + tb_locals: bool + + if sys.version_info >= (3, 12): + durations: unittest.result._DurationsType | None + def __init__( + self, + stream: TextIO | None = None, + descriptions: bool = True, + verbosity: int = 1, + failfast: bool = False, + buffer: bool = False, + resultclass: _ResultClassType | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + durations: unittest.result._DurationsType | None = None, + ) -> None: ... + else: + def __init__( + self, + stream: TextIO | None = None, + descriptions: bool = True, + verbosity: int = 1, + failfast: bool = False, + buffer: bool = False, + resultclass: _ResultClassType | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + ) -> None: ... + def _makeResult(self) -> unittest.result.TestResult: ... def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> unittest.result.TestResult: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/urllib/request.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/urllib/request.pyi index 079c97555..a4849dfa2 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/urllib/request.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/urllib/request.pyi @@ -235,7 +235,11 @@ class _HTTPConnectionProtocol(Protocol): ) -> HTTPConnection: ... class AbstractHTTPHandler(BaseHandler): # undocumented - def __init__(self, debuglevel: int = 0) -> None: ... + if sys.version_info >= (3, 12): + def __init__(self, debuglevel: int | None = None) -> None: ... + else: + def __init__(self, debuglevel: int = 0) -> None: ... + def set_http_debuglevel(self, level: int) -> None: ... def do_request_(self, request: Request) -> Request: ... def do_open(self, http_class: _HTTPConnectionProtocol, req: Request, **http_conn_args: Any) -> HTTPResponse: ... @@ -245,9 +249,15 @@ class HTTPHandler(AbstractHTTPHandler): def http_request(self, request: Request) -> Request: ... # undocumented class HTTPSHandler(AbstractHTTPHandler): - def __init__( - self, debuglevel: int = 0, context: ssl.SSLContext | None = None, check_hostname: bool | None = None - ) -> None: ... + if sys.version_info >= (3, 12): + def __init__( + self, debuglevel: int | None = None, context: ssl.SSLContext | None = None, check_hostname: bool | None = None + ) -> None: ... + else: + def __init__( + self, debuglevel: int = 0, context: ssl.SSLContext | None = None, check_hostname: bool | None = None + ) -> None: ... + def https_open(self, req: Request) -> HTTPResponse: ... def https_request(self, request: Request) -> Request: ... # undocumented diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi index ecb98d426..ca5366602 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi @@ -65,6 +65,10 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def copy(self) -> WeakValueDictionary[_KT, _VT]: ... __copy__ = copy def __deepcopy__(self, memo: Any) -> Self: ... + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] @@ -107,6 +111,10 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... __copy__ = copy def __deepcopy__(self, memo: Any) -> Self: ... + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/zipfile.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/zipfile.pyi index abda7a3b9..dc07eb3f2 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/zipfile.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/zipfile.pyi @@ -257,7 +257,11 @@ if sys.version_info >= (3, 8): @property def open(self) -> _PathOpenProtocol: ... - def iterdir(self) -> Iterator[Path]: ... + if sys.version_info >= (3, 10): + def iterdir(self) -> Iterator[Self]: ... + else: + def iterdir(self) -> Iterator[Path]: ... + def is_dir(self) -> bool: ... def is_file(self) -> bool: ... def exists(self) -> bool: ... @@ -274,6 +278,14 @@ if sys.version_info >= (3, 8): def joinpath(self, *other: StrPath) -> Path: ... else: def joinpath(self, add: StrPath) -> Path: ... # undocumented + if sys.version_info >= (3, 12): + def glob(self, pattern: str) -> Iterator[Self]: ... + def rglob(self, pattern: str) -> Iterator[Self]: ... + def is_symlink(self) -> Literal[False]: ... + def relative_to(self, other: Path, *extra: StrPath) -> str: ... + def match(self, path_pattern: str) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... def __truediv__(self, add: StrPath) -> Path: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/Pillow/PIL/ImageFont.pyi b/packages/pyright-internal/typeshed-fallback/stubs/Pillow/PIL/ImageFont.pyi index e90c4f0cc..08b987e50 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/Pillow/PIL/ImageFont.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/Pillow/PIL/ImageFont.pyi @@ -44,7 +44,7 @@ class FreeTypeFont: direction: Literal["ltr", "rtl", "ttb"] | None = None, features: Incomplete | None = None, language: str | None = None, - ) -> int: ... + ) -> float: ... def getbbox( self, text: str | bytes, diff --git a/packages/pyright-internal/typeshed-fallback/stubs/braintree/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/braintree/METADATA.toml index b5cad7abd..464274f4a 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/braintree/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/braintree/METADATA.toml @@ -1,4 +1,4 @@ -version = "4.21.*" +version = "4.22.*" upstream_repository = "https://github.com/braintree/braintree_python" partial_stub = true diff --git a/packages/pyright-internal/typeshed-fallback/stubs/flake8-bugbear/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/flake8-bugbear/METADATA.toml index ccc105020..e6bc40721 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/flake8-bugbear/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/flake8-bugbear/METADATA.toml @@ -1,4 +1,4 @@ -version = "23.7.10" +version = "23.9.16" upstream_repository = "https://github.com/PyCQA/flake8-bugbear" partial_stub = true diff --git a/packages/pyright-internal/typeshed-fallback/stubs/google-cloud-ndb/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/google-cloud-ndb/METADATA.toml index 715653337..51c55a7b5 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/google-cloud-ndb/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/google-cloud-ndb/METADATA.toml @@ -3,5 +3,5 @@ upstream_repository = "https://github.com/googleapis/python-ndb" partial_stub = true [tool.stubtest] -stubtest_requirements = ["protobuf==3.20.2"] +stubtest_requirements = ["protobuf==3.20.2", "six"] ignore_missing_stub = true diff --git a/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml index 84c775a54..d553633dd 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml @@ -1,2 +1,2 @@ -version = "2.17.*" +version = "2.18.*" # upstream_repository = closed-source diff --git a/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/METADATA.toml index e02e23ad3..14bf98b29 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/METADATA.toml @@ -1,2 +1,2 @@ -version = "3.1.*" +version = "3.2.*" upstream_repository = "https://github.com/ibmdb/python-ibmdb" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/ibm_db.pyi b/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/ibm_db.pyi index ba3063500..9ba5a3b0d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/ibm_db.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/ibm-db/ibm_db.pyi @@ -82,6 +82,93 @@ USE_WCHAR: int WCHAR_NO: int WCHAR_YES: int +# TODO: SQL_ATTR_TXN_ISOLATION: int +SQL_ATTR_ACCESS_MODE: int +SQL_ATTR_ALLOW_INTERLEAVED_GETDATA: int +SQL_ATTR_ANSI_APP: int +SQL_ATTR_APPEND_FOR_FETCH_ONLY: int +SQL_ATTR_APP_USES_LOB_LOCATOR: int +SQL_ATTR_ASYNC_ENABLE: int +SQL_ATTR_AUTO_IPD: int +SQL_ATTR_CACHE_USRLIBL: int +SQL_ATTR_CLIENT_APPLCOMPAT: int +SQL_ATTR_CLIENT_CODEPAGE: int +SQL_ATTR_COLUMNWISE_MRI: int +SQL_ATTR_COMMITONEOF: int +SQL_ATTR_CONCURRENT_ACCESS_RESOLUTION: int +SQL_ATTR_CONFIG_KEYWORDS_ARRAY_SIZE: int +SQL_ATTR_CONFIG_KEYWORDS_MAXLEN: int +SQL_ATTR_CONNECTION_DEAD: int +SQL_ATTR_CONNECTTYPE: int +SQL_ATTR_CONNECT_NODE: int +SQL_ATTR_CONNECT_PASSIVE: int +SQL_ATTR_CONN_CONTEXT: int +SQL_ATTR_CURRENT_CATALOG: int +SQL_ATTR_CURRENT_IMPLICIT_XMLPARSE_OPTION: int +SQL_ATTR_CURRENT_PACKAGE_PATH: int +SQL_ATTR_CURRENT_PACKAGE_SET: int +SQL_ATTR_DATE_FMT: int +SQL_ATTR_DATE_SEP: int +SQL_ATTR_DB2EXPLAIN: int +SQL_ATTR_DB2_APPLICATION_HANDLE: int +SQL_ATTR_DB2_APPLICATION_ID: int +SQL_ATTR_DB2_SQLERRP: int +SQL_ATTR_DECFLOAT_ROUNDING_MODE: int +SQL_ATTR_DECIMAL_SEP: int +SQL_ATTR_DESCRIBE_CALL: int +SQL_ATTR_DESCRIBE_OUTPUT_LEVEL: int +SQL_ATTR_DETECT_READ_ONLY_TXN: int +SQL_ATTR_ENLIST_IN_DTC: int +SQL_ATTR_EXTENDED_INDICATORS: int +SQL_ATTR_FET_BUF_SIZE: int +SQL_ATTR_FORCE_ROLLBACK: int +SQL_ATTR_FREE_LOCATORS_ON_FETCH: int +SQL_ATTR_GET_LATEST_MEMBER: int +SQL_ATTR_GET_LATEST_MEMBER_NAME: int +SQL_ATTR_IGNORE_SERVER_LIST: int +SQL_ATTR_INFO_CRRTKN: int +SQL_ATTR_INFO_PROGRAMID: int +SQL_ATTR_KEEP_DYNAMIC: int +SQL_ATTR_LOB_CACHE_SIZE: int +SQL_ATTR_LOB_FILE_THRESHOLD: int +SQL_ATTR_LOGIN_TIMEOUT: int +SQL_ATTR_LONGDATA_COMPAT: int +SQL_ATTR_MAPCHAR: int +SQL_ATTR_MAXBLKEXT: int +SQL_ATTR_MAX_LOB_BLOCK_SIZE: int +SQL_ATTR_NETWORK_STATISTICS: int +SQL_ATTR_OVERRIDE_CHARACTER_CODEPAGE: int +SQL_ATTR_OVERRIDE_CODEPAGE: int +SQL_ATTR_OVERRIDE_PRIMARY_AFFINITY: int +SQL_ATTR_PARC_BATCH: int +SQL_ATTR_PING_DB: int +SQL_ATTR_PING_NTIMES: int +SQL_ATTR_PING_REQUEST_PACKET_SIZE: int +SQL_ATTR_QUERY_PREFETCH: int +SQL_ATTR_QUIET_MODE: int +SQL_ATTR_READ_ONLY_CONNECTION: int +SQL_ATTR_RECEIVE_TIMEOUT: int +SQL_ATTR_REOPT: int +SQL_ATTR_REPORT_ISLONG_FOR_LONGTYPES_OLEDB: int +SQL_ATTR_REPORT_SEAMLESSFAILOVER_WARNING: int +SQL_ATTR_REPORT_TIMESTAMP_TRUNC_AS_WARN: int +SQL_ATTR_RETRYONERROR: int +SQL_ATTR_RETRY_ON_MERGE: int +SQL_ATTR_SERVER_MSGTXT_MASK: int +SQL_ATTR_SERVER_MSGTXT_SP: int +SQL_ATTR_SESSION_GLOBAL_VAR: int +SQL_ATTR_SESSION_TIME_ZONE: int +SQL_ATTR_SPECIAL_REGISTER: int +SQL_ATTR_SQLCOLUMNS_SORT_BY_ORDINAL_OLEDB: int +SQL_ATTR_STMT_CONCENTRATOR: int +SQL_ATTR_STREAM_GETDATA: int +SQL_ATTR_STREAM_OUTPUTLOB_ON_CALL: int +SQL_ATTR_TIME_FMT: int +SQL_ATTR_TIME_SEP: int +SQL_ATTR_TRUSTED_CONTEXT_ACCESSTOKEN: int +SQL_ATTR_USER_REGISTRY_NAME: int +SQL_ATTR_WCHARTYPE: int + @final class IBM_DBClientInfo: def __new__(cls, *args: object, **kwargs: object) -> Self: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/libsass/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/libsass/METADATA.toml new file mode 100644 index 000000000..2d48b88a6 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/libsass/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.22.*" +requires = ["types-setuptools"] +upstream_repository = "https://github.com/sass/libsass-python" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/libsass/sass.pyi b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sass.pyi new file mode 100644 index 000000000..d43fe4e5d --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sass.pyi @@ -0,0 +1,176 @@ +import enum +from _typeshed import ReadableBuffer, SupportsKeysAndGetItem +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Set as AbstractSet +from typing import Any, Generic, NamedTuple, SupportsFloat, TypeVar, overload, type_check_only +from typing_extensions import Literal, ParamSpec, Self, SupportsIndex, TypeAlias + +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT_co = TypeVar("_VT_co", covariant=True) +_P = ParamSpec("_P") +_Mode: TypeAlias = Literal["string", "filename", "dirname"] +_OutputStyle: TypeAlias = Literal["nested", "expanded", "compact", "compressed"] +_ConvertsToFloat: TypeAlias = SupportsFloat | SupportsIndex | str | ReadableBuffer +_CustomFunctions: TypeAlias = Mapping[str, Callable[..., Any]] | Sequence[Callable[..., Any]] | AbstractSet[Callable[..., Any]] +_ImportCallbackRet: TypeAlias = ( + list[tuple[str, str, str]] | list[tuple[str, str]] | list[tuple[str]] | list[tuple[str, ...]] | None +) +_ImportCallback: TypeAlias = Callable[[str], _ImportCallbackRet] | Callable[[str, str], _ImportCallbackRet] + +__version__: str +libsass_version: str +OUTPUT_STYLES: dict[str, int] +SOURCE_COMMENTS: dict[str, int] +MODES: frozenset[_Mode] + +class CompileError(ValueError): + def __init__(self, msg: str) -> None: ... + +# _P needs to be positional only and can't contain varargs, but there is no way to express that +# the arguments also need +class SassFunction(Generic[_P, _T]): + @classmethod + def from_lambda(cls, name: str, lambda_: Callable[_P, _T]) -> SassFunction[_P, _T]: ... + @classmethod + def from_named_function(cls, function: Callable[_P, _T]) -> SassFunction[_P, _T]: ... + name: str + arguments: tuple[str, ...] + callable_: Callable[_P, _T] + def __init__(self, name: str, arguments: Sequence[str], callable_: Callable[_P, _T]) -> None: ... + @property + def signature(self) -> str: ... + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: ... + +@overload +def compile( + *, + string: str, + output_style: _OutputStyle = "nested", + source_comments: bool = False, + source_map_contents: bool = False, + source_map_embed: bool = False, + omit_source_map_url: bool = False, + source_map_root: str | None = None, + include_paths: Sequence[str] = (), + precision: int = 5, + custom_functions: _CustomFunctions = (), + indented: bool = False, + importers: Iterable[tuple[int, _ImportCallback]] | None = None, +) -> str: ... +@overload +def compile( + *, + filename: str, + output_style: _OutputStyle = "nested", + source_comments: bool = False, + source_map_filename: None = None, + output_filename_hint: str | None = None, + source_map_contents: bool = False, + source_map_embed: bool = False, + omit_source_map_url: bool = False, + source_map_root: str | None = None, + include_paths: Sequence[str] = (), + precision: int = 5, + custom_functions: _CustomFunctions = (), + importers: Iterable[tuple[int, _ImportCallback]] | None = None, +) -> str: ... +@overload +def compile( + *, + filename: str, + output_style: _OutputStyle = "nested", + source_comments: bool = False, + source_map_filename: str, + output_filename_hint: str | None = None, + source_map_contents: bool = False, + source_map_embed: bool = False, + omit_source_map_url: bool = False, + source_map_root: str | None = None, + include_paths: Sequence[str] = (), + precision: int = 5, + custom_functions: _CustomFunctions = (), + importers: Iterable[tuple[int, _ImportCallback]] | None = None, +) -> tuple[str, str]: ... +@overload +def compile( + *, + dirname: tuple[str, str], + output_style: _OutputStyle = "nested", + source_comments: bool = False, + source_map_contents: bool = False, + source_map_embed: bool = False, + omit_source_map_url: bool = False, + source_map_root: str | None = None, + include_paths: Sequence[str] = (), + precision: int = 5, + custom_functions: _CustomFunctions = (), + importers: Iterable[tuple[int, _ImportCallback]] | None = None, +) -> None: ... +def and_join(strings: Sequence[str]) -> str: ... +@type_check_only +class _SassNumber(NamedTuple): + value: float + unit: str + +class SassNumber(_SassNumber): + def __new__(cls, value: _ConvertsToFloat, unit: str | bytes) -> Self: ... + +@type_check_only +class _SassColor(NamedTuple): + r: float + g: float + b: float + a: float + +class SassColor(_SassColor): + def __new__(cls, r: _ConvertsToFloat, g: _ConvertsToFloat, b: _ConvertsToFloat, a: _ConvertsToFloat) -> Self: ... + +@type_check_only +class _Separator(enum.Enum): + SASS_SEPARATOR_COMMA = enum.auto() + SASS_SEPARATOR_SPACE = enum.auto() + +SASS_SEPARATOR_COMMA: Literal[_Separator.SASS_SEPARATOR_COMMA] +SASS_SEPARATOR_SPACE: Literal[_Separator.SASS_SEPARATOR_SPACE] + +@type_check_only +class _SassList(NamedTuple, Generic[_T]): + items: tuple[_T, ...] + separator: _Separator + bracketed: bool + +class SassList(_SassList[_T]): + def __new__(cls, items: Iterable[_T], separator: _Separator, bracketed: bool = ...) -> SassList[_T]: ... + +@type_check_only +class _SassError(NamedTuple): + msg: str + +class SassError(_SassError): + def __new__(cls, msg: str | bytes) -> Self: ... + +@type_check_only +class _SassWarning(NamedTuple): + msg: str + +class SassWarning(_SassWarning): + def __new__(cls, msg: str | bytes) -> Self: ... + +class SassMap(Mapping[_KT, _VT_co]): + # copied from dict.__init__ in builtins.pyi, since it uses dict() internally + @overload + def __init__(self) -> None: ... + @overload + def __init__(self: SassMap[str, _VT_co], **kwargs: _VT_co) -> None: ... + @overload + def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT_co]) -> None: ... + @overload + def __init__(self: SassMap[str, _VT_co], __map: SupportsKeysAndGetItem[str, _VT_co], **kwargs: _VT_co) -> None: ... + @overload + def __init__(self, __iterable: Iterable[tuple[_KT, _VT_co]]) -> None: ... + @overload + def __init__(self: SassMap[str, _VT_co], __iterable: Iterable[tuple[str, _VT_co]], **kwargs: _VT_co) -> None: ... + def __getitem__(self, key: _KT) -> _VT_co: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + def __hash__(self) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/builder.pyi b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/builder.pyi new file mode 100644 index 000000000..7d23a6fbb --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/builder.pyi @@ -0,0 +1,34 @@ +from collections.abc import Mapping +from re import Pattern +from typing import Any + +from sass import _OutputStyle + +SUFFIXES: frozenset[str] +SUFFIX_PATTERN: Pattern[str] + +def build_directory( + sass_path: str, + css_path: str, + output_style: _OutputStyle = "nested", + _root_sass: None = None, # internal arguments for recursion + _root_css: None = None, # internal arguments for recursion + strip_extension: bool = False, +) -> dict[str, str]: ... + +class Manifest: + @classmethod + def normalize_manifests( + cls, manifests: Mapping[str, Manifest | tuple[Any, ...] | Mapping[str, Any] | str] | None + ) -> dict[str, Manifest]: ... + sass_path: str + css_path: str + wsgi_path: str + strip_extension: bool + def __init__( + self, sass_path: str, css_path: str | None = None, wsgi_path: str | None = None, strip_extension: bool | None = None + ) -> None: ... + def resolve_filename(self, package_dir: str, filename: str) -> tuple[str, str]: ... + def unresolve_filename(self, package_dir: str, filename: str) -> str: ... + def build(self, package_dir: str, output_style: _OutputStyle = "nested") -> frozenset[str]: ... + def build_one(self, package_dir: str, filename: str, source_map: bool = False) -> str: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/distutils.pyi b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/distutils.pyi new file mode 100644 index 000000000..309488346 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/distutils.pyi @@ -0,0 +1,14 @@ +from sassutils.builder import Manifest as Manifest +from setuptools import Command, Distribution + +def validate_manifests(dist: Distribution, attr: str, value: object) -> None: ... + +class build_sass(Command): + description: str + user_options: list[tuple[str, str, str]] + package_dir: dict[str, str] | None + output_style: str + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_package_dir(self, package: str) -> str: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/wsgi.pyi b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/wsgi.pyi new file mode 100644 index 000000000..fa2a9d792 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/libsass/sassutils/wsgi.pyi @@ -0,0 +1,22 @@ +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable, Mapping +from typing import Any + +from sassutils.builder import Manifest + +class SassMiddleware: + app: WSGIApplication + manifests: dict[str, Manifest] + error_status: str + package_dir: Mapping[str, str] + paths: list[tuple[str, str, Manifest]] + def __init__( + self, + app: WSGIApplication, + manifests: Mapping[str, Manifest | tuple[Any, ...] | Mapping[str, Any] | str] | None, + package_dir: Mapping[str, str] = {}, + error_status: str = "200 OK", + ) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + @staticmethod + def quote_css_string(s: str) -> str: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/mock/mock/mock.pyi b/packages/pyright-internal/typeshed-fallback/stubs/mock/mock/mock.pyi index 0479bde4c..04e314e30 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/mock/mock/mock.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/mock/mock/mock.pyi @@ -89,7 +89,7 @@ class NonCallableMock(Base, Any): def __new__( cls, spec: list[str] | object | type[object] | None = None, - wraps: Incomplete | None = None, + wraps: Any | None = None, name: str | None = None, spec_set: list[str] | object | type[object] | None = None, parent: NonCallableMock | None = None, @@ -104,7 +104,7 @@ class NonCallableMock(Base, Any): def __init__( self, spec: list[str] | object | type[object] | None = None, - wraps: Incomplete | None = None, + wraps: Any | None = None, name: str | None = None, spec_set: list[str] | object | type[object] | None = None, parent: NonCallableMock | None = None, diff --git a/packages/pyright-internal/typeshed-fallback/stubs/netaddr/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/netaddr/METADATA.toml index b4cfb9f54..d41665082 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/netaddr/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/netaddr/METADATA.toml @@ -1,2 +1,2 @@ -version = "0.8.*" +version = "0.9.*" upstream_repository = "https://github.com/drkjam/netaddr" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/netaddr/netaddr/ip/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/netaddr/netaddr/ip/__init__.pyi index 24ed94f73..58a921df1 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/netaddr/netaddr/ip/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/netaddr/netaddr/ip/__init__.pyi @@ -167,7 +167,7 @@ IPV4_LINK_LOCAL: IPNetwork IPV4_MULTICAST: IPNetwork IPV4_6TO4: IPNetwork IPV4_RESERVED: tuple[IPNetwork | IPRange, ...] -IPV6_LOOPBACK: IPAddress +IPV6_LOOPBACK: IPNetwork IPV6_PRIVATE: tuple[IPNetwork, ...] IPV6_LINK_LOCAL: IPNetwork IPV6_MULTICAST: IPNetwork diff --git a/packages/pyright-internal/typeshed-fallback/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi b/packages/pyright-internal/typeshed-fallback/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi index 447fd0750..4bc3a3644 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi @@ -1,32 +1,43 @@ from typing import Any +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.clients import Client + log: Any class RequestValidator: - def client_authentication_required(self, request, *args, **kwargs): ... - def authenticate_client(self, request, *args, **kwargs) -> None: ... - def authenticate_client_id(self, client_id, request, *args, **kwargs) -> None: ... - def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, *args, **kwargs) -> None: ... - def get_default_redirect_uri(self, client_id, request, *args, **kwargs) -> None: ... - def get_default_scopes(self, client_id, request, *args, **kwargs) -> None: ... - def get_original_scopes(self, refresh_token, request, *args, **kwargs) -> None: ... - def is_within_original_scope(self, request_scopes, refresh_token, request, *args, **kwargs): ... - def introspect_token(self, token, token_type_hint, request, *args, **kwargs) -> None: ... - def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs) -> None: ... - def revoke_token(self, token, token_type_hint, request, *args, **kwargs) -> None: ... - def rotate_refresh_token(self, request): ... - def save_authorization_code(self, client_id, code, request, *args, **kwargs) -> None: ... - def save_token(self, token, request, *args, **kwargs): ... - def save_bearer_token(self, token, request, *args, **kwargs) -> None: ... - def validate_bearer_token(self, token, scopes, request) -> None: ... - def validate_client_id(self, client_id, request, *args, **kwargs) -> None: ... - def validate_code(self, client_id, code, client, request, *args, **kwargs) -> None: ... - def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs) -> None: ... - def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs) -> None: ... - def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs) -> None: ... - def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs) -> None: ... - def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs) -> None: ... - def validate_user(self, username, password, client, request, *args, **kwargs) -> None: ... - def is_pkce_required(self, client_id, request): ... - def get_code_challenge(self, code, request) -> None: ... - def get_code_challenge_method(self, code, request) -> None: ... + def client_authentication_required(self, request: Request, *args, **kwargs) -> bool: ... + def authenticate_client(self, request: Request, *args, **kwargs) -> bool: ... + def authenticate_client_id(self, client_id: str, request: Request, *args, **kwargs) -> bool: ... + def confirm_redirect_uri( + self, client_id: str, code: str, redirect_uri: str, client: Client, request: Request, *args, **kwargs + ) -> bool: ... + def get_default_redirect_uri(self, client_id: str, request: Request, *args, **kwargs) -> str: ... + def get_default_scopes(self, client_id: str, request: Request, *args, **kwargs) -> list[str]: ... + def get_original_scopes(self, refresh_token: str, request: Request, *args, **kwargs) -> list[str]: ... + def is_within_original_scope( + self, request_scopes: list[str], refresh_token: str, request: Request, *args, **kwargs + ) -> bool: ... + def introspect_token( + self, token: str, token_type_hint: str, request: Request, *args, **kwargs + ) -> dict[str, int | str | list[str]] | None: ... + def invalidate_authorization_code(self, client_id: str, code: str, request: Request, *args, **kwargs) -> None: ... + def revoke_token(self, token: str, token_type_hint: str, request: Request, *args, **kwargs) -> None: ... + def rotate_refresh_token(self, request: Request) -> bool: ... + def save_authorization_code(self, client_id: str, code: str, request: Request, *args, **kwargs) -> None: ... + def save_token(self, token: dict[str, int | str], request: Request, *args, **kwargs) -> None: ... + def save_bearer_token(self, token: dict[str, int | str], request: Request, *args, **kwargs) -> str: ... + def validate_bearer_token(self, token: str, scopes: list[str], request: Request) -> bool: ... + def validate_client_id(self, client_id: str, request: Request, *args, **kwargs) -> bool: ... + def validate_code(self, client_id: str, code: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_grant_type(self, client_id: str, grant_type: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_redirect_uri(self, client_id: str, redirect_uri: str, request: Request, *args, **kwargs) -> bool: ... + def validate_refresh_token(self, refresh_token: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_response_type( + self, client_id: str, response_type: str, client: Client, request: Request, *args, **kwargs + ) -> bool: ... + def validate_scopes(self, client_id: str, scopes: list[str], client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_user(self, username: str, password: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def is_pkce_required(self, client_id: str, request: Request) -> bool: ... + def get_code_challenge(self, code: str, request: Request) -> str: ... + def get_code_challenge_method(self, code: str, request: Request) -> str: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/axis.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/axis.pyi index 36a5e5d53..229080a5e 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/axis.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/axis.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete, Unused from typing import ClassVar, overload -from typing_extensions import Literal, TypeAlias +from typing_extensions import Literal, Self, TypeAlias from openpyxl.chart.layout import Layout from openpyxl.chart.shapes import GraphicalProperties @@ -19,7 +19,7 @@ from openpyxl.descriptors.nested import ( ) from openpyxl.descriptors.serialisable import Serialisable -from ..xml._functions_overloads import _HasTagAndGet +from ..xml._functions_overloads import _HasTagAndGet, _SupportsFindAndIterAndAttribAndText _ScalingOrientation: TypeAlias = Literal["maxMin", "minMax"] _BaseAxisAxPos: TypeAlias = Literal["b", "l", "r", "t"] @@ -198,7 +198,7 @@ class NumericAxis(_BaseAxis): **kw, ) -> None: ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _SupportsFindAndIterAndAttribAndText) -> Self: ... class TextAxis(_BaseAxis): tagname: ClassVar[str] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/plotarea.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/plotarea.pyi index caaa62a0d..3e80697ac 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/plotarea.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/plotarea.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete, Unused from typing import ClassVar -from typing_extensions import Literal +from typing_extensions import Literal, Self from openpyxl.chart.layout import Layout from openpyxl.chart.shapes import GraphicalProperties @@ -8,7 +8,7 @@ from openpyxl.chart.text import RichText from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool from openpyxl.descriptors.excel import ExtensionList from openpyxl.descriptors.nested import NestedBool -from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement from ..xml._functions_overloads import _HasTagAndGet @@ -73,4 +73,4 @@ class PlotArea(Serialisable): ) -> None: ... def to_tree(self, tagname: str | None = None, idx: Incomplete | None = None, namespace: str | None = None): ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/nested.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/nested.pyi index caabf89d7..8a7af3be8 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/nested.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/nested.pyi @@ -9,7 +9,7 @@ from openpyxl.descriptors.serialisable import Serialisable from openpyxl.drawing.fill import Blip from openpyxl.xml.functions import Element -from ..xml._functions_overloads import _HasTagAndGet, _HasTagAndText +from ..xml._functions_overloads import _HasGet, _HasTagAndGet, _HasText from .base import _M, _N, _T, _ConvertibleToBool, _ConvertibleToFloat, _ConvertibleToInt, _ExpectedTypeParam _NestedNoneSetParam: TypeAlias = _HasTagAndGet[_T | Literal["none"] | None] | _T | Literal["none"] | None @@ -35,7 +35,7 @@ class Nested(Descriptor[_T]): ) -> None: ... def __get__(self, instance: Serialisable | Strict, cls: type | None) -> _T: ... def __set__(self, instance: Serialisable | Strict, value: _HasTagAndGet[_T] | _T) -> None: ... - def from_tree(self, node: _HasTagAndGet[_T]) -> _T: ... + def from_tree(self, node: _HasGet[_T]) -> _T: ... def to_tree(self, tagname: str | None = None, value: Incomplete | None = None, namespace: str | None = None) -> Element: ... class NestedValue(Nested[_T], Convertible[_T, _N]): # type: ignore[misc] @@ -150,7 +150,7 @@ class NestedText(NestedValue[_T, _N]): # Anything else @overload def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _T | int | Any | None) -> None: ... - def from_tree(self, node: _HasTagAndText) -> str: ... # type: ignore[override] + def from_tree(self, node: _HasText) -> str: ... # type: ignore[override] def to_tree(self, tagname: str | None = None, value: Incomplete | None = None, namespace: str | None = None) -> Element: ... class NestedFloat(NestedValue[float, _N], Float[_N]): # type: ignore[misc] @@ -179,7 +179,7 @@ class NestedBool(NestedValue[bool, _N], Bool[_N]): # type: ignore[misc] def __set__( # type:ignore[override] # Different restrictions self, instance: Serialisable | Strict, value: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool ) -> None: ... - def from_tree(self, node) -> bool: ... # type: ignore[override] # Actual overriden return type + def from_tree(self, node: _HasGet[bool]) -> bool: ... # type: ignore[override] # Actual overriden return type class NestedNoneSet(Nested[_T | None], NoneSet[_T]): # type: ignore[misc] def __init__(self, name: str | None = None, *, values: Iterable[_T | None]) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi index ff2176f25..ef3d3096f 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi @@ -1,12 +1,20 @@ from _typeshed import Incomplete, Unused -from collections.abc import Generator -from typing_extensions import Self +from collections.abc import Generator, Iterable +from typing import Any, Protocol +from typing_extensions import Self, TypeVar from openpyxl.descriptors import Strict -from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.descriptors.serialisable import Serialisable, _SerialisableTreeElement +from openpyxl.xml._functions_overloads import _HasGet from .base import Alias, Descriptor +_T = TypeVar("_T") + +class _SupportsFromTree(Protocol): + @classmethod + def from_tree(cls, node: _SerialisableTreeElement) -> Any: ... + class Sequence(Descriptor[Incomplete]): expected_type: type[Incomplete] seq_types: tuple[type, ...] @@ -23,12 +31,15 @@ class UniqueSequence(Sequence): class ValueSequence(Sequence): attribute: str def to_tree(self, tagname, obj, namespace: str | None = None) -> Generator[Incomplete, None, None]: ... - def from_tree(self, node): ... + def from_tree(self, node: _HasGet[_T]) -> _T: ... class NestedSequence(Sequence): count: bool + expected_type: type[_SupportsFromTree] def to_tree(self, tagname, obj, namespace: str | None = None): ... - def from_tree(self, node): ... + # returned list generic type should be same as the return type of expected_type.from_tree(node) + # Which can really be anything given the wildly different, and sometimes generic, from_tree return types + def from_tree(self, node: Iterable[_SerialisableTreeElement]) -> list[Any]: ... class MultiSequence(Sequence): def __set__(self, instance: Serialisable | Strict, seq) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi index 3afff355f..7da292d88 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi @@ -1,16 +1,14 @@ from _typeshed import Incomplete, SupportsIter from typing import Any, ClassVar, NoReturn, Protocol -from typing_extensions import Final +from typing_extensions import Final, Self from openpyxl.descriptors import MetaSerialisable -from ..xml._functions_overloads import _HasAttrib, _HasTagAndGet, _HasText +from ..xml._functions_overloads import _HasAttrib, _HasGet, _HasText, _SupportsFindChartLines # For any override directly re-using Serialisable.from_tree class _ChildSerialisableTreeElement(_HasAttrib, _HasText, SupportsIter[Incomplete], Protocol): ... - -class _SerialisableTreeElement(_HasTagAndGet[Incomplete], _ChildSerialisableTreeElement, Protocol): - def find(self, __path: str) -> Incomplete | None: ... +class _SerialisableTreeElement(_HasGet[object], _SupportsFindChartLines, _ChildSerialisableTreeElement, Protocol): ... KEYWORDS: Final[frozenset[str]] seq_types: Final[tuple[type[list[Any]], type[tuple[Any, ...]]]] @@ -26,12 +24,13 @@ class Serialisable(metaclass=MetaSerialisable): @property def tagname(self) -> str | NoReturn: ... namespace: ClassVar[str | None] - # Note: To respect the Liskov substitution principle, the protocol for node includes all child class requirements + # Note: To respect the Liskov substitution principle, the protocol for node includes all child class requirements. + # Same with the return type to avoid override issues. # See comment in xml/functions.pyi as to why use a protocol instead of Element # Child classes should be more precise than _SerialisableTreeElement ! # Use _ChildSerialisableTreeElement instead for child classes that reuse Serialisable.from_tree directly. @classmethod - def from_tree(cls, node: _SerialisableTreeElement): ... + def from_tree(cls, node: _SerialisableTreeElement) -> Self | None: ... def to_tree(self, tagname: str | None = None, idx: Incomplete | None = None, namespace: str | None = None): ... def __iter__(self): ... def __eq__(self, other): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi index 9aadb179c..048329b94 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi @@ -16,6 +16,7 @@ from openpyxl.descriptors.base import ( _ConvertibleToInt, ) from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement _T = TypeVar("_T") @@ -57,7 +58,7 @@ class CustomPropertyList(Strict): props: Sequence def __init__(self) -> None: ... @classmethod - def from_tree(cls, tree) -> Self: ... + def from_tree(cls, tree: _ChildSerialisableTreeElement) -> Self: ... def append(self, prop) -> None: ... def to_tree(self): ... def __len__(self) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi index b65e4d567..f8bf1b486 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi @@ -1,4 +1,5 @@ from _typeshed import Incomplete +from collections.abc import Iterable, Sequence as ABCSequence from typing import ClassVar from typing_extensions import Final, Literal, TypeAlias @@ -6,6 +7,8 @@ from openpyxl.descriptors import Sequence from openpyxl.descriptors.base import Alias, Float, MinMax, NoneSet, Set, _ConvertibleToFloat from openpyxl.descriptors.serialisable import Serialisable +from ..xml._functions_overloads import _SupportsIterAndAttribAndTextAndTag + FILL_NONE: Final = "none" FILL_SOLID: Final = "solid" FILL_PATTERN_DARKDOWN: Final = "darkDown" @@ -53,7 +56,7 @@ fills: tuple[_FillsType, ...] class Fill(Serialisable): tagname: ClassVar[str] @classmethod - def from_tree(cls, el): ... + def from_tree(cls, el: Iterable[ABCSequence[_SupportsIterAndAttribAndTextAndTag]]) -> PatternFill | GradientFill | None: ... class PatternFill(Fill): tagname: ClassVar[str] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fonts.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fonts.pyi index 923d8a850..d8ab9e06d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fonts.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fonts.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete from typing import ClassVar -from typing_extensions import Final, Literal, TypeAlias +from typing_extensions import Final, Literal, Self, TypeAlias from openpyxl.descriptors.base import Alias, _ConvertibleToBool, _ConvertibleToFloat, _ConvertibleToInt from openpyxl.descriptors.nested import ( @@ -14,7 +14,7 @@ from openpyxl.descriptors.nested import ( ) from openpyxl.descriptors.serialisable import Serialisable -from ..xml._functions_overloads import _HasTagAndGet +from ..xml._functions_overloads import _HasTagAndGet, _SupportsFindAndIterAndAttribAndText _FontU: TypeAlias = Literal["single", "double", "singleAccounting", "doubleAccounting"] _FontVertAlign: TypeAlias = Literal["superscript", "subscript", "baseline"] @@ -71,6 +71,6 @@ class Font(Serialisable): extend: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, ) -> None: ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _SupportsFindAndIterAndAttribAndText) -> Self: ... DEFAULT_FONT: Final[Font] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/stylesheet.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/stylesheet.pyi index 1d7b2fe26..b3c1465ad 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/stylesheet.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/stylesheet.pyi @@ -1,10 +1,10 @@ from _typeshed import Incomplete, Unused from typing import ClassVar -from typing_extensions import Literal +from typing_extensions import Literal, Self from openpyxl.descriptors.base import Typed from openpyxl.descriptors.excel import ExtensionList -from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement from openpyxl.styles.cell_style import CellStyleList from openpyxl.styles.colors import ColorList from openpyxl.styles.named_styles import _NamedCellStyleList @@ -45,7 +45,7 @@ class Stylesheet(Serialisable): extLst: Unused = None, ) -> None: ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... @property def custom_formats(self): ... def to_tree(self, tagname: str | None = None, idx: Incomplete | None = None, namespace: str | None = None): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/protection.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/protection.pyi index 1b4c732b1..236dfceb6 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/protection.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/protection.pyi @@ -1,10 +1,12 @@ from _typeshed import Incomplete from typing import ClassVar -from typing_extensions import Literal +from typing_extensions import Literal, Self from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool, _ConvertibleToInt from openpyxl.descriptors.serialisable import Serialisable +from ..xml._functions_overloads import _SupportsIterAndAttribAndTextAndGet + class WorkbookProtection(Serialisable): tagname: ClassVar[str] workbook_password: Alias @@ -55,7 +57,7 @@ class WorkbookProtection(Serialisable): @revisionsPassword.setter def revisionsPassword(self, value) -> None: ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _SupportsIterAndAttribAndTextAndGet) -> Self: ... DocumentSecurity = WorkbookProtection diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi index 56a09f5b5..0ef744d1b 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi @@ -12,9 +12,7 @@ class CellRange(Serialisable): min_row: MinMax[int, Literal[False]] max_col: MinMax[int, Literal[False]] max_row: MinMax[int, Literal[False]] - # Could be None if the caller forgot to set title and range_string doesn't contain "!" - # but that's not intended and will lead to errors (ie: can't be None in __str__) - title: str + title: str | None @overload def __init__( @@ -35,7 +33,7 @@ class CellRange(Serialisable): min_row: _ConvertibleToInt, max_col: _ConvertibleToInt, max_row: _ConvertibleToInt, - title: str, + title: str | None = None, ) -> None: ... @property def bounds(self): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi index e8066e023..714e6ef6c 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi @@ -1,11 +1,13 @@ from re import Pattern from typing import ClassVar -from typing_extensions import Final, Literal +from typing_extensions import Final, Literal, Self from openpyxl.descriptors import Strict from openpyxl.descriptors.base import Alias, Bool, Integer, MatchPattern, String, Typed, _ConvertibleToBool, _ConvertibleToInt from openpyxl.descriptors.serialisable import Serialisable +from ..xml._functions_overloads import _HasText + FONT_PATTERN: Final = '&"(?P.+)"' COLOR_PATTERN: Final = "&K(?P[A-F0-9]{6})" SIZE_REGEX: Final = r"&(?P\d+\s?)" @@ -38,7 +40,7 @@ class HeaderFooterItem(Strict): def __bool__(self) -> bool: ... def to_tree(self, tagname): ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _HasText) -> Self: ... class HeaderFooter(Serialisable): tagname: ClassVar[str] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/page.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/page.pyi index 06a96e133..2538cabf0 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/page.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/page.pyi @@ -1,9 +1,9 @@ from _typeshed import Incomplete from typing import ClassVar -from typing_extensions import Literal, TypeAlias +from typing_extensions import Literal, Self, TypeAlias from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, _ConvertibleToBool, _ConvertibleToFloat, _ConvertibleToInt -from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement _PrintPageSetupOrientation: TypeAlias = Literal["default", "portrait", "landscape"] _PrintPageSetupPageOrder: TypeAlias = Literal["downThenOver", "overThenDown"] @@ -66,7 +66,7 @@ class PrintPageSetup(Serialisable): @autoPageBreaks.setter def autoPageBreaks(self, value) -> None: ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... class PrintOptions(Serialisable): tagname: ClassVar[str] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/table.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/table.pyi index 8b48b4a02..03f0e0ffb 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/table.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/table.pyi @@ -1,11 +1,11 @@ from _typeshed import Incomplete, Unused from typing import ClassVar, overload -from typing_extensions import Final, Literal, TypeAlias +from typing_extensions import Final, Literal, Self, TypeAlias from openpyxl.descriptors import Strict, String from openpyxl.descriptors.base import Alias, Bool, Integer, NoneSet, Typed, _ConvertibleToBool, _ConvertibleToInt from openpyxl.descriptors.excel import ExtensionList -from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement from openpyxl.worksheet.filters import AutoFilter, SortState _TableColumnTotalsRowFunction: TypeAlias = Literal[ @@ -129,7 +129,7 @@ class TableColumn(Serialisable): ) -> None: ... def __iter__(self): ... @classmethod - def from_tree(cls, node): ... + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... class TableNameDescriptor(String[Incomplete]): def __set__(self, instance: Serialisable | Strict, value) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi index 06437d35f..af057881a 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi @@ -1,12 +1,14 @@ # This file does not exist at runtime. It is a helper file to overload imported functions in openpyxl.xml.functions import sys -from _typeshed import Incomplete, ReadableBuffer +from _typeshed import Incomplete, ReadableBuffer, SupportsIter from collections.abc import Iterable, Iterator, Mapping, Sequence from typing import Any, Protocol, TypeVar, overload from typing_extensions import TypeAlias from xml.etree.ElementTree import Element, ElementTree, QName, XMLParser, _FileRead +from openpyxl.chart.axis import ChartLines + _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -17,18 +19,30 @@ _T_co = TypeVar("_T_co", covariant=True) class _HasTag(Protocol): tag: Any # AnyOf[str, None, Callable[..., AnyOf[str, None]]] +class _HasGet(Protocol[_T_co]): + def get(self, __value: str) -> _T_co | None: ... + class _HasText(Protocol): text: str class _HasAttrib(Protocol): attrib: Iterable[Any] # AnyOf[dict[str, str], Iterable[tuple[str, str]]] -class _HasTagAndGet(_HasTag, Protocol[_T_co]): - def get(self, __value: str) -> _T_co | None: ... - +class _HasTagAndGet(_HasTag, _HasGet[_T_co], Protocol[_T_co]): ... class _HasTagAndText(_HasTag, _HasText, Protocol): ... # noqa: Y046 class _HasTagAndTextAndAttrib(_HasTag, _HasText, _HasAttrib, Protocol): ... # noqa: Y046 +class _SupportsFindChartLines(Protocol): + def find(self, __path: str) -> ChartLines | None: ... + +class _SupportsFindAndIterAndAttribAndText( # noqa: Y046 + _SupportsFindChartLines, SupportsIter[Incomplete], _HasAttrib, _HasText, Protocol +): ... +class _SupportsIterAndAttribAndTextAndTag(SupportsIter[Incomplete], _HasAttrib, _HasText, _HasTag, Protocol): ... # noqa: Y046 +class _SupportsIterAndAttribAndTextAndGet( # noqa: Y046 + SupportsIter[Incomplete], _HasAttrib, _HasText, _HasGet[Incomplete], Protocol +): ... + class _ParentElement(Protocol[_T]): def makeelement(self, __tag: str, __attrib: dict[str, str]) -> _T: ... def append(self, __element: _T) -> object: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pika/pika/adapters/twisted_connection.pyi b/packages/pyright-internal/typeshed-fallback/stubs/pika/pika/adapters/twisted_connection.pyi index 11843dfc6..ab66ddd2f 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pika/pika/adapters/twisted_connection.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/pika/pika/adapters/twisted_connection.pyi @@ -21,7 +21,7 @@ class ClosableDeferredQueue(DeferredQueue[_T], Generic[_T]): # pyright: ignore[ def __init__(self, size: Incomplete | None = ..., backlog: Incomplete | None = ...) -> None: ... # Returns a Deferred with an error if fails. None if success def put(self, obj: _T) -> Deferred[Failure | BaseException] | None: ... # type: ignore[override] - def get(self) -> Deferred[Failure | BaseException | _T]: ... + def get(self) -> Deferred[Failure | BaseException | _T]: ... # type: ignore[override] pending: Incomplete def close(self, reason: BaseException | None) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pluggy/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/pluggy/METADATA.toml index 29b734085..69173ea16 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pluggy/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/pluggy/METADATA.toml @@ -1,2 +1,3 @@ version = "1.2.0" upstream_repository = "https://github.com/pytest-dev/pluggy" +obsolete_since = "1.3.0" # Released on 2023-08-26 diff --git a/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor.pyi b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor.pyi index 2b4f36e35..d8a1ad676 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor.pyi @@ -20,6 +20,7 @@ class DescriptorMetaclass(type): def __instancecheck__(self, obj: Any) -> bool: ... _internal_create_key: object +_USE_C_DESCRIPTORS: bool class DescriptorBase(metaclass=DescriptorMetaclass): has_options: Any diff --git a/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/internal/builder.pyi b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/internal/builder.pyi new file mode 100644 index 000000000..a0a72dec5 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/internal/builder.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete +from typing import Any + +def BuildMessageAndEnumDescriptors(file_des: Incomplete, module: dict[str, Any]) -> None: ... +def BuildTopDescriptorsAndMessages(file_des: Incomplete, module_name: str, module: dict[str, Any]) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/METADATA.toml index d5b778dd3..a49a94bb3 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/METADATA.toml @@ -3,4 +3,4 @@ upstream_repository = "https://github.com/psycopg/psycopg2" partial_stub = true [tool.stubtest] -ignore_missing_stub = true +ignore_missing_stub = false diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/__init__.pyi index 00267dd99..da21d947b 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/__init__.pyi @@ -27,8 +27,8 @@ from psycopg2._psycopg import ( Warning as Warning, __libpq_version__ as __libpq_version__, apilevel as apilevel, - connection as connection, - cursor as cursor, + connection, + cursor, paramstyle as paramstyle, threadsafety as threadsafety, ) @@ -36,10 +36,19 @@ from psycopg2._psycopg import ( _T_conn = TypeVar("_T_conn", bound=connection) @overload -def connect(dsn: str, connection_factory: Callable[..., _T_conn], cursor_factory: None = None, **kwargs: Any) -> _T_conn: ... +def connect( + dsn: str | None, + connection_factory: Callable[..., _T_conn], + cursor_factory: Callable[..., cursor] | None = None, + **kwargs: Any, +) -> _T_conn: ... @overload def connect( - dsn: str | None = None, *, connection_factory: Callable[..., _T_conn], cursor_factory: None = None, **kwargs: Any + dsn: str | None = None, + *, + connection_factory: Callable[..., _T_conn], + cursor_factory: Callable[..., cursor] | None = None, + **kwargs: Any, ) -> _T_conn: ... @overload def connect( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_ipaddress.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_ipaddress.pyi index 7c9cb8b0d..60085a3be 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_ipaddress.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_ipaddress.pyi @@ -1,9 +1,9 @@ -from _typeshed import Incomplete -from typing import Any +import ipaddress as ipaddress +from _typeshed import Unused -ipaddress: Any +from psycopg2._psycopg import QuotedString, connection, cursor -def register_ipaddress(conn_or_curs: Incomplete | None = None) -> None: ... -def cast_interface(s, cur: Incomplete | None = None): ... -def cast_network(s, cur: Incomplete | None = None): ... -def adapt_ipaddress(obj): ... +def register_ipaddress(conn_or_curs: connection | cursor | None = None) -> None: ... +def cast_interface(s: str, cur: Unused = None) -> ipaddress.IPv4Interface | ipaddress.IPv6Interface | None: ... +def cast_network(s: str, cur: Unused = None) -> ipaddress.IPv4Network | ipaddress.IPv6Network | None: ... +def adapt_ipaddress(obj: object) -> QuotedString: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_json.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_json.pyi index c1dd3ee3f..40ce54d4a 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_json.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_json.pyi @@ -1,5 +1,8 @@ -from _typeshed import Incomplete +from collections.abc import Callable from typing import Any +from typing_extensions import Self + +from psycopg2._psycopg import _type, connection, cursor JSON_OID: int JSONARRAY_OID: int @@ -8,19 +11,23 @@ JSONBARRAY_OID: int class Json: adapted: Any - def __init__(self, adapted, dumps: Incomplete | None = None) -> None: ... - def __conform__(self, proto): ... - def dumps(self, obj): ... - def prepare(self, conn) -> None: ... - def getquoted(self): ... + def __init__(self, adapted: Any, dumps: Callable[..., str] | None = None) -> None: ... + def __conform__(self, proto) -> Self | None: ... + def dumps(self, obj: Any) -> str: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... def register_json( - conn_or_curs: Incomplete | None = None, + conn_or_curs: connection | cursor | None = None, globally: bool = False, - loads: Incomplete | None = None, - oid: Incomplete | None = None, - array_oid: Incomplete | None = None, + loads: Callable[..., Any] | None = None, + oid: int | None = None, + array_oid: int | None = None, name: str = "json", -): ... -def register_default_json(conn_or_curs: Incomplete | None = None, globally: bool = False, loads: Incomplete | None = None): ... -def register_default_jsonb(conn_or_curs: Incomplete | None = None, globally: bool = False, loads: Incomplete | None = None): ... +) -> tuple[_type, _type | None]: ... +def register_default_json( + conn_or_curs: connection | cursor | None = None, globally: bool = False, loads: Callable[..., Any] | None = None +) -> tuple[_type, _type | None]: ... +def register_default_jsonb( + conn_or_curs: connection | cursor | None = None, globally: bool = False, loads: Callable[..., Any] | None = None +) -> tuple[_type, _type | None]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_psycopg.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_psycopg.pyi index a6362acbd..1902f3fbb 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_psycopg.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_psycopg.pyi @@ -1,109 +1,148 @@ +import datetime as dt +from _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsReadline, SupportsTrunc, SupportsWrite, Unused from collections.abc import Callable, Iterable, Mapping, Sequence from types import TracebackType -from typing import Any, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, NoReturn, Protocol, SupportsInt, TypeVar, overload, type_check_only +from typing_extensions import Literal, Self, SupportsIndex, TypeAlias -import psycopg2 -import psycopg2.extensions from psycopg2.sql import Composable _Vars: TypeAlias = Sequence[Any] | Mapping[str, Any] | None +_AcceptedByInt: TypeAlias = str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc + +@type_check_only +class _type: + # The class doesn't exist at runtime but following attributes have type "psycopg2._psycopg.type" + name: str + values: tuple[int, ...] + def __call__(self, __value: str | bytes | None, __cur: cursor | None) -> Any: ... + +BINARY: _type +BINARYARRAY: _type +BOOLEAN: _type +BOOLEANARRAY: _type +BYTES: _type +BYTESARRAY: _type +CIDRARRAY: _type +DATE: _type +DATEARRAY: _type +DATETIME: _type +DATETIMEARRAY: _type +DATETIMETZ: _type +DATETIMETZARRAY: _type +DECIMAL: _type +DECIMALARRAY: _type +FLOAT: _type +FLOATARRAY: _type +INETARRAY: _type +INTEGER: _type +INTEGERARRAY: _type +INTERVAL: _type +INTERVALARRAY: _type +LONGINTEGER: _type +LONGINTEGERARRAY: _type +MACADDRARRAY: _type +NUMBER: _type +PYDATE: _type +PYDATEARRAY: _type +PYDATETIME: _type +PYDATETIMEARRAY: _type +PYDATETIMETZ: _type +PYDATETIMETZARRAY: _type +PYINTERVAL: _type +PYINTERVALARRAY: _type +PYTIME: _type +PYTIMEARRAY: _type +ROWID: _type +ROWIDARRAY: _type +STRING: _type +STRINGARRAY: _type +TIME: _type +TIMEARRAY: _type +UNICODE: _type +UNICODEARRAY: _type +UNKNOWN: _type -BINARY: Any -BINARYARRAY: Any -BOOLEAN: Any -BOOLEANARRAY: Any -BYTES: Any -BYTESARRAY: Any -CIDRARRAY: Any -DATE: Any -DATEARRAY: Any -DATETIME: Any -DATETIMEARRAY: Any -DATETIMETZ: Any -DATETIMETZARRAY: Any -DECIMAL: Any -DECIMALARRAY: Any -FLOAT: Any -FLOATARRAY: Any -INETARRAY: Any -INTEGER: Any -INTEGERARRAY: Any -INTERVAL: Any -INTERVALARRAY: Any -LONGINTEGER: Any -LONGINTEGERARRAY: Any -MACADDRARRAY: Any -NUMBER: Any -PYDATE: Any -PYDATEARRAY: Any -PYDATETIME: Any -PYDATETIMEARRAY: Any -PYDATETIMETZ: Any -PYDATETIMETZARRAY: Any -PYINTERVAL: Any -PYINTERVALARRAY: Any -PYTIME: Any -PYTIMEARRAY: Any REPLICATION_LOGICAL: int REPLICATION_PHYSICAL: int -ROWID: Any -ROWIDARRAY: Any -STRING: Any -STRINGARRAY: Any -TIME: Any -TIMEARRAY: Any -UNICODE: Any -UNICODEARRAY: Any -UNKNOWN: Any -adapters: dict[Any, Any] + +class _ISQLQuoteProto(Protocol): + # Objects conforming this protocol should implement a getquoted() and optionally a prepare() method. + # The real ISQLQuote class is implemented below with more stuff. + def getquoted(self) -> bytes: ... + # def prepare(self, __conn: connection) -> None: ... # optional + +adapters: dict[tuple[type[Any], type[ISQLQuote]], Callable[[Any], _ISQLQuoteProto]] apilevel: str binary_types: dict[Any, Any] -encodings: dict[Any, Any] +encodings: dict[str, str] paramstyle: str -sqlstate_errors: dict[Any, Any] -string_types: dict[Any, Any] +sqlstate_errors: dict[str, type[Error]] +string_types: dict[int, _type] threadsafety: int __libpq_version__: int +class _SupportsReadAndReadline(SupportsRead[str], SupportsReadline[str]): ... +class _SupportsReadAndReadlineAndWrite(_SupportsReadAndReadline, SupportsWrite[str]): ... + class cursor: arraysize: int - binary_types: Any - closed: Any - connection: Any - description: Any - itersize: Any - lastrowid: Any - name: Any - pgresult_ptr: Any - query: Any - row_factory: Any - rowcount: int - rownumber: int + binary_types: Incomplete | None + connection: _Connection + itersize: int + row_factory: Incomplete | None scrollable: bool | None - statusmessage: Any - string_types: Any - typecaster: Any - tzinfo_factory: Any + string_types: Incomplete | None + tzinfo_factory: Callable[..., dt.tzinfo] withhold: bool - def __init__(self, conn: connection, name: str | bytes | None = ...) -> None: ... - def callproc(self, procname, parameters=...): ... - def cast(self, oid, s): ... - def close(self): ... - def copy_expert(self, sql: str | bytes | Composable, file, size=...): ... - def copy_from(self, file, table, sep=..., null=..., size=..., columns=...): ... - def copy_to(self, file, table, sep=..., null=..., columns=...): ... - def execute(self, query: str | bytes | Composable, vars: _Vars = ...) -> None: ... + def __init__(self, conn: _Connection, name: str | bytes | None = None) -> None: ... + @property + def closed(self) -> bool: ... + @property + def lastrowid(self) -> int: ... + @property + def name(self) -> Incomplete | None: ... + @property + def query(self) -> bytes | None: ... + @property + def description(self) -> tuple[Column, ...] | None: ... + @property + def rowcount(self) -> int: ... + @property + def rownumber(self) -> int: ... + @property + def typecaster(self) -> Incomplete | None: ... + @property + def statusmessage(self) -> str | None: ... + @property + def pgresult_ptr(self) -> int | None: ... + def callproc(self, __procname: str | bytes, __parameters: _Vars = None) -> None: ... + def cast(self, __oid: int, __s: str | bytes) -> Any: ... + def close(self) -> None: ... + def copy_expert(self, sql: str | bytes | Composable, file: _SupportsReadAndReadlineAndWrite, size: int = 8192) -> None: ... + def copy_from( + self, + file: _SupportsReadAndReadline, + table: str, + sep: str = "\t", + null: str = "\\N", + size: int = 8192, + columns: Iterable[str] | None = None, + ) -> None: ... + def copy_to( + self, file: SupportsWrite[str], table: str, sep: str = "\t", null: str = "\\N", columns: Iterable[str] | None = None + ) -> None: ... + def execute(self, query: str | bytes | Composable, vars: _Vars = None) -> None: ... def executemany(self, query: str | bytes | Composable, vars_list: Iterable[_Vars]) -> None: ... def fetchall(self) -> list[tuple[Any, ...]]: ... - def fetchmany(self, size: int | None = ...) -> list[tuple[Any, ...]]: ... + def fetchmany(self, size: int | None = None) -> list[tuple[Any, ...]]: ... def fetchone(self) -> tuple[Any, ...] | None: ... - def mogrify(self, *args, **kwargs): ... - def nextset(self): ... - def scroll(self, value, mode=...): ... - def setinputsizes(self, sizes): ... - def setoutputsize(self, size, column=...): ... + def mogrify(self, query: str | bytes, vars: _Vars | None = None) -> bytes: ... + def nextset(self) -> NoReturn: ... # not supported + def scroll(self, value: int, mode: Literal["absolute", "relative"] = "relative") -> None: ... + def setinputsizes(self, sizes: Unused) -> None: ... + def setoutputsize(self, __size: int, __column: int = ...) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None @@ -114,24 +153,28 @@ class cursor: _Cursor: TypeAlias = cursor class AsIs: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... + def __init__(self, __obj: object, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, __proto) -> Self | None: ... class Binary: - adapted: Any - buffer: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def prepare(self, conn): ... - def __conform__(self, *args, **kwargs): ... + def __init__(self, __str: object, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def buffer(self) -> Any: ... + def getquoted(self) -> bytes: ... + def prepare(self, __conn: connection) -> None: ... + def __conform__(self, __proto) -> Self | None: ... class Boolean: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... + def __init__(self, __obj: object, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, __proto) -> Self | None: ... class Column: display_size: Any @@ -214,14 +257,40 @@ class ConnectionInfo: def parameter_status(self, name: str) -> str | None: ... def ssl_attribute(self, name: str) -> str | None: ... -class DataError(psycopg2.DatabaseError): ... -class DatabaseError(psycopg2.Error): ... +class Error(Exception): + cursor: _Cursor | None + diag: Diagnostics + pgcode: str | None + pgerror: str | None + def __init__(self, *args, **kwargs) -> None: ... + def __reduce__(self): ... + def __setstate__(self, state): ... + +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class QueryCanceledError(OperationalError): ... +class TransactionRollbackError(OperationalError): ... +class InterfaceError(Error): ... +class Warning(Exception): ... + +class ISQLQuote: + _wrapped: Any + def __init__(self, __wrapped: object, **kwargs) -> None: ... + def getbinary(self) -> Incomplete: ... + def getbuffer(self) -> Incomplete: ... + def getquoted(self) -> bytes: ... class Decimal: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... + def __init__(self, __value: object, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, __proto) -> Self | None: ... class Diagnostics: column_name: str | None @@ -244,46 +313,27 @@ class Diagnostics: table_name: str | None def __init__(self, __err: Error) -> None: ... -class Error(Exception): - cursor: _Cursor | None - diag: Diagnostics - pgcode: str | None - pgerror: str | None - def __init__(self, *args, **kwargs) -> None: ... - def __reduce__(self): ... - def __setstate__(self, state): ... - class Float: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... - -class ISQLQuote: - _wrapped: Any - def __init__(self, *args, **kwargs) -> None: ... - def getbinary(self, *args, **kwargs): ... - def getbuffer(self, *args, **kwargs): ... - def getquoted(self, *args, **kwargs): ... + def __init__(self, __value: float, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> float: ... + def getquoted(self) -> bytes: ... + def __conform__(self, __proto) -> Self | None: ... class Int: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... - -class IntegrityError(psycopg2.DatabaseError): ... -class InterfaceError(psycopg2.Error): ... -class InternalError(psycopg2.DatabaseError): ... + def __init__(self, __value: _AcceptedByInt, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, __proto) -> Self | None: ... class List: - adapted: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def prepare(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... - -class NotSupportedError(psycopg2.DatabaseError): ... + def __init__(self, __objs: list[object], **kwargs: Unused) -> None: ... + @property + def adapted(self) -> list[Any]: ... + def getquoted(self) -> bytes: ... + def prepare(self, __conn: connection) -> None: ... + def __conform__(self, __proto) -> Self | None: ... class Notify: channel: Any @@ -300,27 +350,16 @@ class Notify: def __lt__(self, __other): ... def __ne__(self, __other): ... -class OperationalError(psycopg2.DatabaseError): ... -class ProgrammingError(psycopg2.DatabaseError): ... -class QueryCanceledError(psycopg2.OperationalError): ... - class QuotedString: - adapted: Any - buffer: Any - encoding: Any - def __init__(self, *args, **kwargs) -> None: ... - def getquoted(self, *args, **kwargs): ... - def prepare(self, *args, **kwargs): ... - def __conform__(self, *args, **kwargs): ... - -class ReplicationConnection(psycopg2.extensions.connection): - autocommit: Any - isolation_level: Any - replication_type: Any - reset: Any - set_isolation_level: Any - set_session: Any - def __init__(self, *args, **kwargs) -> None: ... + encoding: str + def __init__(self, __str: object, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def buffer(self) -> Any: ... + def getquoted(self) -> bytes: ... + def prepare(self, __conn: connection) -> None: ... + def __conform__(self, __proto) -> Self | None: ... class ReplicationCursor(cursor): feedback_timestamp: Any @@ -341,9 +380,6 @@ class ReplicationMessage: wal_end: Any def __init__(self, *args, **kwargs) -> None: ... -class TransactionRollbackError(psycopg2.OperationalError): ... -class Warning(Exception): ... - class Xid: bqual: Any database: Any @@ -359,21 +395,21 @@ class Xid: _T_cur = TypeVar("_T_cur", bound=cursor) class connection: - DataError: Any - DatabaseError: Any - Error: Any - IntegrityError: Any - InterfaceError: Any - InternalError: Any - NotSupportedError: Any - OperationalError: Any - ProgrammingError: Any - Warning: Any + DataError: type[DataError] + DatabaseError: type[DatabaseError] + Error: type[Error] + IntegrityError: type[IntegrityError] + InterfaceError: type[InterfaceError] + InternalError: type[InternalError] + NotSupportedError: type[NotSupportedError] + OperationalError: type[OperationalError] + ProgrammingError: type[ProgrammingError] + Warning: type[Warning] @property def async_(self) -> int: ... autocommit: bool @property - def binary_types(self) -> Any: ... + def binary_types(self) -> dict[Incomplete, Incomplete]: ... @property def closed(self) -> int: ... cursor_factory: Callable[..., _Cursor] @@ -387,8 +423,8 @@ class connection: def isolation_level(self) -> int | None: ... @isolation_level.setter def isolation_level(self, __value: str | bytes | int | None) -> None: ... - notices: list[Any] - notifies: list[Any] + notices: list[str] + notifies: list[Notify] @property def pgconn_ptr(self) -> int | None: ... @property @@ -406,27 +442,33 @@ class connection: @property def status(self) -> int: ... @property - def string_types(self) -> Any: ... - # Really it's dsn: str, async: int = ..., async_: int = ..., but + def string_types(self) -> dict[Incomplete, Incomplete]: ... + # Really it's dsn: str, async: int = 0, async_: int = 0, but # that would be a syntax error. - def __init__(self, dsn: str, *, async_: int = ...) -> None: ... + def __init__(self, dsn: str, *, async_: int = 0) -> None: ... def cancel(self) -> None: ... def close(self) -> None: ... def commit(self) -> None: ... @overload - def cursor(self, name: str | bytes | None = ..., *, withhold: bool = ..., scrollable: bool | None = ...) -> _Cursor: ... + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> _Cursor: ... @overload def cursor( self, - name: str | bytes | None = ..., + name: str | bytes | None = None, *, cursor_factory: Callable[..., _T_cur], - withhold: bool = ..., - scrollable: bool | None = ..., + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... @overload def cursor( - self, name: str | bytes | None, cursor_factory: Callable[..., _T_cur], withhold: bool = ..., scrollable: bool | None = ... + self, + name: str | bytes | None, + cursor_factory: Callable[..., _T_cur], + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... def fileno(self) -> int: ... def get_backend_pid(self) -> int: ... @@ -464,6 +506,17 @@ class connection: def __enter__(self) -> Self: ... def __exit__(self, __type: type[BaseException] | None, __name: BaseException | None, __tb: TracebackType | None) -> None: ... +_Connection: TypeAlias = connection + +class ReplicationConnection(connection): + autocommit: Any + isolation_level: Any + replication_type: Any + reset: Any + set_isolation_level: Any + set_session: Any + def __init__(self, *args, **kwargs) -> None: ... + class lobject: closed: Any mode: Any @@ -478,24 +531,52 @@ class lobject: def unlink(self): ... def write(self, str): ... -def Date(year, month, day): ... -def DateFromPy(*args, **kwargs): ... -def DateFromTicks(ticks): ... -def IntervalFromPy(*args, **kwargs): ... -def Time(hour, minutes, seconds, tzinfo=...): ... -def TimeFromPy(*args, **kwargs): ... -def TimeFromTicks(ticks): ... -def Timestamp(year, month, day, hour, minutes, seconds, tzinfo=...): ... -def TimestampFromPy(*args, **kwargs): ... -def TimestampFromTicks(ticks): ... +@type_check_only +class _datetime: + # The class doesn't exist at runtime but functions below return "psycopg2._psycopg.datetime" objects + # XXX: This and other classes that implement the `ISQLQuote` protocol could be made generic + # in the return type of their `adapted` property if someone asks for it. + def __init__(self, __obj: object, __type: int = -1, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def type(self) -> int: ... + def getquoted(self) -> bytes: ... + def __conform__(self, __proto) -> Self | None: ... + +def Date(__year: int, __month: int, __day: int) -> _datetime: ... +def DateFromPy(__date: dt.date) -> _datetime: ... +def DateFromTicks(__ticks: float) -> _datetime: ... +def IntervalFromPy(__interval: dt.timedelta) -> _datetime: ... +def Time(__hour: int, __minutes: int, __seconds: float, __tzinfo: dt.tzinfo | None = None) -> _datetime: ... +def TimeFromPy(__time: dt.time) -> _datetime: ... +def TimeFromTicks(__ticks: float) -> _datetime: ... +def Timestamp( + __year: int, + __month: int, + __day: int, + __hour: int = 0, + __minutes: int = 0, + __seconds: float = 0, + __tzinfo: dt.tzinfo | None = None, +) -> _datetime: ... +def TimestampFromPy(__datetime: dt.datetime) -> _datetime: ... +def TimestampFromTicks(__ticks: float) -> _datetime: ... def _connect(*args, **kwargs): ... -def adapt(*args, **kwargs): ... -def encrypt_password(*args, **kwargs): ... -def get_wait_callback(*args, **kwargs): ... -def libpq_version(*args, **kwargs): ... -def new_array_type(oids, name, baseobj): ... -def new_type(oids, name, castobj): ... +def adapt(__obj: object, __protocol: Incomplete = ..., __alternate: Incomplete = ...) -> Any: ... +def encrypt_password( + password: str | bytes, user: str | bytes, scope: connection | cursor | None = None, algorithm: str | None = None +) -> str: ... +def get_wait_callback() -> Incomplete | None: ... +def libpq_version() -> int: ... +def new_array_type(values: tuple[int, ...], name: str, baseobj: _type) -> _type: ... +def new_type( + values: tuple[int, ...], + name: str, + castobj: Callable[[str | bytes | None, cursor], Any] | None = None, + baseobj: Incomplete | None = None, +) -> _type: ... def parse_dsn(dsn: str | bytes) -> dict[str, Any]: ... -def quote_ident(*args, **kwargs): ... -def register_type(*args, **kwargs): ... -def set_wait_callback(_none): ... +def quote_ident(ident: str | bytes, scope) -> str: ... +def register_type(__obj: _type, __conn_or_curs: connection | cursor | None = None) -> None: ... +def set_wait_callback(__none: Callable[..., Incomplete] | None) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_range.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_range.pyi index a3b3a118c..131196c95 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_range.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/_range.pyi @@ -1,5 +1,8 @@ from _typeshed import Incomplete -from typing import Any +from typing import Any, overload +from typing_extensions import Self + +from psycopg2._psycopg import connection, cursor class Range: def __init__( @@ -10,41 +13,50 @@ class Range: @property def upper(self): ... @property - def isempty(self): ... + def isempty(self) -> bool: ... @property - def lower_inf(self): ... + def lower_inf(self) -> bool: ... @property - def upper_inf(self): ... + def upper_inf(self) -> bool: ... @property - def lower_inc(self): ... + def lower_inc(self) -> bool: ... @property - def upper_inc(self): ... - def __contains__(self, x): ... + def upper_inc(self) -> bool: ... + def __contains__(self, x) -> bool: ... def __bool__(self) -> bool: ... - def __eq__(self, other): ... - def __ne__(self, other): ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... def __hash__(self) -> int: ... - def __lt__(self, other): ... - def __le__(self, other): ... - def __gt__(self, other): ... - def __ge__(self, other): ... + def __lt__(self, other: Range) -> bool: ... + def __le__(self, other: Range) -> bool: ... + def __gt__(self, other: Range) -> bool: ... + def __ge__(self, other: Range) -> bool: ... -def register_range(pgrange, pyrange, conn_or_curs, globally: bool = False): ... +def register_range( + pgrange: str, pyrange: str | Range, conn_or_curs: connection | cursor, globally: bool = False +) -> RangeCaster: ... class RangeAdapter: - name: Any - adapted: Any - def __init__(self, adapted) -> None: ... - def __conform__(self, proto): ... - def prepare(self, conn) -> None: ... - def getquoted(self): ... + name: str # this is None here but MUST be str in subclasses + adapted: Range + def __init__(self, adapted: Range) -> None: ... + def __conform__(self, proto) -> Self | None: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... class RangeCaster: + adapter: type[RangeAdapter] + range: type[Range] subtype_oid: Any typecaster: Any array_typecaster: Any - def __init__(self, pgrange, pyrange, oid, subtype_oid, array_oid: Incomplete | None = None) -> None: ... - def parse(self, s, cur: Incomplete | None = None): ... + def __init__( + self, pgrange: str | RangeAdapter, pyrange: str | Range, oid: int, subtype_oid: int, array_oid: int | None = None + ) -> None: ... + @overload + def parse(self, s: None, cur: cursor | None = None) -> None: ... + @overload + def parse(self, s: str, cur: cursor | None = None) -> Range: ... class NumericRange(Range): ... class DateRange(Range): ... @@ -52,11 +64,11 @@ class DateTimeRange(Range): ... class DateTimeTZRange(Range): ... class NumberRangeAdapter(RangeAdapter): - def getquoted(self): ... - -int4range_caster: Any -int8range_caster: Any -numrange_caster: Any -daterange_caster: Any -tsrange_caster: Any -tstzrange_caster: Any + def getquoted(self) -> bytes: ... + +int4range_caster: RangeCaster +int8range_caster: RangeCaster +numrange_caster: RangeCaster +daterange_caster: RangeCaster +tsrange_caster: RangeCaster +tstzrange_caster: RangeCaster diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errorcodes.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errorcodes.pyi index 66e6cef18..9ec275329 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errorcodes.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errorcodes.pyi @@ -1,4 +1,4 @@ -def lookup(code, _cache={}): ... +def lookup(code: str, _cache: dict[str, str] = {}) -> str: ... CLASS_SUCCESSFUL_COMPLETION: str CLASS_WARNING: str @@ -302,3 +302,5 @@ ASSERT_FAILURE: str INTERNAL_ERROR: str DATA_CORRUPTED: str INDEX_CORRUPTED: str +IDLE_SESSION_TIMEOUT: str +SQL_JSON_ITEM_CANNOT_BE_CAST_TO_TARGET_TYPE: str diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errors.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errors.pyi index bf7d35795..b2ced2230 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errors.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/errors.pyi @@ -1,11 +1,19 @@ -from psycopg2._psycopg import Error as Error, Warning as Warning +from psycopg2._psycopg import ( + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + QueryCanceledError as QueryCanceledError, + TransactionRollbackError as TransactionRollbackError, + Warning as Warning, +) -class DatabaseError(Error): ... -class InterfaceError(Error): ... -class DataError(DatabaseError): ... class DiagnosticsException(DatabaseError): ... -class IntegrityError(DatabaseError): ... -class InternalError(DatabaseError): ... class InvalidGrantOperation(DatabaseError): ... class InvalidGrantor(DatabaseError): ... class InvalidLocatorSpecification(DatabaseError): ... @@ -14,9 +22,6 @@ class InvalidTransactionInitiation(DatabaseError): ... class LocatorException(DatabaseError): ... class NoAdditionalDynamicResultSetsReturned(DatabaseError): ... class NoData(DatabaseError): ... -class NotSupportedError(DatabaseError): ... -class OperationalError(DatabaseError): ... -class ProgrammingError(DatabaseError): ... class SnapshotTooOld(DatabaseError): ... class SqlStatementNotYetComplete(DatabaseError): ... class StackedDiagnosticsAccessedWithoutActiveHandler(DatabaseError): ... @@ -201,7 +206,6 @@ class ProgramLimitExceeded(OperationalError): ... class ProhibitedSqlStatementAttempted(InternalError): ... class ProhibitedSqlStatementAttemptedExt(InternalError): ... class ProtocolViolation(OperationalError): ... -class QueryCanceledError(OperationalError): ... class RaiseException(InternalError): ... class ReadOnlySqlTransaction(InternalError): ... class ReadingSqlDataNotPermitted(InternalError): ... @@ -235,7 +239,6 @@ class TooManyJsonArrayElements(DataError): ... class TooManyJsonObjectMembers(DataError): ... class TooManyRows(InternalError): ... class TransactionResolutionUnknown(OperationalError): ... -class TransactionRollbackError(OperationalError): ... class TriggerProtocolViolated(InternalError): ... class TriggeredDataChangeViolation(OperationalError): ... class TrimError(DataError): ... @@ -259,5 +262,7 @@ class SerializationFailure(TransactionRollbackError): ... class StatementCompletionUnknown(TransactionRollbackError): ... class TransactionIntegrityConstraintViolation(TransactionRollbackError): ... class TransactionRollback(TransactionRollbackError): ... +class IdleSessionTimeout(OperationalError): ... +class SqlJsonItemCannotBeCastToTargetType(DataError): ... -def lookup(code): ... +def lookup(code: str) -> type[Error]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extensions.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extensions.pyi index 227212312..a964f0ed5 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extensions.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extensions.pyi @@ -1,5 +1,6 @@ -from _typeshed import Incomplete -from typing import Any +from _typeshed import Unused +from collections.abc import Callable, Iterable +from typing import Any, TypeVar, overload from psycopg2._psycopg import ( BINARYARRAY as BINARYARRAY, @@ -54,6 +55,8 @@ from psycopg2._psycopg import ( TimestampFromPy as TimestampFromPy, TransactionRollbackError as TransactionRollbackError, Xid as Xid, + _ISQLQuoteProto, + _type, adapt as adapt, adapters as adapters, binary_types as binary_types, @@ -96,20 +99,27 @@ TRANSACTION_STATUS_INTRANS: int TRANSACTION_STATUS_INERROR: int TRANSACTION_STATUS_UNKNOWN: int -def register_adapter(typ, callable) -> None: ... +_T = TypeVar("_T") + +def register_adapter(typ: type[_T], callable: Callable[[_T], _ISQLQuoteProto]) -> None: ... class SQL_IN: - def __init__(self, seq) -> None: ... - def prepare(self, conn) -> None: ... - def getquoted(self): ... + def __init__(self, seq: Iterable[object]) -> None: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... class NoneAdapter: - def __init__(self, obj) -> None: ... - def getquoted(self, _null: bytes = b"NULL"): ... + def __init__(self, obj: Unused) -> None: ... + def getquoted(self, _null: bytes = b"NULL") -> bytes: ... -def make_dsn(dsn: Incomplete | None = None, **kwargs): ... +@overload +def make_dsn(dsn: bytes) -> bytes: ... # type: ignore[misc] +@overload +def make_dsn(dsn: None = None) -> str: ... +@overload +def make_dsn(dsn: str | bytes | None = None, **kwargs: Any) -> str: ... -JSON: Any -JSONARRAY: Any -JSONB: Any -JSONBARRAY: Any +JSON: _type +JSONARRAY: _type | None +JSONB: _type +JSONBARRAY: _type | None diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extras.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extras.pyi index 5c809e51e..808e236b3 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extras.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/extras.pyi @@ -16,6 +16,9 @@ from psycopg2._psycopg import ( ReplicationConnection as _replicationConnection, ReplicationCursor as _replicationCursor, ReplicationMessage as ReplicationMessage, + connection as _connection, + cursor as _cursor, + quote_ident as quote_ident, ) from psycopg2._range import ( DateRange as DateRange, @@ -28,8 +31,6 @@ from psycopg2._range import ( register_range as register_range, ) -from .extensions import connection as _connection, cursor as _cursor, quote_ident as quote_ident - _T_cur = TypeVar("_T_cur", bound=_cursor) class DictCursorBase(_cursor): @@ -37,19 +38,25 @@ class DictCursorBase(_cursor): class DictConnection(_connection): @overload - def cursor(self, name: str | bytes | None = ..., *, withhold: bool = ..., scrollable: bool | None = ...) -> DictCursor: ... + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> DictCursor: ... @overload def cursor( self, - name: str | bytes | None = ..., + name: str | bytes | None = None, *, cursor_factory: Callable[..., _T_cur], - withhold: bool = ..., - scrollable: bool | None = ..., + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... @overload def cursor( - self, name: str | bytes | None, cursor_factory: Callable[..., _T_cur], withhold: bool = ..., scrollable: bool | None = ... + self, + name: str | bytes | None, + cursor_factory: Callable[..., _T_cur], + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... class DictCursor(DictCursorBase): @@ -77,20 +84,24 @@ class DictRow(list[Any]): class RealDictConnection(_connection): @overload def cursor( - self, name: str | bytes | None = ..., *, withhold: bool = ..., scrollable: bool | None = ... + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None ) -> RealDictCursor: ... @overload def cursor( self, - name: str | bytes | None = ..., + name: str | bytes | None = None, *, cursor_factory: Callable[..., _T_cur], - withhold: bool = ..., - scrollable: bool | None = ..., + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... @overload def cursor( - self, name: str | bytes | None, cursor_factory: Callable[..., _T_cur], withhold: bool = ..., scrollable: bool | None = ... + self, + name: str | bytes | None, + cursor_factory: Callable[..., _T_cur], + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... class RealDictCursor(DictCursorBase): @@ -110,20 +121,24 @@ class RealDictRow(OrderedDict[Any, Any]): class NamedTupleConnection(_connection): @overload def cursor( - self, name: str | bytes | None = ..., *, withhold: bool = ..., scrollable: bool | None = ... + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None ) -> NamedTupleCursor: ... @overload def cursor( self, - name: str | bytes | None = ..., + name: str | bytes | None = None, *, cursor_factory: Callable[..., _T_cur], - withhold: bool = ..., - scrollable: bool | None = ..., + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... @overload def cursor( - self, name: str | bytes | None, cursor_factory: Callable[..., _T_cur], withhold: bool = ..., scrollable: bool | None = ... + self, + name: str | bytes | None, + cursor_factory: Callable[..., _T_cur], + withhold: bool = False, + scrollable: bool | None = None, ) -> _T_cur: ... class NamedTupleCursor(_cursor): diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/pool.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/pool.pyi index d380aa19b..c12def3a5 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/pool.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/pool.pyi @@ -1,19 +1,20 @@ from _typeshed import Incomplete -from typing import Any +from collections.abc import Hashable import psycopg2 +from psycopg2._psycopg import _AcceptedByInt class PoolError(psycopg2.Error): ... class AbstractConnectionPool: - minconn: Any - maxconn: Any + minconn: int + maxconn: int closed: bool - def __init__(self, minconn, maxconn, *args, **kwargs) -> None: ... + def __init__(self, minconn: _AcceptedByInt, maxconn: _AcceptedByInt, *args, **kwargs) -> None: ... # getconn, putconn and closeall are officially documented as methods of the # abstract base class, but in reality, they only exist on the children classes - def getconn(self, key: Incomplete | None = ...): ... - def putconn(self, conn: Any, key: Incomplete | None = ..., close: bool = ...) -> None: ... + def getconn(self, key: Hashable | None = None) -> Incomplete: ... + def putconn(self, conn: Incomplete, key: Hashable | None = None, close: bool = False) -> None: ... def closeall(self) -> None: ... class SimpleConnectionPool(AbstractConnectionPool): ... @@ -21,4 +22,4 @@ class SimpleConnectionPool(AbstractConnectionPool): ... class ThreadedConnectionPool(AbstractConnectionPool): # This subclass has a default value for conn which doesn't exist # in the SimpleConnectionPool class, nor in the documentation - def putconn(self, conn: Incomplete | None = None, key: Incomplete | None = None, close: bool = False) -> None: ... + def putconn(self, conn: Incomplete | None = None, key: Hashable | None = None, close: bool = False) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/sql.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/sql.pyi index 5721e9f43..60f7d8714 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/sql.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/sql.pyi @@ -1,50 +1,49 @@ -from _typeshed import Incomplete -from collections.abc import Iterator -from typing import Any +from collections.abc import Iterable, Iterator +from typing import Any, Generic, TypeVar + +from psycopg2._psycopg import connection, cursor + +_T = TypeVar("_T") class Composable: - def __init__(self, wrapped) -> None: ... - def as_string(self, context) -> str: ... - def __add__(self, other) -> Composed: ... - def __mul__(self, n) -> Composed: ... - def __eq__(self, other) -> bool: ... - def __ne__(self, other) -> bool: ... + def __init__(self, wrapped: Any) -> None: ... + def as_string(self, context: connection | cursor) -> str: ... + def __add__(self, other: Composable) -> Composed: ... + def __mul__(self, n: int) -> Composed: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... class Composed(Composable): - def __init__(self, seq) -> None: ... + def __init__(self, seq: Iterable[Composable]) -> None: ... @property def seq(self) -> list[Composable]: ... - def as_string(self, context) -> str: ... def __iter__(self) -> Iterator[Composable]: ... - def __add__(self, other) -> Composed: ... - def join(self, joiner) -> Composed: ... + def __add__(self, other: Composable) -> Composed: ... + def join(self, joiner: str | SQL) -> Composed: ... class SQL(Composable): - def __init__(self, string) -> None: ... + def __init__(self, string: str) -> None: ... @property def string(self) -> str: ... - def as_string(self, context) -> str: ... - def format(self, *args, **kwargs) -> Composed: ... - def join(self, seq) -> Composed: ... + def format(self, *args: Composable, **kwargs: Composable) -> Composed: ... + def join(self, seq: Iterable[Composable]) -> Composed: ... class Identifier(Composable): - def __init__(self, *strings) -> None: ... + def __init__(self, *strings: str) -> None: ... @property def strings(self) -> tuple[str, ...]: ... @property def string(self) -> str: ... - def as_string(self, context) -> str: ... -class Literal(Composable): +class Literal(Composable, Generic[_T]): + def __init__(self, wrapped: _T) -> None: ... @property - def wrapped(self): ... - def as_string(self, context) -> str: ... + def wrapped(self) -> _T: ... class Placeholder(Composable): - def __init__(self, name: Incomplete | None = None) -> None: ... + def __init__(self, name: str | None = None) -> None: ... @property def name(self) -> str | None: ... - def as_string(self, context) -> str: ... -NULL: Any -DEFAULT: Any +NULL: SQL +DEFAULT: SQL diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/tz.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/tz.pyi index 5095ae74e..75d148480 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/tz.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psycopg2/psycopg2/tz.pyi @@ -1,26 +1,26 @@ import datetime -from _typeshed import Incomplete from typing import Any +from typing_extensions import Self -ZERO: Any +ZERO: datetime.timedelta class FixedOffsetTimezone(datetime.tzinfo): - def __init__(self, offset: Incomplete | None = None, name: Incomplete | None = None) -> None: ... - def __new__(cls, offset: Incomplete | None = None, name: Incomplete | None = None): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __getinitargs__(self): ... - def utcoffset(self, dt): ... - def tzname(self, dt): ... - def dst(self, dt): ... + def __init__(self, offset: datetime.timedelta | float | None = None, name: str | None = None) -> None: ... + def __new__(cls, offset: datetime.timedelta | float | None = None, name: str | None = None) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __getinitargs__(self) -> tuple[Any, ...]: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... -STDOFFSET: Any -DSTOFFSET: Any -DSTDIFF: Any +STDOFFSET: datetime.timedelta +DSTOFFSET: datetime.timedelta +DSTDIFF: datetime.timedelta class LocalTimezone(datetime.tzinfo): - def utcoffset(self, dt): ... - def dst(self, dt): ... - def tzname(self, dt): ... + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def dst(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def tzname(self, dt: datetime.datetime) -> str: ... # type: ignore[override] -LOCAL: Any +LOCAL: LocalTimezone diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/tools/list_ports_windows.pyi b/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/tools/list_ports_windows.pyi index d1b6cfdad..9b00f7102 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/tools/list_ports_windows.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/tools/list_ports_windows.pyi @@ -1,5 +1,6 @@ import ctypes import sys +from _typeshed import Incomplete from collections.abc import Generator from ctypes.wintypes import DWORD @@ -24,16 +25,16 @@ if sys.platform == "win32": REGSAM = ACCESS_MASK class GUID(ctypes.Structure): - Data1: ctypes._CField - Data2: ctypes._CField - Data3: ctypes._CField - Data4: ctypes._CField + Data1: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data2: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data3: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data4: ctypes._CField[Incomplete, Incomplete, Incomplete] class SP_DEVINFO_DATA(ctypes.Structure): - cbSize: ctypes._CField - ClassGuid: ctypes._CField - DevInst: ctypes._CField - Reserved: ctypes._CField + cbSize: ctypes._CField[Incomplete, Incomplete, Incomplete] + ClassGuid: ctypes._CField[Incomplete, Incomplete, Incomplete] + DevInst: ctypes._CField[Incomplete, Incomplete, Incomplete] + Reserved: ctypes._CField[Incomplete, Incomplete, Incomplete] PSP_DEVINFO_DATA: type[ctypes._Pointer[SP_DEVINFO_DATA]] PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p setupapi: ctypes.WinDLL diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/win32.pyi b/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/win32.pyi index fdcc3081e..d9d19b73c 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/win32.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/pyserial/serial/win32.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Incomplete from ctypes import Structure, Union, _CField, _NamedFuncPointer, _Pointer, c_int64, c_ulong, c_void_p from ctypes.wintypes import DWORD from typing_extensions import TypeAlias @@ -9,9 +10,9 @@ if sys.platform == "win32": ULONG_PTR: type[c_int64 | c_ulong] class _SECURITY_ATTRIBUTES(Structure): - nLength: _CField - lpSecurityDescriptor: _CField - bInheritHandle: _CField + nLength: _CField[Incomplete, Incomplete, Incomplete] + lpSecurityDescriptor: _CField[Incomplete, Incomplete, Incomplete] + bInheritHandle: _CField[Incomplete, Incomplete, Incomplete] LPSECURITY_ATTRIBUTES: type[_Pointer[_SECURITY_ATTRIBUTES]] CreateEvent: _NamedFuncPointer CreateFile: _NamedFuncPointer @@ -21,64 +22,64 @@ if sys.platform == "win32": CreateFileW: _NamedFuncPointer class _OVERLAPPED(Structure): - Internal: _CField - InternalHigh: _CField - Offset: _CField - OffsetHigh: _CField - Pointer: _CField - hEvent: _CField + Internal: _CField[Incomplete, Incomplete, Incomplete] + InternalHigh: _CField[Incomplete, Incomplete, Incomplete] + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + Pointer: _CField[Incomplete, Incomplete, Incomplete] + hEvent: _CField[Incomplete, Incomplete, Incomplete] OVERLAPPED: TypeAlias = _OVERLAPPED class _COMSTAT(Structure): - fCtsHold: _CField - fDsrHold: _CField - fRlsdHold: _CField - fXoffHold: _CField - fXoffSent: _CField - fEof: _CField - fTxim: _CField - fReserved: _CField - cbInQue: _CField - cbOutQue: _CField + fCtsHold: _CField[Incomplete, Incomplete, Incomplete] + fDsrHold: _CField[Incomplete, Incomplete, Incomplete] + fRlsdHold: _CField[Incomplete, Incomplete, Incomplete] + fXoffHold: _CField[Incomplete, Incomplete, Incomplete] + fXoffSent: _CField[Incomplete, Incomplete, Incomplete] + fEof: _CField[Incomplete, Incomplete, Incomplete] + fTxim: _CField[Incomplete, Incomplete, Incomplete] + fReserved: _CField[Incomplete, Incomplete, Incomplete] + cbInQue: _CField[Incomplete, Incomplete, Incomplete] + cbOutQue: _CField[Incomplete, Incomplete, Incomplete] COMSTAT: TypeAlias = _COMSTAT class _DCB(Structure): - DCBlength: _CField - BaudRate: _CField - fBinary: _CField - fParity: _CField - fOutxCtsFlow: _CField - fOutxDsrFlow: _CField - fDtrControl: _CField - fDsrSensitivity: _CField - fTXContinueOnXoff: _CField - fOutX: _CField - fInX: _CField - fErrorChar: _CField - fNull: _CField - fRtsControl: _CField - fAbortOnError: _CField - fDummy2: _CField - wReserved: _CField - XonLim: _CField - XoffLim: _CField - ByteSize: _CField - Parity: _CField - StopBits: _CField - XonChar: _CField - XoffChar: _CField - ErrorChar: _CField - EofChar: _CField - EvtChar: _CField - wReserved1: _CField + DCBlength: _CField[Incomplete, Incomplete, Incomplete] + BaudRate: _CField[Incomplete, Incomplete, Incomplete] + fBinary: _CField[Incomplete, Incomplete, Incomplete] + fParity: _CField[Incomplete, Incomplete, Incomplete] + fOutxCtsFlow: _CField[Incomplete, Incomplete, Incomplete] + fOutxDsrFlow: _CField[Incomplete, Incomplete, Incomplete] + fDtrControl: _CField[Incomplete, Incomplete, Incomplete] + fDsrSensitivity: _CField[Incomplete, Incomplete, Incomplete] + fTXContinueOnXoff: _CField[Incomplete, Incomplete, Incomplete] + fOutX: _CField[Incomplete, Incomplete, Incomplete] + fInX: _CField[Incomplete, Incomplete, Incomplete] + fErrorChar: _CField[Incomplete, Incomplete, Incomplete] + fNull: _CField[Incomplete, Incomplete, Incomplete] + fRtsControl: _CField[Incomplete, Incomplete, Incomplete] + fAbortOnError: _CField[Incomplete, Incomplete, Incomplete] + fDummy2: _CField[Incomplete, Incomplete, Incomplete] + wReserved: _CField[Incomplete, Incomplete, Incomplete] + XonLim: _CField[Incomplete, Incomplete, Incomplete] + XoffLim: _CField[Incomplete, Incomplete, Incomplete] + ByteSize: _CField[Incomplete, Incomplete, Incomplete] + Parity: _CField[Incomplete, Incomplete, Incomplete] + StopBits: _CField[Incomplete, Incomplete, Incomplete] + XonChar: _CField[Incomplete, Incomplete, Incomplete] + XoffChar: _CField[Incomplete, Incomplete, Incomplete] + ErrorChar: _CField[Incomplete, Incomplete, Incomplete] + EofChar: _CField[Incomplete, Incomplete, Incomplete] + EvtChar: _CField[Incomplete, Incomplete, Incomplete] + wReserved1: _CField[Incomplete, Incomplete, Incomplete] DCB: TypeAlias = _DCB class _COMMTIMEOUTS(Structure): - ReadIntervalTimeout: _CField - ReadTotalTimeoutMultiplier: _CField - ReadTotalTimeoutConstant: _CField - WriteTotalTimeoutMultiplier: _CField - WriteTotalTimeoutConstant: _CField + ReadIntervalTimeout: _CField[Incomplete, Incomplete, Incomplete] + ReadTotalTimeoutMultiplier: _CField[Incomplete, Incomplete, Incomplete] + ReadTotalTimeoutConstant: _CField[Incomplete, Incomplete, Incomplete] + WriteTotalTimeoutMultiplier: _CField[Incomplete, Incomplete, Incomplete] + WriteTotalTimeoutConstant: _CField[Incomplete, Incomplete, Incomplete] COMMTIMEOUTS: TypeAlias = _COMMTIMEOUTS GetLastError: _NamedFuncPointer @@ -151,11 +152,11 @@ if sys.platform == "win32": PURGE_RXCLEAR: int class N11_OVERLAPPED4DOLLAR_48E(Union): - Offset: _CField - OffsetHigh: _CField - Pointer: _CField + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + Pointer: _CField[Incomplete, Incomplete, Incomplete] class N11_OVERLAPPED4DOLLAR_484DOLLAR_49E(Structure): - Offset: _CField - OffsetHigh: _CField + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] PVOID: TypeAlias = c_void_p diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pytz/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/pytz/METADATA.toml index 334d21947..94314823c 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pytz/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/pytz/METADATA.toml @@ -1,3 +1,3 @@ -version = "2023.3" +version = "2023.3.post1" # This is a mirror of https://git.launchpad.net/pytz/tree, see https://pythonhosted.org/pytz/#latest-versions upstream_repository = "https://github.com/stub42/pytz" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/redis/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/redis/METADATA.toml index 175143019..84f3ce183 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/redis/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/redis/METADATA.toml @@ -3,7 +3,15 @@ upstream_repository = "https://github.com/redis/redis-py" # Requires a version of cryptography with a `py.typed` file requires = ["cryptography>=35.0.0", "types-pyOpenSSL"] partial_stub = true -obsolete_since = "5.0.0" # Released on 2023-08-15 +# While upstream added a py.typed file, the upstream annotations are rather +# incomplete. By using "obsolete_since" we recommend deinstalling this +# package, which isn't the best idea at the moment. +# obsolete_since = "5.0.0" # Released on 2023-08-15 +extra_description = """\ + Note: Redis-py 5.0.0 added a py.typed file, but the inline annotations \ + are incomplete. Continuing to use `types-redis` for the time being may \ + lead to superior results.\ + """ [tool.stubtest] ignore_missing_stub = true diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/METADATA.toml new file mode 100644 index 000000000..7d3601518 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.3.*" +upstream_repository = "https://github.com/requests/requests-oauthlib" +requires = ["types-oauthlib", "types-requests"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi new file mode 100644 index 000000000..0a22c06d9 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi @@ -0,0 +1,6 @@ +from .oauth1_auth import OAuth1 as OAuth1 +from .oauth1_session import OAuth1Session as OAuth1Session +from .oauth2_auth import OAuth2 as OAuth2 +from .oauth2_session import OAuth2Session as OAuth2Session, TokenUpdated as TokenUpdated + +__version__: str diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi new file mode 100644 index 000000000..77a5568fa --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi @@ -0,0 +1,8 @@ +from .ebay import ebay_compliance_fix as ebay_compliance_fix +from .facebook import facebook_compliance_fix as facebook_compliance_fix +from .fitbit import fitbit_compliance_fix as fitbit_compliance_fix +from .instagram import instagram_compliance_fix as instagram_compliance_fix +from .mailchimp import mailchimp_compliance_fix as mailchimp_compliance_fix +from .plentymarkets import plentymarkets_compliance_fix as plentymarkets_compliance_fix +from .slack import slack_compliance_fix as slack_compliance_fix +from .weibo import weibo_compliance_fix as weibo_compliance_fix diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi new file mode 100644 index 000000000..8a1384588 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def douban_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi new file mode 100644 index 000000000..58369d712 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def ebay_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi new file mode 100644 index 000000000..6544ed533 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def facebook_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi new file mode 100644 index 000000000..cd311cdc2 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi @@ -0,0 +1,3 @@ +from requests_oauthlib import OAuth2Session + +def fitbit_compliance_fix(session: OAuth2Session) -> OAuth2Session: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi new file mode 100644 index 000000000..342505444 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def instagram_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi new file mode 100644 index 000000000..f27eca445 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def mailchimp_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi new file mode 100644 index 000000000..38f27441e --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def plentymarkets_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi new file mode 100644 index 000000000..f5f67b00e --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def slack_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi new file mode 100644 index 000000000..dd8c3b23b --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def weibo_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi new file mode 100644 index 000000000..2db50b97e --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from logging import Logger + +from oauthlib.oauth1 import Client +from requests.auth import AuthBase + +CONTENT_TYPE_FORM_URLENCODED: str +CONTENT_TYPE_MULTI_PART: str +log: Logger + +class OAuth1(AuthBase): + client_class: type[Client] + client: Client + force_include_body: bool + def __init__( + self, + client_key, + client_secret: Incomplete | None = None, + resource_owner_key: Incomplete | None = None, + resource_owner_secret: Incomplete | None = None, + callback_uri: Incomplete | None = None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key: Incomplete | None = None, + verifier: Incomplete | None = None, + decoding: str = "utf-8", + client_class: type[Client] | None = None, + force_include_body: bool = False, + *, + encoding: str = "utf-8", + nonce: Incomplete | None = None, + timestamp: Incomplete | None = None, + ) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi new file mode 100644 index 000000000..e6b1324ae --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete +from logging import Logger +from typing_extensions import TypeAlias, TypedDict + +import requests +from oauthlib.oauth1 import Client + +from . import OAuth1 + +# should be dict[str, str] but could look different +_ParsedToken: TypeAlias = dict[str, Incomplete] + +class _TokenDict(TypedDict, total=False): + oauth_token: Incomplete # oauthlib.oauth1.Client.resource_owner_key + oauth_token_secret: Incomplete # oauthlib.oauth1.Client.resource_token_secret + oauth_verifier: Incomplete # oauthlib.oauth1.Client.oauth_verifier + +log: Logger + +def urldecode(body): ... + +class TokenRequestDenied(ValueError): + response: requests.Response + def __init__(self, message: str, response: requests.Response) -> None: ... + @property + def status_code(self) -> int: ... + +class TokenMissing(ValueError): + response: requests.Response + def __init__(self, message: str, response: requests.Response) -> None: ... + +class VerifierMissing(ValueError): ... + +class OAuth1Session(requests.Session): + auth: OAuth1 + def __init__( + self, + client_key, + client_secret: Incomplete | None = None, + resource_owner_key: Incomplete | None = None, + resource_owner_secret: Incomplete | None = None, + callback_uri: Incomplete | None = None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key: Incomplete | None = None, + verifier: Incomplete | None = None, + client_class: type[Client] | None = None, + force_include_body: bool = False, + *, + encoding: str = "utf-8", + nonce: Incomplete | None = None, + timestamp: Incomplete | None = None, + ) -> None: ... + @property + def token(self) -> _TokenDict: ... + @token.setter + def token(self, value: _TokenDict) -> None: ... + @property + def authorized(self) -> bool: ... + def authorization_url(self, url: str, request_token: Incomplete | None = None, **kwargs) -> str: ... + def fetch_request_token(self, url: str, realm: Incomplete | None = None, **request_kwargs) -> _ParsedToken: ... + def fetch_access_token(self, url: str, verifier: Incomplete | None = None, **request_kwargs) -> _ParsedToken: ... + def parse_authorization_response(self, url: str) -> _ParsedToken: ... + def rebuild_auth(self, prepared_request: requests.PreparedRequest, response: requests.Response) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi new file mode 100644 index 000000000..fb241519e --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from oauthlib.oauth2 import Client +from requests.auth import AuthBase + +class OAuth2(AuthBase): + def __init__( + self, client_id: Incomplete | None = None, client: Client | None = None, token: Incomplete | None = None + ) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi new file mode 100644 index 000000000..b9317cad3 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi @@ -0,0 +1,136 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Any, Protocol, overload +from typing_extensions import Literal, TypeAlias, TypedDict + +import requests +from oauthlib.oauth2 import Client +from requests.cookies import RequestsCookieJar + +_Token: TypeAlias = dict[str, Incomplete] # oauthlib.oauth2.Client.token + +class _AccessTokenResponseHook(Protocol): + def __call__(self, __response: requests.Response) -> requests.Response: ... + +class _RefreshTokenResponseHook(Protocol): + def __call__(self, __response: requests.Response) -> requests.Response: ... + +class _ProtectedRequestHook(Protocol): + def __call__( + self, __url: Incomplete, __headers: Incomplete, __data: Incomplete + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +class _ComplianceHooks(TypedDict): + access_token_response: set[_AccessTokenResponseHook] + refresh_token_response: set[_RefreshTokenResponseHook] + protected_request: set[_ProtectedRequestHook] + +log: Logger + +class TokenUpdated(Warning): + token: Incomplete + def __init__(self, token) -> None: ... + +class OAuth2Session(requests.Session): + redirect_uri: Incomplete + state: Incomplete + auto_refresh_url: str | None + auto_refresh_kwargs: dict[str, Any] + token_updater: Incomplete + compliance_hook: _ComplianceHooks + scope: Incomplete | None + def __init__( + self, + client_id: Incomplete | None = None, + client: Client | None = None, + auto_refresh_url: str | None = None, + auto_refresh_kwargs: dict[str, Any] | None = None, + scope: Incomplete | None = None, + redirect_uri: Incomplete | None = None, + token: Incomplete | None = None, + state: Incomplete | None = None, + token_updater: Incomplete | None = None, + **kwargs, + ) -> None: ... + def new_state(self): ... + @property + def client_id(self) -> Incomplete | None: ... # oauthlib.oauth2.Client.client_id + @client_id.setter + def client_id(self, value: Incomplete | None) -> None: ... + @client_id.deleter + def client_id(self) -> None: ... + @property + def token(self): ... # oauthlib.oauth2.Client.token + @token.setter + def token(self, value) -> None: ... + @property + def access_token(self): ... # oauthlib.oauth2.Client.access_token + @access_token.setter + def access_token(self, value) -> None: ... + @access_token.deleter + def access_token(self) -> None: ... + @property + def authorized(self) -> bool: ... + def authorization_url(self, url: str, state: Incomplete | None = None, **kwargs) -> str: ... + def fetch_token( + self, + token_url: str, + code: Incomplete | None = None, + authorization_response: Incomplete | None = None, + body: str = "", + auth: Incomplete | None = None, + username: Incomplete | None = None, + password: Incomplete | None = None, + method: str = "POST", + force_querystring: bool = False, + timeout: Incomplete | None = None, + headers: Incomplete | None = None, + verify: bool = True, + proxies: Incomplete | None = None, + include_client_id: Incomplete | None = None, + client_secret: Incomplete | None = None, + cert: Incomplete | None = None, + **kwargs, + ) -> _Token: ... + def token_from_fragment(self, authorization_response: str) -> _Token: ... + def refresh_token( + self, + token_url: str, + refresh_token: Incomplete | None = None, + body: str = "", + auth: Incomplete | None = None, + timeout: Incomplete | None = None, + headers: Incomplete | None = None, + verify: bool = True, + proxies: Incomplete | None = None, + **kwargs, + ) -> _Token: ... + def request( # type: ignore[override] + self, + method: str | bytes, + url: str | bytes, + data: requests.sessions._Data | None = None, + headers: requests.sessions._HeadersUpdateMapping | None = None, + withhold_token: bool = False, + client_id: Incomplete | None = None, + client_secret: Incomplete | None = None, + *, + params: requests.sessions._Params | None = None, + cookies: None | RequestsCookieJar | requests.sessions._TextMapping = None, + files: requests.sessions._Files | None = None, + auth: requests.sessions._Auth | None = None, + timeout: requests.sessions._Timeout | None = None, + allow_redirects: bool = True, + proxies: requests.sessions._TextMapping | None = None, + hooks: requests.sessions._HooksInput | None = None, + stream: bool | None = None, + verify: requests.sessions._Verify | None = None, + cert: requests.sessions._Cert | None = None, + json: Incomplete | None = None, + ) -> requests.Response: ... + @overload + def register_compliance_hook(self, hook_type: Literal["access_token_response"], hook: _AccessTokenResponseHook) -> None: ... + @overload + def register_compliance_hook(self, hook_type: Literal["refresh_token_response"], hook: _RefreshTokenResponseHook) -> None: ... + @overload + def register_compliance_hook(self, hook_type: Literal["protected_request"], hook: _ProtectedRequestHook) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml index 0d2fc57ca..d1530b871 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml @@ -1,4 +1,4 @@ -version = "68.1.*" +version = "68.2.*" upstream_repository = "https://github.com/pypa/setuptools" partial_stub = true diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/ccompiler.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/ccompiler.pyi index 96a756bb2..4182c9044 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/ccompiler.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/ccompiler.pyi @@ -1,5 +1,5 @@ from collections.abc import Callable -from typing import Any +from typing import Any, ClassVar from typing_extensions import TypeAlias _Macro: TypeAlias = tuple[str] | tuple[str, str | None] @@ -15,6 +15,15 @@ def new_compiler( def show_compilers() -> None: ... class CCompiler: + src_extensions: ClassVar[list[str] | None] + obj_extensions: ClassVar[str | None] + static_lib_extension: ClassVar[str | None] + shared_lib_extension: ClassVar[str | None] + static_lib_format: ClassVar[str | None] + shared_lib_format: ClassVar[str | None] + exe_extension: ClassVar[str | None] + language_map: ClassVar[dict[str, str]] + language_order: ClassVar[list[str]] dry_run: bool force: bool verbose: bool diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/cmd.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/cmd.pyi index 3c05f2680..7a4f6fc7b 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/cmd.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/cmd.pyi @@ -10,6 +10,7 @@ class Command: distribution: Distribution sub_commands: ClassVar[list[tuple[str, Callable[[Self], bool] | None]]] def __init__(self, dist: Distribution) -> None: ... + def ensure_finalized(self) -> None: ... @abstractmethod def initialize_options(self) -> None: ... @abstractmethod diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi index dfdfe4427..67b31e7bb 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete from ..cmd import Command +from ..extension import Extension class build_ext(Command): description: str @@ -42,5 +43,5 @@ class build_ext(Command): def get_ext_fullpath(self, ext_name: str) -> str: ... def get_ext_fullname(self, ext_name: str) -> str: ... def get_ext_filename(self, ext_name: str) -> str: ... - def get_export_symbols(self, ext): ... - def get_libraries(self, ext): ... + def get_export_symbols(self, ext: Extension) -> list[str]: ... + def get_libraries(self, ext: Extension) -> list[str]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/logging.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/logging.pyi index 6933bcbd5..4f87159e2 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/logging.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/logging.pyi @@ -1,2 +1,2 @@ def configure() -> None: ... -def set_threshold(level): ... +def set_threshold(level: int) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/singledispatch/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/singledispatch/METADATA.toml index 8cbdb9a79..4c6341083 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/singledispatch/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/singledispatch/METADATA.toml @@ -1,2 +1,2 @@ -version = "4.0.*" +version = "4.1.*" upstream_repository = "https://github.com/jaraco/singledispatch" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/asyncio.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/asyncio.pyi index 12bef569c..3f9558419 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/asyncio.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/asyncio.pyi @@ -9,7 +9,7 @@ __all__ = ["tqdm_asyncio", "tarange", "tqdm", "trange"] _T = TypeVar("_T") -class tqdm_asyncio(Generic[_T], std_tqdm[_T]): +class tqdm_asyncio(std_tqdm[_T], Generic[_T]): iterable_awaitable: bool iterable_next: Callable[[], _T | Awaitable[_T]] iterable_iterator: Iterator[_T] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/discord.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/discord.pyi index 4c7d8b15f..9ab90e8b8 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/discord.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/discord.pyi @@ -15,7 +15,7 @@ class DiscordIO(MonoWorker): _T = TypeVar("_T") -class tqdm_discord(Generic[_T], tqdm_auto[_T]): +class tqdm_discord(tqdm_auto[_T], Generic[_T]): dio: Incomplete @overload def __init__( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/slack.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/slack.pyi index 0f9eba602..97b3a3f6d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/slack.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/slack.pyi @@ -16,7 +16,7 @@ class SlackIO(MonoWorker): _T = TypeVar("_T") -class tqdm_slack(Generic[_T], tqdm_auto[_T]): +class tqdm_slack(tqdm_auto[_T], Generic[_T]): sio: Incomplete @overload def __init__( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/telegram.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/telegram.pyi index cd2beb738..eb0fc7a4a 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/telegram.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/contrib/telegram.pyi @@ -21,7 +21,7 @@ class TelegramIO(MonoWorker): _T = TypeVar("_T") -class tqdm_telegram(Generic[_T], tqdm_auto[_T]): +class tqdm_telegram(tqdm_auto[_T], Generic[_T]): tgio: Incomplete @overload def __init__( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/gui.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/gui.pyi index c0db2c03a..a8a1844ef 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/gui.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/gui.pyi @@ -8,7 +8,7 @@ __all__ = ["tqdm_gui", "tgrange", "tqdm", "trange"] _T = TypeVar("_T") -class tqdm_gui(Generic[_T], std_tqdm[_T]): +class tqdm_gui(std_tqdm[_T], Generic[_T]): mpl: Incomplete plt: Incomplete toolbar: Incomplete diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/notebook.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/notebook.pyi index d2a118fb7..52f8d9c86 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/notebook.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/notebook.pyi @@ -8,7 +8,7 @@ __all__ = ["tqdm_notebook", "tnrange", "tqdm", "trange"] _T = TypeVar("_T") -class tqdm_notebook(Generic[_T], std_tqdm[_T]): +class tqdm_notebook(std_tqdm[_T], Generic[_T]): @staticmethod def status_printer( _: SupportsWrite[str] | None, total: float | None = None, desc: str | None = None, ncols: int | None = None diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/rich.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/rich.pyi index fad4f54d5..993d6b7ef 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/rich.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/rich.pyi @@ -33,7 +33,7 @@ class RateColumn(_ProgressColumn): _T = TypeVar("_T") -class tqdm_rich(Generic[_T], std_tqdm[_T]): +class tqdm_rich(std_tqdm[_T], Generic[_T]): def close(self) -> None: ... def clear(self, *_, **__) -> None: ... def display(self, *_, **__) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/std.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/std.pyi index 409f3747d..534e4afcd 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/std.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/std.pyi @@ -31,7 +31,7 @@ class TqdmMonitorWarning(TqdmWarning, RuntimeWarning): ... _T = TypeVar("_T") -class tqdm(Generic[_T], Iterable[_T], Comparable): +class tqdm(Iterable[_T], Comparable, Generic[_T]): monitor_interval: ClassVar[int] monitor: ClassVar[TMonitor | None] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/tk.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/tk.pyi index 6d925e5d6..49aebbf0a 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/tk.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/tqdm/tqdm/tk.pyi @@ -8,7 +8,7 @@ __all__ = ["tqdm_tk", "ttkrange", "tqdm", "trange"] _T = TypeVar("_T") -class tqdm_tk(Generic[_T], std_tqdm[_T]): +class tqdm_tk(std_tqdm[_T], Generic[_T]): @overload def __init__( self, diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/METADATA.toml index 85770bf0f..350844ff0 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/METADATA.toml @@ -1,2 +1,2 @@ -version = "0.20.*" +version = "0.20.1" upstream_repository = "https://github.com/tree-sitter/py-tree-sitter" diff --git a/packages/pyright/package-lock.json b/packages/pyright/package-lock.json index 83c6b483a..0b1543c1e 100644 --- a/packages/pyright/package-lock.json +++ b/packages/pyright/package-lock.json @@ -1,12 +1,12 @@ { "name": "@replit/pyright-extended", - "version": "2.0.5", + "version": "2.0.6", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@replit/pyright-extended", - "version": "2.0.5", + "version": "2.0.6", "license": "MIT", "bin": { "pyright": "index.js", diff --git a/packages/pyright/package.json b/packages/pyright/package.json index f373389de..d6b8e2ef0 100644 --- a/packages/pyright/package.json +++ b/packages/pyright/package.json @@ -2,7 +2,7 @@ "name": "@replit/pyright-extended", "displayName": "pyright-extended", "description": "Extending pyright with yapf + ruff", - "version": "2.0.5", + "version": "2.0.6", "license": "MIT", "author": { "name": "Replit" diff --git a/packages/vscode-pyright/package-lock.json b/packages/vscode-pyright/package-lock.json index d726b3c3b..21a74bb9a 100644 --- a/packages/vscode-pyright/package-lock.json +++ b/packages/vscode-pyright/package-lock.json @@ -1,12 +1,12 @@ { "name": "vscode-pyright", - "version": "1.1.325", + "version": "1.1.328", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "vscode-pyright", - "version": "1.1.325", + "version": "1.1.328", "license": "MIT", "dependencies": { "vscode-jsonrpc": "8.1.0", diff --git a/packages/vscode-pyright/package.json b/packages/vscode-pyright/package.json index be2d8e98d..c177f95a7 100644 --- a/packages/vscode-pyright/package.json +++ b/packages/vscode-pyright/package.json @@ -2,7 +2,7 @@ "name": "vscode-pyright", "displayName": "Pyright", "description": "VS Code static type checking for Python", - "version": "1.1.325", + "version": "1.1.328", "private": true, "license": "MIT", "author": {