Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions crates/ty_python_semantic/resources/mdtest/conditional/match.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,25 @@ def _(target: None | Foo):
reveal_type(y) # revealed: Literal[1, 3]
```

## `as` patterns

```py
def _(target: int | str):
y = 1

match target:
case 1 as x:
y = 2
reveal_type(x) # revealed: @Todo(`match` pattern definition types)
case "foo" as x:
y = 3
reveal_type(x) # revealed: @Todo(`match` pattern definition types)
case _:
y = 4

reveal_type(y) # revealed: Literal[2, 3, 4]
```

## Guard with object that implements `__bool__` incorrectly

```py
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,32 @@ def no_invalid_return_diagnostic_here_either[T](x: A[T]) -> ASub[T]:
# is null and void (and therefore we don't emit a diagnostic)
return x
```

## More `match` pattern types

### `as` patterns

```py
from typing import assert_never

def as_pattern_exhaustive(subject: int | str):
match subject:
case int() as x:
pass
case str() as y:
pass
case _:
no_diagnostic_here

assert_never(subject)

def as_pattern_non_exhaustive(subject: int | str):
match subject:
case int() as x:
pass
case _:
this_should_be_an_error # error: [unresolved-reference]

# this diagnostic is correct: the inferred type of `subject` is `str`
assert_never(subject) # error: [type-assertion-failure]
```
9 changes: 6 additions & 3 deletions crates/ty_python_semantic/resources/mdtest/import/star.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,16 +182,19 @@ class ContextManagerThatMightNotRunToCompletion:
with ContextManagerThatMightNotRunToCompletion() as L:
U = ...

match 42:
def get_object() -> object:
pass

match get_object():
case {"something": M}:
...
case [*N]:
...
case [O]:
...
case P | Q: # error: [invalid-syntax] "name capture `P` makes remaining patterns unreachable"
case I(foo=R):
...
case object(foo=R):
case P | Q:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed the order here (and matched on I(…) instead of object(…)). The test would fail otherwise because we would detect the P | Q pattern to be always reachable (and the ones behind it to not be reachable). I don't think this was the original intention of this test (or the assertion below should have a TODO).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup, the intent of the test is just to check that the re_exports query correctly identifies both Or patterns and Class patterns as binding names in the global scope

...

match 56:
Expand Down
7 changes: 7 additions & 0 deletions crates/ty_python_semantic/src/semantic_index/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,13 @@ impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
.collect();
PatternPredicateKind::Or(predicates)
}
ast::Pattern::MatchAs(pattern) => PatternPredicateKind::As(
pattern
.pattern
.as_ref()
.map(|p| Box::new(self.predicate_kind(p))),
pattern.name.as_ref().map(|name| name.id.clone()),
),
_ => PatternPredicateKind::Unsupported,
}
}
Expand Down
3 changes: 2 additions & 1 deletion crates/ty_python_semantic/src/semantic_index/predicate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

use ruff_db::files::File;
use ruff_index::{Idx, IndexVec};
use ruff_python_ast::Singleton;
use ruff_python_ast::{Singleton, name::Name};

use crate::db::Db;
use crate::semantic_index::expression::Expression;
Expand Down Expand Up @@ -136,6 +136,7 @@ pub(crate) enum PatternPredicateKind<'db> {
Value(Expression<'db>),
Or(Vec<PatternPredicateKind<'db>>),
Class(Expression<'db>, ClassPatternKind),
As(Option<Box<PatternPredicateKind<'db>>>, Option<Name>),
Unsupported,
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,10 @@ fn pattern_kind_to_type<'db>(db: &'db dyn Db, kind: &PatternPredicateKind<'db>)
PatternPredicateKind::Or(predicates) => {
UnionType::from_elements(db, predicates.iter().map(|p| pattern_kind_to_type(db, p)))
}
PatternPredicateKind::As(pattern, _) => pattern
.as_deref()
.map(|p| pattern_kind_to_type(db, p))
.unwrap_or_else(|| Type::object(db)),
PatternPredicateKind::Unsupported => Type::Never,
}
}
Expand Down Expand Up @@ -761,6 +765,10 @@ impl ReachabilityConstraints {
}
})
}
PatternPredicateKind::As(pattern, _) => pattern
.as_deref()
.map(|p| Self::analyze_single_pattern_predicate_kind(db, p, subject_ty))
.unwrap_or(Truthiness::AlwaysTrue),
PatternPredicateKind::Unsupported => Truthiness::Ambiguous,
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ty_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3584,7 +3584,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
fn infer_nested_match_pattern(&mut self, pattern: &ast::Pattern) {
match pattern {
ast::Pattern::MatchValue(match_value) => {
self.infer_expression(&match_value.value);
self.infer_maybe_standalone_expression(&match_value.value);
}
ast::Pattern::MatchSequence(match_sequence) => {
for pattern in &match_sequence.patterns {
Expand Down Expand Up @@ -3619,7 +3619,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
for keyword in &arguments.keywords {
self.infer_nested_match_pattern(&keyword.pattern);
}
self.infer_expression(cls);
self.infer_maybe_standalone_expression(cls);
}
ast::Pattern::MatchAs(match_as) => {
if let Some(pattern) = &match_as.pattern {
Expand Down
3 changes: 3 additions & 0 deletions crates/ty_python_semantic/src/types/narrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,9 @@ impl<'db, 'ast> NarrowingConstraintsBuilder<'db, 'ast> {
PatternPredicateKind::Or(predicates) => {
self.evaluate_match_pattern_or(subject, predicates, is_positive)
}
PatternPredicateKind::As(pattern, _) => pattern
.as_deref()
.and_then(|p| self.evaluate_pattern_predicate_kind(p, subject, is_positive)),
PatternPredicateKind::Unsupported => None,
}
}
Expand Down
Loading