Skip to content

Commit

Permalink
Small updates
Browse files Browse the repository at this point in the history
  • Loading branch information
tibor-reiss committed Apr 18, 2024
1 parent 74f7ee5 commit 4875d68
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 60 deletions.
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
# These testcases should raise errors


class Bool:
def __hash__(self):
return True # [invalid-hash-return]


class Float:
def __hash__(self):
return 3.05 # [invalid-hash-return]


class Str:
def __hash__(self):
return "ruff" # [invalid-hash-return]


class HashNoReturn:
def __hash__(self):
print("ruff") # [invalid-hash-return]


class HashWrongRaise:
def __hash__(self):
print("raise some error")
raise NotImplementedError # [invalid-hash-return]


# TODO: Once Ruff has better type checking
def return_int():
return "3"


class ComplexReturn:
def __hash__(self):
return return_int() # [invalid-hash-return]
Expand All @@ -33,23 +40,27 @@ def __hash__(self):

# These testcases should NOT raise errors


class Hash:
def __hash__(self):
return 7741


class Hash2:
def __hash__(self):
x = 7741
return x


class Hash3:
def __hash__(self):
...
def __hash__(self): ...


class Has4:
def __hash__(self):
pass


class Hash5:
def __hash__(self):
raise NotImplementedError
raise NotImplementedError
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/checkers/ast/analyze/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
pylint::rules::invalid_bytes_return(checker, function_def);
}
if checker.enabled(Rule::InvalidHashReturnType) {
pylint::rules::invalid_hash_return(checker, name, body);
pylint::rules::invalid_hash_return(checker, function_def);
}
if checker.enabled(Rule::InvalidStrReturnType) {
pylint::rules::invalid_str_return(checker, function_def);
Expand Down
37 changes: 13 additions & 24 deletions crates/ruff_linter/src/rules/pylint/rules/invalid_hash_return.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::ReturnStatementVisitor;
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::Stmt;
use ruff_python_ast::{self as ast};
use ruff_python_semantic::analyze::function_type::is_stub;
use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType};
use ruff_text_size::Ranged;

Expand All @@ -15,6 +17,10 @@ use crate::checkers::ast::Checker;
/// The `__hash__` method should return an `integer`. Returning a different
/// type may cause unexpected behavior.
///
/// Note: `bool` is a subclass of `int`, so it's technically valid for `__hash__` to
/// return `True` or `False`. However, for consistency with other rules, Ruff will
/// still raise when `__hash__` returns a `bool`.
///
/// ## Example
/// ```python
/// class Foo:
Expand All @@ -29,9 +35,7 @@ use crate::checkers::ast::Checker;
/// return 2
/// ```
///
/// Note: Strictly speaking `bool` is a subclass of `int`, thus returning `True`/`False` is valid.
/// To be consistent with other rules (e.g. PLE0305 invalid-index-returned), ruff will raise, compared
/// to pylint which will not raise.
///
/// ## References
/// - [Python documentation: The `__hash__` method](https://docs.python.org/3/reference/datamodel.html#object.__hash__)
#[violation]
Expand All @@ -45,44 +49,29 @@ impl Violation for InvalidHashReturnType {
}

/// E0309
pub(crate) fn invalid_hash_return(checker: &mut Checker, name: &str, body: &[Stmt]) {
if name != "__hash__" {
pub(crate) fn invalid_hash_return(checker: &mut Checker, function_def: &ast::StmtFunctionDef) {
if function_def.name.as_str() != "__hash__" {
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() {
if is_stub(function_def, checker.semantic()) {
return;
}

let returns = {
let mut visitor = ReturnStatementVisitor::default();
visitor.visit_body(body);
visitor.visit_body(&function_def.body);
visitor.returns
};

if returns.is_empty() {
checker.diagnostics.push(Diagnostic::new(
InvalidHashReturnType,
body.last().unwrap().range(),
function_def.identifier(),
));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,52 +1,43 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
invalid_return_type_hash.py:5:16: PLE0309 `__hash__` does not return `integer`
invalid_return_type_hash.py:6:16: PLE0309 `__hash__` does not return `integer`
|
3 | class Bool:
4 | def __hash__(self):
5 | return True # [invalid-hash-return]
4 | class Bool:
5 | def __hash__(self):
6 | return True # [invalid-hash-return]
| ^^^^ PLE0309
6 |
7 | class Float:
|

invalid_return_type_hash.py:9:16: PLE0309 `__hash__` does not return `integer`
invalid_return_type_hash.py:11:16: PLE0309 `__hash__` does not return `integer`
|
7 | class Float:
8 | def __hash__(self):
9 | return 3.05 # [invalid-hash-return]
9 | class Float:
10 | def __hash__(self):
11 | return 3.05 # [invalid-hash-return]
| ^^^^ PLE0309
10 |
11 | class Str:
|

invalid_return_type_hash.py:13:16: PLE0309 `__hash__` does not return `integer`
invalid_return_type_hash.py:16:16: PLE0309 `__hash__` does not return `integer`
|
11 | class Str:
12 | def __hash__(self):
13 | return "ruff" # [invalid-hash-return]
14 | class Str:
15 | def __hash__(self):
16 | return "ruff" # [invalid-hash-return]
| ^^^^^^ PLE0309
14 |
15 | class HashNoReturn:
|

invalid_return_type_hash.py:17:9: PLE0309 `__hash__` does not return `integer`
invalid_return_type_hash.py:20:9: PLE0309 `__hash__` does not return `integer`
|
15 | class HashNoReturn:
16 | def __hash__(self):
17 | print("ruff") # [invalid-hash-return]
| ^^^^^^^^^^^^^ PLE0309
18 |
19 | class HashWrongRaise:
19 | class HashNoReturn:
20 | def __hash__(self):
| ^^^^^^^^ PLE0309
21 | print("ruff") # [invalid-hash-return]
|

invalid_return_type_hash.py:22:9: PLE0309 `__hash__` does not return `integer`
invalid_return_type_hash.py:25:9: PLE0309 `__hash__` does not return `integer`
|
20 | def __hash__(self):
21 | print("raise some error")
22 | raise NotImplementedError # [invalid-hash-return]
| ^^^^^^^^^^^^^^^^^^^^^^^^^ PLE0309
23 |
24 | # TODO: Once Ruff has better type checking
24 | class HashWrongRaise:
25 | def __hash__(self):
| ^^^^^^^^ PLE0309
26 | print("raise some error")
27 | raise NotImplementedError # [invalid-hash-return]
|

0 comments on commit 4875d68

Please sign in to comment.