Skip to content

Commit e2a38e4

Browse files
authored
[red-knot] optimize is_subtype_of for literals (#17394)
## Summary Allows us to establish that two literals do not have a subtype relationship with each other, without having to fallback to a typeshed Instance type, which is comparatively slow. Improves the performance of the many-string-literals union benchmark by 5x. ## Test Plan `cargo test -p red_knot_python_semantic` and `cargo bench --bench red_knot`.
1 parent 9bee942 commit e2a38e4

File tree

1 file changed

+21
-0
lines changed
  • crates/red_knot_python_semantic/src

1 file changed

+21
-0
lines changed

crates/red_knot_python_semantic/src/types.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,27 @@ impl<'db> Type<'db> {
886886
target.is_equivalent_to(db, Type::object(db))
887887
}
888888

889+
// No literal type is a subtype of any other literal type, unless they are the same
890+
// type (which is handled above). This case is not necessary from a correctness
891+
// perspective (the fallback cases below will handle it correctly), but it is important
892+
// for performance of simplifying large unions of literal types.
893+
(
894+
Type::StringLiteral(_)
895+
| Type::IntLiteral(_)
896+
| Type::BytesLiteral(_)
897+
| Type::ClassLiteral(_)
898+
| Type::FunctionLiteral(_)
899+
| Type::ModuleLiteral(_)
900+
| Type::SliceLiteral(_),
901+
Type::StringLiteral(_)
902+
| Type::IntLiteral(_)
903+
| Type::BytesLiteral(_)
904+
| Type::ClassLiteral(_)
905+
| Type::FunctionLiteral(_)
906+
| Type::ModuleLiteral(_)
907+
| Type::SliceLiteral(_),
908+
) => false,
909+
889910
// All `StringLiteral` types are a subtype of `LiteralString`.
890911
(Type::StringLiteral(_), Type::LiteralString) => true,
891912

0 commit comments

Comments
 (0)