[ty] only issue redundant-cast on fully static types

This commit is contained in:
Carl Meyer 2025-05-12 15:59:29 -07:00
parent 0d6fafd0f9
commit 2736e87b2c
No known key found for this signature in database
GPG key ID: 2D1FB7916A52E121
2 changed files with 7 additions and 17 deletions

View file

@ -31,12 +31,6 @@ def function_returning_int() -> int:
# error: [redundant-cast] "Value is already of type `int`" # error: [redundant-cast] "Value is already of type `int`"
cast(int, function_returning_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]` 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) b = cast(tuple[list[bytes]], y)
``` ```
A cast from `Todo` or `Unknown` to `Any` is not considered a "redundant cast": even if these are Casting `Unknown` to `Unknown` or `Any` to `Any` is not considered redundant; these dynamic types
understood as gradually equivalent types by ty, they are understood as different types by human may represent different static types, and erroring on this violates the gradual guarantee.
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.
```py ```py
from ty_extensions import Unknown from ty_extensions import Unknown
@ -66,5 +57,8 @@ def f(x: Any, y: Unknown, z: Any | str | int):
b = cast(Any, y) b = cast(Any, y)
reveal_type(b) # revealed: Any 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)
``` ```

View file

@ -4908,11 +4908,7 @@ impl<'db> TypeInferenceBuilder<'db> {
overload.parameter_types() overload.parameter_types()
{ {
let db = self.db(); let db = self.db();
if (source_type.is_equivalent_to(db, *casted_type) if source_type.is_equivalent_to(db, *casted_type) {
|| source_type.normalized(db)
== casted_type.normalized(db))
&& !source_type.contains_todo(db)
{
if let Some(builder) = self if let Some(builder) = self
.context .context
.report_lint(&REDUNDANT_CAST, call_expression) .report_lint(&REDUNDANT_CAST, call_expression)