-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
[pylint
] Implement invalid-bytes-returned
(E0308
)
#10959
Merged
charliermarsh
merged 7 commits into
astral-sh:main
from
tibor-reiss:add-E0308-invalid-bytes-returned
Apr 18, 2024
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
be811c6
Implement E0308 - invalid-bytes-returned
tibor-reiss 197b5fc
Code review
tibor-reiss c5d6194
ellipsis, raise
tibor-reiss 4faf319
special raise
tibor-reiss e218cc1
Format fixture
charliermarsh 5b5b86a
Merge branch 'main' into add-E0308-invalid-bytes-returned
charliermarsh ced76b9
Use is_stub
charliermarsh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
54 changes: 54 additions & 0 deletions
54
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_bytes.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# These testcases should raise errors | ||
|
||
class Float: | ||
def __bytes__(self): | ||
return 3.05 # [invalid-bytes-return] | ||
|
||
class Int: | ||
def __bytes__(self): | ||
return 0 # [invalid-bytes-return] | ||
|
||
class Str: | ||
def __bytes__(self): | ||
return "some bytes" # [invalid-bytes-return] | ||
|
||
class BytesNoReturn: | ||
def __bytes__(self): | ||
print("ruff") # [invalid-bytes-return] | ||
|
||
class BytesWrongRaise: | ||
def __bytes__(self): | ||
print("raise some error") | ||
raise NotImplementedError # [invalid-bytes-return] | ||
|
||
# TODO: Once Ruff has better type checking | ||
def return_bytes(): | ||
return "some string" | ||
|
||
class ComplexReturn: | ||
def __bytes__(self): | ||
return return_bytes() # [invalid-bytes-return] | ||
|
||
|
||
# These testcases should NOT raise errors | ||
|
||
class Bytes: | ||
def __bytes__(self): | ||
return b"some bytes" | ||
|
||
class Bytes2: | ||
def __bytes__(self): | ||
x = b"some bytes" | ||
return x | ||
|
||
class Bytes3: | ||
def __bytes__(self): | ||
... | ||
|
||
class Bytes4: | ||
def __bytes__(self): | ||
pass | ||
|
||
class Bytes5: | ||
def __bytes__(self): | ||
raise NotImplementedError |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
103 changes: 103 additions & 0 deletions
103
crates/ruff_linter/src/rules/pylint/rules/invalid_bytes_return.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
use ruff_diagnostics::{Diagnostic, Violation}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::helpers::ReturnStatementVisitor; | ||
use ruff_python_ast::visitor::Visitor; | ||
use ruff_python_ast::Stmt; | ||
use ruff_python_semantic::analyze::type_inference::{PythonType, ResolvedPythonType}; | ||
use ruff_text_size::Ranged; | ||
|
||
use crate::checkers::ast::Checker; | ||
|
||
/// ## What it does | ||
/// Checks for `__bytes__` implementations that return a type other than `bytes`. | ||
/// | ||
/// ## Why is this bad? | ||
/// The `__bytes__` method should return a `bytes` object. Returning a different | ||
/// type may cause unexpected behavior. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// class Foo: | ||
/// def __bytes__(self): | ||
/// return 2 | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// class Foo: | ||
/// def __bytes__(self): | ||
/// return b"2" | ||
/// ``` | ||
/// | ||
/// ## References | ||
/// - [Python documentation: The `__bytes__` method](https://docs.python.org/3/reference/datamodel.html#object.__bytes__) | ||
#[violation] | ||
pub struct InvalidBytesReturnType; | ||
|
||
impl Violation for InvalidBytesReturnType { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("`__bytes__` does not return `bytes`") | ||
} | ||
} | ||
|
||
/// E0308 | ||
pub(crate) fn invalid_bytes_return(checker: &mut Checker, name: &str, body: &[Stmt]) { | ||
if name != "__bytes__" { | ||
return; | ||
} | ||
|
||
if !checker.semantic().current_scope().kind.is_class() { | ||
return; | ||
} | ||
|
||
if body.len() == 1 | ||
&& (matches!(&body[0], Stmt::Expr(expr) if expr.value.is_ellipsis_literal_expr()) | ||
|| body[0].is_pass_stmt() | ||
|| body[0].is_raise_stmt()) | ||
{ | ||
return; | ||
} | ||
|
||
let body_without_comments = body | ||
.iter() | ||
.filter(|stmt| !matches!(stmt, Stmt::Expr(expr) if expr.value.is_string_literal_expr())) | ||
.collect::<Vec<_>>(); | ||
if body_without_comments.is_empty() { | ||
return; | ||
} | ||
if body_without_comments.len() == 1 && body_without_comments[0].is_raise_stmt() { | ||
return; | ||
} | ||
|
||
let returns = { | ||
let mut visitor = ReturnStatementVisitor::default(); | ||
visitor.visit_body(body); | ||
visitor.returns | ||
}; | ||
|
||
if returns.is_empty() { | ||
checker.diagnostics.push(Diagnostic::new( | ||
InvalidBytesReturnType, | ||
body.last().unwrap().range(), | ||
)); | ||
} | ||
|
||
for stmt in returns { | ||
if let Some(value) = stmt.value.as_deref() { | ||
if !matches!( | ||
ResolvedPythonType::from(value), | ||
ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Bytes) | ||
) { | ||
checker | ||
.diagnostics | ||
.push(Diagnostic::new(InvalidBytesReturnType, value.range())); | ||
} | ||
} else { | ||
// Disallow implicit `None`. | ||
checker | ||
.diagnostics | ||
.push(Diagnostic::new(InvalidBytesReturnType, stmt.range())); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
...nt/snapshots/ruff_linter__rules__pylint__tests__PLE0308_invalid_return_type_bytes.py.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
--- | ||
source: crates/ruff_linter/src/rules/pylint/mod.rs | ||
--- | ||
invalid_return_type_bytes.py:5:16: PLE0308 `__bytes__` does not return `bytes` | ||
| | ||
3 | class Float: | ||
4 | def __bytes__(self): | ||
5 | return 3.05 # [invalid-bytes-return] | ||
| ^^^^ PLE0308 | ||
6 | | ||
7 | class Int: | ||
| | ||
|
||
invalid_return_type_bytes.py:9:16: PLE0308 `__bytes__` does not return `bytes` | ||
| | ||
7 | class Int: | ||
8 | def __bytes__(self): | ||
9 | return 0 # [invalid-bytes-return] | ||
| ^ PLE0308 | ||
10 | | ||
11 | class Str: | ||
| | ||
|
||
invalid_return_type_bytes.py:13:16: PLE0308 `__bytes__` does not return `bytes` | ||
| | ||
11 | class Str: | ||
12 | def __bytes__(self): | ||
13 | return "some bytes" # [invalid-bytes-return] | ||
| ^^^^^^^^^^^^ PLE0308 | ||
14 | | ||
15 | class BytesNoReturn: | ||
| | ||
|
||
invalid_return_type_bytes.py:17:9: PLE0308 `__bytes__` does not return `bytes` | ||
| | ||
15 | class BytesNoReturn: | ||
16 | def __bytes__(self): | ||
17 | print("ruff") # [invalid-bytes-return] | ||
| ^^^^^^^^^^^^^ PLE0308 | ||
18 | | ||
19 | class BytesWrongRaise: | ||
| | ||
|
||
invalid_return_type_bytes.py:22:9: PLE0308 `__bytes__` does not return `bytes` | ||
| | ||
20 | def __bytes__(self): | ||
21 | print("raise some error") | ||
22 | raise NotImplementedError # [invalid-bytes-return] | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^ PLE0308 | ||
23 | | ||
24 | # TODO: Once Ruff has better type checking | ||
| |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Should this rule and the other invalid-*-returned rules also flag the case where the method has no return statement
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 added this case as well. If this becomes the consensus, I can also add it to the already included bool (E0304) and str (E0307) cases.
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.
@MichaReiser As it turned out, the no-return case is not that simple: if there is just a pass/ellipsis/raise statement, then this rule should not raise. However, if there is e.g. a print statement and a raise statement, then it should raise - see the tests for examples.
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 changed this to use
is_stub
for detecting the other cases.