Skip to content

Commit 95888b2

Browse files
authored
[ty] Preserve narrowing after guarded match subject captures (#29558)
When a match case captures the subject under its own name and its guard fails, later cases now narrow that capture. Previously, those cases could retain a wider type because narrowing targeted only the binding read before the match. Retain bindings that capture the entire subject under its original name, including `as` patterns and OR alternatives. Captures of extracted values and assignments made by guards remain distinct from the saved subject. Fixes astral-sh/ty#4761.
1 parent 3c8166b commit 95888b2

2 files changed

Lines changed: 144 additions & 0 deletions

File tree

‎crates/ty_python_core/src/builder.rs‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2887,6 +2887,42 @@ impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
28872887
(predicate, predicate_id)
28882888
}
28892889

2890+
/// Retain captures that bind the entire subject to its original name. These definitions
2891+
/// still refer to the saved subject if a guard fails, so later cases can narrow them.
2892+
fn extend_match_subject_bindings(
2893+
&self,
2894+
pattern: &ast::Pattern,
2895+
symbol: ScopedSymbolId,
2896+
bindings: &mut SmallVec<[ScopedDefinitionId; 2]>,
2897+
) {
2898+
match pattern {
2899+
ast::Pattern::MatchAs(pattern) => {
2900+
if let Some(name) = &pattern.name
2901+
&& let Some(definition) = self
2902+
.definitions_by_node
2903+
.get(&name.into())
2904+
.and_then(|definitions| definitions.first())
2905+
{
2906+
let use_def = self.current_use_def_map();
2907+
bindings.extend(use_def.symbol_binding_definition_ids(symbol).filter(
2908+
|binding| use_def.definition(*binding).definition() == Some(*definition),
2909+
));
2910+
}
2911+
if let Some(pattern) = &pattern.pattern {
2912+
self.extend_match_subject_bindings(pattern, symbol, bindings);
2913+
}
2914+
}
2915+
ast::Pattern::MatchOr(pattern) => {
2916+
for pattern in &pattern.patterns {
2917+
self.extend_match_subject_bindings(pattern, symbol, bindings);
2918+
}
2919+
}
2920+
// Structural patterns can capture extracted values. Identifying whole-subject
2921+
// captures in class patterns requires type information.
2922+
_ => {}
2923+
}
2924+
}
2925+
28902926
/// Record an expression that needs to be a Salsa ingredient, because we need to infer its type
28912927
/// standalone (type narrowing tests, RHS of an assignment.)
28922928
fn add_standalone_expression(&mut self, expression_node: &ast::Expr) -> Expression<'db> {
@@ -4922,6 +4958,8 @@ impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
49224958
};
49234959
subject_targets.push((place, bindings));
49244960
}
4961+
let subject_place = PlaceExpr::try_from_expr(subject.as_ref())
4962+
.and_then(|place| self.current_place_table().place_id((&place).into()));
49254963
let places = self.current_place_table();
49264964
let ast_ids = self.current_ast_ids();
49274965
let mut sequence_subject_targets =
@@ -4974,6 +5012,12 @@ impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
49745012
self.record_exception_checkpoint_if(Self::pattern_can_raise(&case.pattern));
49755013
self.visit_pattern(&case.pattern);
49765014
self.current_match_case = None;
5015+
if let Some((ScopedPlaceId::Symbol(symbol), bindings)) = subject_targets
5016+
.iter_mut()
5017+
.find(|(place, _)| Some(*place) == subject_place)
5018+
{
5019+
self.extend_match_subject_bindings(&case.pattern, *symbol, bindings);
5020+
}
49775021
// unlike in [Stmt::If], we don't reset [no_case_matched]
49785022
// here because the effects of visiting a pattern is binding
49795023
// symbols, and this doesn't occur unless the pattern

‎crates/ty_python_semantic/resources/mdtest/narrow/match.md‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3545,6 +3545,95 @@ def match_tuple_expression_guard_rebinding(
35453545
reveal_type(b) # revealed: TupleSubjectB1
35463546
```
35473547

3548+
## Captures of the subject across cases
3549+
3550+
### Narrowing guards
3551+
3552+
Capturing the subject under its original name keeps its value. If the guard fails, later patterns
3553+
can still narrow that capture.
3554+
3555+
```py
3556+
def narrow_after_capture(value: int | str | bytes) -> None:
3557+
match value:
3558+
case value if isinstance(value, int):
3559+
reveal_type(value) # revealed: int
3560+
case str():
3561+
reveal_type(value) # revealed: str
3562+
case bytes():
3563+
reveal_type(value) # revealed: bytes
3564+
```
3565+
3566+
### Constrained `as` patterns
3567+
3568+
If the first pattern matches but its guard fails, the captured integer cannot reach the string case.
3569+
3570+
```py
3571+
def narrow_after_as_capture(value: int | str, flag: bool) -> None:
3572+
match value:
3573+
case int() as value if flag:
3574+
pass
3575+
case str():
3576+
reveal_type(value) # revealed: str
3577+
```
3578+
3579+
### Or pattern alternatives
3580+
3581+
Each alternative can capture the whole subject under its original name.
3582+
3583+
```py
3584+
def narrow_after_or_capture(value: int | str | bytes, flag: bool) -> None:
3585+
match value:
3586+
case (int() as value) | (str() as value) if flag:
3587+
pass
3588+
case str():
3589+
reveal_type(value) # revealed: str
3590+
```
3591+
3592+
A capture can also refer to the whole subject in one alternative and an extracted element in
3593+
another. Matching the original tuple in a later case does not make its captured integer unreachable.
3594+
3595+
```py
3596+
def mixed_or_captures(subject: int | tuple[int], flag: bool) -> None:
3597+
value = subject
3598+
match value:
3599+
case (int() as value) | [value] if flag:
3600+
pass
3601+
case tuple():
3602+
reveal_type(value) # revealed: int
3603+
```
3604+
3605+
### Reassignment in guards
3606+
3607+
A guard can assign a different value to the captured name. Later cases still match the saved
3608+
subject, so their patterns do not narrow that assignment.
3609+
3610+
```py
3611+
def reassign_capture(value: int | str, flag: bool) -> None:
3612+
match value:
3613+
case value if (value := "changed") and flag:
3614+
pass
3615+
case int():
3616+
reveal_type(value) # revealed: Literal["changed"]
3617+
```
3618+
3619+
### Member subjects
3620+
3621+
Capturing an attribute under the name of its owner replaces the owner with the attribute value.
3622+
Narrowing the saved attribute does not narrow this new binding of the owner's name.
3623+
3624+
```py
3625+
class Holder:
3626+
attr: int | str
3627+
3628+
def capture_member(holder: Holder) -> None:
3629+
value = holder
3630+
match value.attr:
3631+
case value if False:
3632+
pass
3633+
case int():
3634+
reveal_type(value) # revealed: int | str
3635+
```
3636+
35483637
## Named-expression subjects
35493638

35503639
A named expression creates a new binding for the subject. The successful pattern narrows that
@@ -3569,6 +3658,17 @@ def match_named_expression_subject_capture(value: tuple[int]) -> None:
35693658
reveal_type(subject) # revealed: int
35703659
```
35713660

3661+
Capturing the entire subject under its new name preserves narrowing in later cases.
3662+
3663+
```py
3664+
def match_named_expression_guarded_capture(value: int | str) -> None:
3665+
match subject := value:
3666+
case subject if False:
3667+
pass
3668+
case int():
3669+
reveal_type(subject) # revealed: int
3670+
```
3671+
35723672
## Cycles in pattern binding types
35733673

35743674
Pattern captures can affect the type of a later match subject, including through a loop or a

0 commit comments

Comments
 (0)