-
Notifications
You must be signed in to change notification settings - Fork 160
Detect redundant cast usage and emit warning #634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
91d4aaf
af4d4d5
5a58fd7
fb37ea0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -234,6 +234,19 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> { | |
"`typing.cast` missing required argument `val`".to_owned(), | ||
); | ||
} | ||
if let Some(val_expr) = val { | ||
let val_type = self.expr_infer(val_expr, errors); | ||
|
||
if self.subtype(&val_type, &ret) { | ||
self.error( | ||
errors, | ||
range, | ||
ErrorKind::RedundantCast, | ||
None, | ||
"`typing.cast` is unnecessary because the value already has the target type".to_owned(), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this message is slightly misleading if the thing being cast is why not something simpler like "redundant cast to |
||
); | ||
} | ||
} | ||
ret | ||
} | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/* | ||
* Copyright (c) Meta Platforms, Inc. and affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
|
||
use crate::testcase; | ||
|
||
|
||
testcase!( | ||
test_redundant_cast_simple, | ||
r#" | ||
from typing import cast | ||
x = cast(int, 5) # E: Redundant cast: expression already has type `int` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. these messages don't seem to match the implementaiton in special_calls.rs |
||
y = cast(str, "hello") # E: Redundant cast: expression already has type `str` | ||
"#, | ||
); | ||
|
||
testcase!( | ||
test_redundant_cast_with_annotation, | ||
r#" | ||
from typing import cast | ||
x: int = cast(int, 42) # E: Redundant cast: expression already has type `int` | ||
"#, | ||
); | ||
|
||
testcase!( | ||
test_non_redundant_cast, | ||
r#" | ||
from typing import Any, cast | ||
def deserialize(data: Any) -> int: | ||
return cast(int, data) | ||
"#, | ||
); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think
subtype
is a function?Try
is_subset_eq