-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
## Summary <!-- What's the purpose of the change? What does it do, and why? --> Implement FURB164 in the issue #1348. Relevant Refurb docs is here: https://github.com/dosisod/refurb/blob/v2.0.0/docs/checks.md#furb164-no-from-float I've changed the name from `no-from-float` to `verbose-decimal-fraction-construction`. ## Test Plan <!-- How was it tested? --> I've written it in the `FURB164.py`. --------- Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
- Loading branch information
1 parent
75e0142
commit 9ad9cea
Showing
9 changed files
with
606 additions
and
2 deletions.
There are no files selected for viewing
34 changes: 34 additions & 0 deletions
34
crates/ruff_linter/resources/test/fixtures/refurb/FURB164.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,34 @@ | ||
from decimal import Decimal | ||
from fractions import Fraction | ||
import decimal | ||
import fractions | ||
|
||
# Errors | ||
_ = Fraction.from_float(0.1) | ||
_ = Fraction.from_float(-0.5) | ||
_ = Fraction.from_float(5.0) | ||
_ = fractions.Fraction.from_float(4.2) | ||
_ = Fraction.from_decimal(Decimal("4.2")) | ||
_ = Fraction.from_decimal(Decimal("-4.2")) | ||
_ = Fraction.from_decimal(Decimal.from_float(4.2)) | ||
_ = Decimal.from_float(0.1) | ||
_ = Decimal.from_float(-0.5) | ||
_ = Decimal.from_float(5.0) | ||
_ = decimal.Decimal.from_float(4.2) | ||
_ = Decimal.from_float(float("inf")) | ||
_ = Decimal.from_float(float("-inf")) | ||
_ = Decimal.from_float(float("Infinity")) | ||
_ = Decimal.from_float(float("-Infinity")) | ||
_ = Decimal.from_float(float("nan")) | ||
|
||
# OK | ||
_ = Fraction(0.1) | ||
_ = Fraction(-0.5) | ||
_ = Fraction(5.0) | ||
_ = fractions.Fraction(4.2) | ||
_ = Fraction(Decimal("4.2")) | ||
_ = Fraction(Decimal("-4.2")) | ||
_ = Decimal(0.1) | ||
_ = Decimal(-0.5) | ||
_ = Decimal(5.0) | ||
_ = decimal.Decimal(4.2) |
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
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
205 changes: 205 additions & 0 deletions
205
crates/ruff_linter/src/rules/refurb/rules/unnecessary_from_float.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,205 @@ | ||
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::{self as ast, Expr, ExprCall}; | ||
use ruff_text_size::Ranged; | ||
|
||
use crate::checkers::ast::Checker; | ||
|
||
/// ## What it does | ||
/// Checks for unnecessary `from_float` and `from_decimal` usages to construct | ||
/// `Decimal` and `Fraction` instances. | ||
/// | ||
/// ## Why is this bad? | ||
/// Since Python 3.2, the `Fraction` and `Decimal` classes can be constructed | ||
/// by passing float or decimal instances to the constructor directly. As such, | ||
/// the use of `from_float` and `from_decimal` methods is unnecessary, and | ||
/// should be avoided in favor of the more concise constructor syntax. | ||
/// | ||
/// ## Examples | ||
/// ```python | ||
/// Decimal.from_float(4.2) | ||
/// Decimal.from_float(float("inf")) | ||
/// Fraction.from_float(4.2) | ||
/// Fraction.from_decimal(Decimal("4.2")) | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// Decimal(4.2) | ||
/// Decimal("inf") | ||
/// Fraction(4.2) | ||
/// Fraction(Decimal(4.2)) | ||
/// ``` | ||
/// | ||
/// ## References | ||
/// - [Python documentation: `decimal`](https://docs.python.org/3/library/decimal.html) | ||
/// - [Python documentation: `fractions`](https://docs.python.org/3/library/fractions.html) | ||
#[violation] | ||
pub struct UnnecessaryFromFloat { | ||
method_name: MethodName, | ||
constructor: Constructor, | ||
} | ||
|
||
impl Violation for UnnecessaryFromFloat { | ||
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; | ||
|
||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
let UnnecessaryFromFloat { | ||
method_name, | ||
constructor, | ||
} = self; | ||
format!("Verbose method `{method_name}` in `{constructor}` construction",) | ||
} | ||
|
||
fn fix_title(&self) -> Option<String> { | ||
let UnnecessaryFromFloat { constructor, .. } = self; | ||
Some(format!("Replace with `{constructor}` constructor")) | ||
} | ||
} | ||
|
||
/// FURB164 | ||
pub(crate) fn unnecessary_from_float(checker: &mut Checker, call: &ExprCall) { | ||
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = &*call.func else { | ||
return; | ||
}; | ||
|
||
// The method name must be either `from_float` or `from_decimal`. | ||
let method_name = match attr.as_str() { | ||
"from_float" => MethodName::FromFloat, | ||
"from_decimal" => MethodName::FromDecimal, | ||
_ => return, | ||
}; | ||
|
||
// The value must be either `decimal.Decimal` or `fractions.Fraction`. | ||
let Some(constructor) = | ||
checker | ||
.semantic() | ||
.resolve_qualified_name(value) | ||
.and_then(|qualified_name| match qualified_name.segments() { | ||
["decimal", "Decimal"] => Some(Constructor::Decimal), | ||
["fractions", "Fraction"] => Some(Constructor::Fraction), | ||
_ => None, | ||
}) | ||
else { | ||
return; | ||
}; | ||
|
||
// `Decimal.from_decimal` doesn't exist. | ||
if matches!( | ||
(method_name, constructor), | ||
(MethodName::FromDecimal, Constructor::Decimal) | ||
) { | ||
return; | ||
} | ||
|
||
let mut diagnostic = Diagnostic::new( | ||
UnnecessaryFromFloat { | ||
method_name, | ||
constructor, | ||
}, | ||
call.range(), | ||
); | ||
|
||
let edit = Edit::range_replacement( | ||
checker.locator().slice(&**value).to_string(), | ||
call.func.range(), | ||
); | ||
|
||
// Short-circuit case for special values, such as: `Decimal.from_float(float("inf"))` to `Decimal("inf")`. | ||
'short_circuit: { | ||
if !matches!(constructor, Constructor::Decimal) { | ||
break 'short_circuit; | ||
}; | ||
if !(method_name == MethodName::FromFloat) { | ||
break 'short_circuit; | ||
}; | ||
|
||
let Some(value) = (match method_name { | ||
MethodName::FromFloat => call.arguments.find_argument("f", 0), | ||
MethodName::FromDecimal => call.arguments.find_argument("dec", 0), | ||
}) else { | ||
return; | ||
}; | ||
|
||
let Expr::Call( | ||
call @ ast::ExprCall { | ||
func, arguments, .. | ||
}, | ||
) = value | ||
else { | ||
break 'short_circuit; | ||
}; | ||
|
||
// Must be a call to the `float` builtin. | ||
let Some(func_name) = func.as_name_expr() else { | ||
break 'short_circuit; | ||
}; | ||
if func_name.id != "float" { | ||
break 'short_circuit; | ||
}; | ||
|
||
// Must have exactly one argument, which is a string literal. | ||
if arguments.keywords.len() != 0 { | ||
break 'short_circuit; | ||
}; | ||
let [float] = arguments.args.as_ref() else { | ||
break 'short_circuit; | ||
}; | ||
let Some(float) = float.as_string_literal_expr() else { | ||
break 'short_circuit; | ||
}; | ||
if !matches!( | ||
float.value.to_str().to_lowercase().as_str(), | ||
"inf" | "-inf" | "infinity" | "-infinity" | "nan" | ||
) { | ||
break 'short_circuit; | ||
} | ||
|
||
if !checker.semantic().is_builtin("float") { | ||
break 'short_circuit; | ||
}; | ||
|
||
let replacement = checker.locator().slice(float).to_string(); | ||
diagnostic.set_fix(Fix::safe_edits( | ||
edit, | ||
[Edit::range_replacement(replacement, call.range())], | ||
)); | ||
checker.diagnostics.push(diagnostic); | ||
|
||
return; | ||
} | ||
|
||
diagnostic.set_fix(Fix::safe_edit(edit)); | ||
checker.diagnostics.push(diagnostic); | ||
} | ||
|
||
#[derive(Debug, Copy, Clone, PartialEq, Eq)] | ||
enum MethodName { | ||
FromFloat, | ||
FromDecimal, | ||
} | ||
|
||
impl std::fmt::Display for MethodName { | ||
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { | ||
match self { | ||
MethodName::FromFloat => fmt.write_str("from_float"), | ||
MethodName::FromDecimal => fmt.write_str("from_decimal"), | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug, Copy, Clone, PartialEq, Eq)] | ||
enum Constructor { | ||
Decimal, | ||
Fraction, | ||
} | ||
|
||
impl std::fmt::Display for Constructor { | ||
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { | ||
match self { | ||
Constructor::Decimal => fmt.write_str("Decimal"), | ||
Constructor::Fraction => fmt.write_str("Fraction"), | ||
} | ||
} | ||
} |
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
Oops, something went wrong.