From 2736e87b2cc81c02d1356cf00b29379d5ca08239 Mon Sep 17 00:00:00 2001 From: Carl Meyer Date: Mon, 12 May 2025 15:59:29 -0700 Subject: [PATCH] [ty] only issue redundant-cast on fully static types --- .../resources/mdtest/directives/cast.md | 18 ++++++------------ crates/ty_python_semantic/src/types/infer.rs | 6 +----- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/crates/ty_python_semantic/resources/mdtest/directives/cast.md b/crates/ty_python_semantic/resources/mdtest/directives/cast.md index 9731d4cb37..cc34b37aba 100644 --- a/crates/ty_python_semantic/resources/mdtest/directives/cast.md +++ b/crates/ty_python_semantic/resources/mdtest/directives/cast.md @@ -31,12 +31,6 @@ def function_returning_int() -> int: # error: [redundant-cast] "Value is already of type `int`" cast(int, function_returning_int()) - -def function_returning_any() -> Any: - return "blah" - -# error: [redundant-cast] "Value is already of type `Any`" -cast(Any, function_returning_any()) ``` Complex type expressions (which may be unsupported) do not lead to spurious `[redundant-cast]` @@ -50,11 +44,8 @@ def f(x: Callable[[dict[str, int]], None], y: tuple[dict[str, int]]): b = cast(tuple[list[bytes]], y) ``` -A cast from `Todo` or `Unknown` to `Any` is not considered a "redundant cast": even if these are -understood as gradually equivalent types by ty, they are understood as different types by human -readers of ty's output. For `Unknown` in particular, we may consider it differently in the context -of some opt-in diagnostics, as it indicates that the gradual type has come about due to an invalid -annotation, missing annotation or missing type argument somewhere. +Casting `Unknown` to `Unknown` or `Any` to `Any` is not considered redundant; these dynamic types +may represent different static types, and erroring on this violates the gradual guarantee. ```py from ty_extensions import Unknown @@ -66,5 +57,8 @@ def f(x: Any, y: Unknown, z: Any | str | int): b = cast(Any, y) reveal_type(b) # revealed: Any - c = cast(str | int | Any, z) # error: [redundant-cast] + c = cast(str | int | Any, z) + + d = cast(y, y) + e = cast(x, x) ``` diff --git a/crates/ty_python_semantic/src/types/infer.rs b/crates/ty_python_semantic/src/types/infer.rs index 43c384c84f..3889d6e829 100644 --- a/crates/ty_python_semantic/src/types/infer.rs +++ b/crates/ty_python_semantic/src/types/infer.rs @@ -4908,11 +4908,7 @@ impl<'db> TypeInferenceBuilder<'db> { overload.parameter_types() { let db = self.db(); - if (source_type.is_equivalent_to(db, *casted_type) - || source_type.normalized(db) - == casted_type.normalized(db)) - && !source_type.contains_todo(db) - { + if source_type.is_equivalent_to(db, *casted_type) { if let Some(builder) = self .context .report_lint(&REDUNDANT_CAST, call_expression)