Skip to content

Commit

Permalink
Fix panic when filling up types vector during unpacking (#14006)
Browse files Browse the repository at this point in the history
## Summary

This PR fixes a panic which can occur in an unpack assignment when:
* (number of target expressions) - (number of tuple types) > 2
* There's a starred expression

The reason being that the `insert` panics because the index is greater
than the length.

This is an error case and so practically it should occur very rarely.
The solution is to resize the types vector to match the number of
expressions and then insert the starred expression type.

## Test Plan

Add a new test case.
  • Loading branch information
dhruvmanila authored Oct 30, 2024
1 parent bf20061 commit 2629527
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
13 changes: 13 additions & 0 deletions crates/red_knot_python_semantic/resources/mdtest/unpacking.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,19 @@ reveal_type(b) # revealed: Literal[2]
reveal_type(c) # revealed: @Todo
```

### Starred expression (6)

```py
# TODO: Add diagnostic (need more values to unpack)
(a, b, c, *d, e, f) = (1,)
reveal_type(a) # revealed: Literal[1]
reveal_type(b) # revealed: Unknown
reveal_type(c) # revealed: Unknown
reveal_type(d) # revealed: @Todo
reveal_type(e) # revealed: Unknown
reveal_type(f) # revealed: Unknown
```

### Non-iterable unpacking

TODO: Remove duplicate diagnostics. This is happening because for a sequence-like
Expand Down
4 changes: 4 additions & 0 deletions crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1257,6 +1257,10 @@ impl<'db> TypeInferenceBuilder<'db> {
Cow::Owned(element_types)
} else {
let mut element_types = tuple_ty.elements(builder.db).to_vec();
// Subtract 1 to insert the starred expression type at the correct
// index.
element_types.resize(elts.len() - 1, Type::Unknown);
// TODO: This should be `list[Unknown]`
element_types.insert(starred_index, Type::Todo);
Cow::Owned(element_types)
}
Expand Down

0 comments on commit 2629527

Please sign in to comment.