Support inference for PEP 604 union annotations (#13964)

## Summary

Supports return type inference for, e.g., `def f() -> int | None:`.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
Charlie Marsh 2024-10-28 10:13:01 -04:00 committed by GitHub
parent c593ccb529
commit 6f52d573ef
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 31 additions and 10 deletions

View file

@ -3494,14 +3494,20 @@ impl<'db> TypeInferenceBuilder<'db> {
Type::Todo
}
// TODO PEP-604 unions
ast::Expr::BinOp(binary) => {
self.infer_binary_expression(binary);
#[allow(clippy::single_match_else)]
match binary.op {
// PEP-604 unions are okay
ast::Operator::BitOr => Type::Todo,
// PEP-604 unions are okay, e.g., `int | str`
ast::Operator::BitOr => {
let left_ty = self.infer_type_expression(&binary.left);
let right_ty = self.infer_type_expression(&binary.right);
UnionType::from_elements(self.db, [left_ty, right_ty])
}
// anything else is an invalid annotation:
_ => Type::Unknown,
_ => {
self.infer_binary_expression(binary);
Type::Unknown
}
}
}