From 0006df9292f04d96f8522f4f07b4c3db965d0f6d Mon Sep 17 00:00:00 2001 From: Brandt Bucher Date: Mon, 26 May 2025 20:26:23 -0700 Subject: [PATCH] Fix unrelated negation edge case --- .../ty_python_semantic/resources/mdtest/binary/integers.md | 7 +++++++ crates/ty_python_semantic/src/types/infer.rs | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/ty_python_semantic/resources/mdtest/binary/integers.md b/crates/ty_python_semantic/resources/mdtest/binary/integers.md index d02f78acb1..612f367bcf 100644 --- a/crates/ty_python_semantic/resources/mdtest/binary/integers.md +++ b/crates/ty_python_semantic/resources/mdtest/binary/integers.md @@ -39,6 +39,13 @@ def both(x: int): reveal_type(x // x) # revealed: int reveal_type(x / x) # revealed: int | float reveal_type(x % x) # revealed: int + +# Edge case where negation leads to overflow: +i64_max = 9223372036854775807 +i64_min = -i64_max - 1 +reveal_type(i64_max) # revealed: Literal[9223372036854775807] +reveal_type(i64_min) # revealed: Literal[-9223372036854775808] +reveal_type(-i64_min) # revealed: int ``` ## Power diff --git a/crates/ty_python_semantic/src/types/infer.rs b/crates/ty_python_semantic/src/types/infer.rs index de54290815..c41ffb0fee 100644 --- a/crates/ty_python_semantic/src/types/infer.rs +++ b/crates/ty_python_semantic/src/types/infer.rs @@ -6349,7 +6349,10 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> { (_, Type::Never) => Type::Never, (ast::UnaryOp::UAdd, Type::IntLiteral(value)) => Type::IntLiteral(value), - (ast::UnaryOp::USub, Type::IntLiteral(value)) => Type::IntLiteral(-value), + (ast::UnaryOp::USub, Type::IntLiteral(value)) => value + .checked_neg() + .map(Type::IntLiteral) + .unwrap_or_else(|| KnownClass::Int.to_instance(self.db())), (ast::UnaryOp::Invert, Type::IntLiteral(value)) => Type::IntLiteral(!value), (ast::UnaryOp::UAdd, Type::BooleanLiteral(bool)) => Type::IntLiteral(i64::from(bool)),