-
Notifications
You must be signed in to change notification settings - Fork 1.6k
[ruff] Fix false positives and negatives in RUF010
#18690
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
eb39e30
[`ruff`] Fix false positives and negatives in `RUF010`
LaBatata101 21edcd0
Suppress fix for starred expressions
LaBatata101 9090ea3
Fix false negative
LaBatata101 9c2bce2
fix typo
LaBatata101 0af2362
Address feedback
LaBatata101 568f4f4
Update code
LaBatata101 13921af
Refactor code
LaBatata101 37dc947
Update code
LaBatata101 e8ecbb6
Fix tests
LaBatata101 a1b5012
Remove unnecessary check
LaBatata101 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,16 +1,14 @@ | ||
| use anyhow::{Result, bail}; | ||
| use std::fmt::Display; | ||
|
|
||
| use anyhow::Result; | ||
|
|
||
| use ruff_macros::{ViolationMetadata, derive_message_formats}; | ||
| use ruff_python_ast::{self as ast, Arguments, Expr}; | ||
| use ruff_python_codegen::Stylist; | ||
| use ruff_python_ast::parenthesize::parenthesized_range; | ||
| use ruff_python_ast::{self as ast, Expr}; | ||
| use ruff_python_parser::TokenKind; | ||
| use ruff_text_size::Ranged; | ||
|
|
||
| use crate::Locator; | ||
| use crate::checkers::ast::Checker; | ||
| use crate::cst::matchers::{ | ||
| match_call_mut, match_formatted_string, match_formatted_string_expression, match_name, | ||
| transform_expression, | ||
| }; | ||
| use crate::{AlwaysFixableViolation, Edit, Fix}; | ||
|
|
||
| /// ## What it does | ||
|
|
@@ -53,7 +51,7 @@ impl AlwaysFixableViolation for ExplicitFStringTypeConversion { | |
|
|
||
| /// RUF010 | ||
| pub(crate) fn explicit_f_string_type_conversion(checker: &Checker, f_string: &ast::FString) { | ||
| for (index, element) in f_string.elements.iter().enumerate() { | ||
| for element in &f_string.elements { | ||
| let Some(ast::InterpolatedElement { | ||
| expression, | ||
| conversion, | ||
|
|
@@ -68,84 +66,126 @@ pub(crate) fn explicit_f_string_type_conversion(checker: &Checker, f_string: &as | |
| continue; | ||
| } | ||
|
|
||
| let Expr::Call(ast::ExprCall { | ||
| func, | ||
| arguments: | ||
| Arguments { | ||
| args, | ||
| keywords, | ||
| range: _, | ||
| node_index: _, | ||
| }, | ||
| .. | ||
| }) = expression.as_ref() | ||
| else { | ||
| let Expr::Call(call) = expression.as_ref() else { | ||
| continue; | ||
| }; | ||
|
|
||
| // Can't be a conversion otherwise. | ||
| if !keywords.is_empty() { | ||
| continue; | ||
| } | ||
|
|
||
| // Can't be a conversion otherwise. | ||
| let [arg] = &**args else { | ||
| let Some(conversion) = checker | ||
| .semantic() | ||
| .resolve_builtin_symbol(&call.func) | ||
| .and_then(Conversion::from_str) | ||
| else { | ||
| continue; | ||
| }; | ||
| let arg = match conversion { | ||
| // Handles the cases: `f"{str(object=arg)}"` and `f"{str(arg)}"` | ||
| Conversion::Str if call.arguments.len() == 1 => { | ||
| let Some(arg) = call.arguments.find_argument_value("object", 0) else { | ||
| continue; | ||
| }; | ||
| arg | ||
| } | ||
| Conversion::Str | Conversion::Repr | Conversion::Ascii => { | ||
| // Can't be a conversion otherwise. | ||
| if !call.arguments.keywords.is_empty() { | ||
| continue; | ||
| } | ||
|
|
||
| // Avoid attempting to rewrite, e.g., `f"{str({})}"`; the curly braces are problematic. | ||
| if matches!( | ||
| arg, | ||
| Expr::Dict(_) | Expr::Set(_) | Expr::DictComp(_) | Expr::SetComp(_) | ||
| ) { | ||
| continue; | ||
| } | ||
| // Can't be a conversion otherwise. | ||
| let [arg] = call.arguments.args.as_ref() else { | ||
| continue; | ||
| }; | ||
| arg | ||
| } | ||
| }; | ||
|
|
||
| if !checker | ||
| .semantic() | ||
| .resolve_builtin_symbol(func) | ||
| .is_some_and(|builtin| matches!(builtin, "str" | "repr" | "ascii")) | ||
| { | ||
| continue; | ||
| // Suppress lint for starred expressions. | ||
| if matches!(arg, Expr::Starred(_)) { | ||
| return; | ||
| } | ||
|
|
||
| let mut diagnostic = | ||
| checker.report_diagnostic(ExplicitFStringTypeConversion, expression.range()); | ||
| diagnostic.try_set_fix(|| { | ||
| convert_call_to_conversion_flag(f_string, index, checker.locator(), checker.stylist()) | ||
| convert_call_to_conversion_flag(checker, conversion, element, call, arg) | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /// Generate a [`Fix`] to replace an explicit type conversion with a conversion flag. | ||
| fn convert_call_to_conversion_flag( | ||
| f_string: &ast::FString, | ||
| index: usize, | ||
| locator: &Locator, | ||
| stylist: &Stylist, | ||
| checker: &Checker, | ||
| conversion: Conversion, | ||
| element: &ast::InterpolatedStringElement, | ||
| call: &ast::ExprCall, | ||
| arg: &Expr, | ||
| ) -> Result<Fix> { | ||
| let source_code = locator.slice(f_string); | ||
| transform_expression(source_code, stylist, |mut expression| { | ||
| let formatted_string = match_formatted_string(&mut expression)?; | ||
| // Replace the formatted call expression at `index` with a conversion flag. | ||
| let formatted_string_expression = | ||
| match_formatted_string_expression(&mut formatted_string.parts[index])?; | ||
| let call = match_call_mut(&mut formatted_string_expression.expression)?; | ||
| let name = match_name(&call.func)?; | ||
| match name.value { | ||
| "str" => { | ||
| formatted_string_expression.conversion = Some("s"); | ||
| } | ||
| "repr" => { | ||
| formatted_string_expression.conversion = Some("r"); | ||
| } | ||
| "ascii" => { | ||
| formatted_string_expression.conversion = Some("a"); | ||
| } | ||
| _ => bail!("Unexpected function call: `{:?}`", name.value), | ||
| } | ||
| formatted_string_expression.expression = call.args[0].value.clone(); | ||
| Ok(expression) | ||
| }) | ||
| .map(|output| Fix::safe_edit(Edit::range_replacement(output, f_string.range()))) | ||
| if element | ||
MichaReiser marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| .as_interpolation() | ||
| .is_some_and(|interpolation| interpolation.debug_text.is_some()) | ||
| { | ||
| anyhow::bail!("Don't support fixing f-string with debug text!"); | ||
| } | ||
|
|
||
| let arg_str = checker.locator().slice(arg); | ||
| let contains_curly_brace = checker | ||
| .tokens() | ||
| .in_range(arg.range()) | ||
|
||
| .iter() | ||
| .any(|token| token.kind() == TokenKind::Lbrace); | ||
|
|
||
| let output = if contains_curly_brace { | ||
| format!(" {arg_str}!{conversion}") | ||
| } else if matches!(arg, Expr::Lambda(_) | Expr::Named(_)) { | ||
| format!("({arg_str})!{conversion}") | ||
| } else { | ||
| format!("{arg_str}!{conversion}") | ||
| }; | ||
|
|
||
| let replace_range = if let Some(range) = parenthesized_range( | ||
| call.into(), | ||
| element.into(), | ||
| checker.comment_ranges(), | ||
| checker.source(), | ||
| ) { | ||
| range | ||
| } else { | ||
| call.range() | ||
| }; | ||
|
|
||
| Ok(Fix::safe_edit(Edit::range_replacement( | ||
| output, | ||
| replace_range, | ||
| ))) | ||
| } | ||
|
|
||
| /// Represents the three built-in Python conversion functions that can be replaced | ||
| /// with f-string conversion flags. | ||
| #[derive(Copy, Clone)] | ||
| enum Conversion { | ||
| Ascii, | ||
| Str, | ||
| Repr, | ||
| } | ||
|
|
||
| impl Conversion { | ||
| fn from_str(value: &str) -> Option<Self> { | ||
| Some(match value { | ||
| "ascii" => Self::Ascii, | ||
| "str" => Self::Str, | ||
| "repr" => Self::Repr, | ||
| _ => return None, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| impl Display for Conversion { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| let value = match self { | ||
| Conversion::Ascii => "a", | ||
| Conversion::Str => "s", | ||
| Conversion::Repr => "r", | ||
| }; | ||
| write!(f, "{value}") | ||
| } | ||
| } | ||
This file contains hidden or 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.
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.
Uh oh!
There was an error while loading. Please reload this page.