-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
[refurb
] Implement math-constant
(FURB152
)
#8727
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
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,7 @@ | ||
r = 3.1 # OK | ||
|
||
A = 3.14 * r ** 2 # FURB152 | ||
|
||
C = 6.28 * r # FURB152 | ||
|
||
e = 2.71 # FURB152 |
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
88 changes: 88 additions & 0 deletions
88
crates/ruff_linter/src/rules/refurb/rules/math_constant.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,88 @@ | ||
use crate::checkers::ast::Checker; | ||
use crate::importer::ImportRequest; | ||
use anyhow::Result; | ||
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::{self as ast, Number}; | ||
use ruff_text_size::Ranged; | ||
|
||
/// ## What it does | ||
/// Checks for literals that are similar to constants in `math` module. | ||
/// | ||
/// ## Why is this bad? | ||
/// Hard coding mathematical constants like π increases code duplication, reduces readability and | ||
/// may lack precision. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// A = 3.141592 * r**2 | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// A = math.pi * r**2 | ||
/// ``` | ||
/// | ||
/// ## References | ||
/// - [Python documentation: `math` constants](https://docs.python.org/3/library/math.html#constants) | ||
#[violation] | ||
pub struct MathConstant { | ||
literal: String, | ||
constant: &'static str, | ||
} | ||
|
||
impl Violation for MathConstant { | ||
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; | ||
|
||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
let MathConstant { literal, constant } = self; | ||
format!("Replace `{literal}` with `math.{constant}`") | ||
} | ||
|
||
fn fix_title(&self) -> Option<String> { | ||
let MathConstant { constant, .. } = self; | ||
Some(format!("Use `math.{constant}`")) | ||
} | ||
} | ||
|
||
fn convert_to_constant( | ||
literal: &ast::ExprNumberLiteral, | ||
constant: &'static str, | ||
checker: &Checker, | ||
) -> Result<Fix> { | ||
let (edit, binding) = checker.importer().get_or_import_symbol( | ||
&ImportRequest::import("math", constant), | ||
literal.start(), | ||
checker.semantic(), | ||
)?; | ||
Ok(Fix::unsafe_edits( | ||
Edit::range_replacement(binding, literal.range()), | ||
[edit], | ||
)) | ||
} | ||
|
||
/// FURB152 | ||
pub(crate) fn math_constant(checker: &mut Checker, literal: &ast::ExprNumberLiteral) { | ||
let Number::Float(value) = literal.value else { | ||
return; | ||
}; | ||
for (real_value, constant) in [ | ||
(std::f64::consts::PI, "pi"), | ||
(std::f64::consts::E, "e"), | ||
(std::f64::consts::TAU, "tau"), | ||
] { | ||
if (value - real_value).abs() < 1e-2 { | ||
let mut diagnostic = Diagnostic::new( | ||
MathConstant { | ||
literal: checker.locator().slice(literal).into(), | ||
constant, | ||
}, | ||
literal.range(), | ||
); | ||
diagnostic.try_set_fix(|| convert_to_constant(literal, constant, checker)); | ||
checker.diagnostics.push(diagnostic); | ||
return; | ||
} | ||
} | ||
} |
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
67 changes: 67 additions & 0 deletions
67
...ter/src/rules/refurb/snapshots/ruff_linter__rules__refurb__tests__FURB152_FURB152.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,67 @@ | ||
--- | ||
source: crates/ruff_linter/src/rules/refurb/mod.rs | ||
--- | ||
FURB152.py:3:5: FURB152 [*] Replace `3.14` with `math.pi` | ||
| | ||
1 | r = 3.1 # OK | ||
2 | | ||
3 | A = 3.14 * r ** 2 # FURB152 | ||
| ^^^^ FURB152 | ||
4 | | ||
5 | C = 6.28 * r # FURB152 | ||
| | ||
= help: Use `math.pi` | ||
|
||
ℹ Unsafe fix | ||
1 |+import math | ||
1 2 | r = 3.1 # OK | ||
2 3 | | ||
3 |-A = 3.14 * r ** 2 # FURB152 | ||
4 |+A = math.pi * r ** 2 # FURB152 | ||
4 5 | | ||
5 6 | C = 6.28 * r # FURB152 | ||
6 7 | | ||
|
||
FURB152.py:5:5: FURB152 [*] Replace `6.28` with `math.tau` | ||
| | ||
3 | A = 3.14 * r ** 2 # FURB152 | ||
4 | | ||
5 | C = 6.28 * r # FURB152 | ||
| ^^^^ FURB152 | ||
6 | | ||
7 | e = 2.71 # FURB152 | ||
| | ||
= help: Use `math.tau` | ||
|
||
ℹ Unsafe fix | ||
1 |+import math | ||
1 2 | r = 3.1 # OK | ||
2 3 | | ||
3 4 | A = 3.14 * r ** 2 # FURB152 | ||
4 5 | | ||
5 |-C = 6.28 * r # FURB152 | ||
6 |+C = math.tau * r # FURB152 | ||
6 7 | | ||
7 8 | e = 2.71 # FURB152 | ||
|
||
FURB152.py:7:5: FURB152 [*] Replace `2.71` with `math.e` | ||
| | ||
5 | C = 6.28 * r # FURB152 | ||
6 | | ||
7 | e = 2.71 # FURB152 | ||
| ^^^^ FURB152 | ||
| | ||
= help: Use `math.e` | ||
|
||
ℹ Unsafe fix | ||
1 |+import math | ||
1 2 | r = 3.1 # OK | ||
2 3 | | ||
3 4 | A = 3.14 * r ** 2 # FURB152 | ||
4 5 | | ||
5 6 | C = 6.28 * r # FURB152 | ||
6 7 | | ||
7 |-e = 2.71 # FURB152 | ||
8 |+e = math.e # FURB152 | ||
|
||
|
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
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.
Why is this an unsafe fix?
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.
Most likely it changes result of calculations. For example,
math.pi
is more precise than3.14
.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'm unsure if that means we need to mark it as unsafe, I could go either way though. @charliermarsh?
If we do leave it as unsafe, we should explain why in the rule docs.
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.
Hah, this is an interesting case. I guess I'd lean towards unsafe since it could break tests, etc., if you had hard-coded expectations that differed slightly?
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 guess but tests written to check floating point math already should include tolerances. Idk I'm struggling to think of a case where this would change runtime behavior in a meaningful way.
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.
Since it's in preview, it may be fine to just use safe and see if we get feedback.