Skip to content

Commit

Permalink
Added missing check for out-of-bound index accesses for named tuple i…
Browse files Browse the repository at this point in the history
…nstances. This addresses #7196. (#7207)
  • Loading branch information
erictraut authored Feb 4, 2024
1 parent e2fab53 commit 626f655
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
11 changes: 7 additions & 4 deletions packages/pyright-internal/src/analyzer/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ import {
getDeclaredGeneratorReturnType,
getGeneratorTypeArgs,
getProtocolSymbolsRecursive,
getSpecializedTupleType,
getTypeVarArgumentsRecursive,
getTypeVarScopeId,
isLiteralType,
Expand Down Expand Up @@ -1242,13 +1243,15 @@ export class Checker extends ParseTreeWalker {
const baseType = this._evaluator.getType(node.baseExpression);
if (baseType) {
doForEachSubtype(baseType, (subtype) => {
const tupleType = getSpecializedTupleType(subtype);

if (
isClassInstance(subtype) &&
subtype.tupleTypeArguments &&
!isUnboundedTupleClass(subtype) &&
!this._evaluator.isTypeSubsumedByOtherType(subtype, baseType, /* allowAnyToSubsume */ false)
tupleType?.tupleTypeArguments &&
!isUnboundedTupleClass(tupleType) &&
!this._evaluator.isTypeSubsumedByOtherType(tupleType, baseType, /* allowAnyToSubsume */ false)
) {
const tupleLength = subtype.tupleTypeArguments.length;
const tupleLength = tupleType.tupleTypeArguments.length;

if (
node.items.length === 1 &&
Expand Down
3 changes: 2 additions & 1 deletion packages/pyright-internal/src/tests/samples/tuple1.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,10 @@ def func13(

v10 = d[0]

# This should generate an error.
v11 = d[1]

# This should generate an error.
# This should generate two errors.
v12 = d[2]

v13: tuple[()] = ()
Expand Down
2 changes: 1 addition & 1 deletion packages/pyright-internal/src/tests/typeEvaluator1.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1270,7 +1270,7 @@ test('Optional2', () => {
test('Tuple1', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['tuple1.py']);

TestUtils.validateResults(analysisResults, 22);
TestUtils.validateResults(analysisResults, 24);
});

test('Tuple2', () => {
Expand Down

0 comments on commit 626f655

Please sign in to comment.