Skip to content
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

FStringPart for f-string formatting #6365

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ def func(address):
# Error
"0.0.0.0"
'0.0.0.0'
f"0.0.0.0"


# Error
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
with open("/tmp/abc", "w") as f:
f.write("def")

with open(f"/tmp/abc", "w") as f:
f.write("def")

with open("/var/tmp/123", "w") as f:
f.write("def")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def f8(x: bytes = b"50 character byte stringgggggggggggggggggggggggggg\xff") ->

foo: str = "50 character stringggggggggggggggggggggggggggggggg"
bar: str = "51 character stringgggggggggggggggggggggggggggggggg"
baz: str = f"51 character stringgggggggggggggggggggggggggggggggg"

baz: bytes = b"50 character byte stringgggggggggggggggggggggggggg"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ baz: bytes = b"50 character byte stringgggggggggggggggggggggggggg" # OK

qux: bytes = b"51 character byte stringggggggggggggggggggggggggggg\xff" # Error: PYI053

ffoo: str = f"50 character stringggggggggggggggggggggggggggggggg" # OK

fbar: str = f"51 character stringgggggggggggggggggggggggggggggggg" # Error: PYI053

class Demo:
"""Docstrings are excluded from this rule. Some padding.""" # OK

Expand Down
62 changes: 48 additions & 14 deletions crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use ruff_python_literal::cformat::{CFormatError, CFormatErrorType};

use ruff_diagnostics::Diagnostic;

use ruff_python_ast::node::AstNode;
use ruff_python_ast::types::Node;
use ruff_python_semantic::analyze::typing;
use ruff_python_semantic::ScopeKind;
Expand Down Expand Up @@ -957,15 +958,41 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
pylint::rules::await_outside_async(checker, expr);
}
}
Expr::FString(ast::ExprFString { values, .. }) => {
Expr::FString(ast::ExprFString { elements, .. }) => {
if checker.enabled(Rule::FStringMissingPlaceholders) {
pyflakes::rules::f_string_missing_placeholders(expr, values, checker);
pyflakes::rules::f_string_missing_placeholders(expr, elements, checker);
}
if checker.enabled(Rule::HardcodedSQLExpression) {
flake8_bandit::rules::hardcoded_sql_expression(checker, expr);
}
if checker.enabled(Rule::ExplicitFStringTypeConversion) {
ruff::rules::explicit_f_string_type_conversion(checker, expr, values);
ruff::rules::explicit_f_string_type_conversion(checker, expr, elements);
}
for element in elements {
if let ast::FStringElement::Literal(
literal_element @ ast::FStringLiteralElement { value, range },
) = element
{
if checker.enabled(Rule::HardcodedBindAllInterfaces) {
if let Some(diagnostic) =
flake8_bandit::rules::hardcoded_bind_all_interfaces(value, *range)
dhruvmanila marked this conversation as resolved.
Show resolved Hide resolved
{
checker.diagnostics.push(diagnostic);
}
}
if checker.enabled(Rule::HardcodedTempFile) {
flake8_bandit::rules::hardcoded_tmp_directory(checker, *range, value);
}

if checker.source_type.is_stub() {
if checker.enabled(Rule::StringOrBytesTooLong) {
flake8_pyi::rules::string_or_bytes_too_long(
checker,
literal_element.as_any_node_ref(),
);
}
}
}
}
}
Expr::BinOp(ast::ExprBinOp {
Expand Down Expand Up @@ -1226,18 +1253,22 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
flake8_pyi::rules::numeric_literal_too_long(checker, expr);
}
}
Expr::Constant(ast::ExprConstant {
value: Constant::Bytes(_),
range: _,
}) => {
Expr::Constant(
constant @ ast::ExprConstant {
value: Constant::Bytes(_),
range: _,
},
) => {
if checker.source_type.is_stub() && checker.enabled(Rule::StringOrBytesTooLong) {
flake8_pyi::rules::string_or_bytes_too_long(checker, expr);
flake8_pyi::rules::string_or_bytes_too_long(checker, constant.as_any_node_ref());
}
}
Expr::Constant(ast::ExprConstant {
value: Constant::Str(value),
range: _,
}) => {
Expr::Constant(
constant @ ast::ExprConstant {
value: Constant::Str(value),
range: _,
},
) => {
if checker.enabled(Rule::HardcodedBindAllInterfaces) {
if let Some(diagnostic) =
flake8_bandit::rules::hardcoded_bind_all_interfaces(value, expr.range())
Expand All @@ -1246,14 +1277,17 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
}
}
if checker.enabled(Rule::HardcodedTempFile) {
flake8_bandit::rules::hardcoded_tmp_directory(checker, expr, value);
flake8_bandit::rules::hardcoded_tmp_directory(checker, expr.range(), value);
}
if checker.enabled(Rule::UnicodeKindPrefix) {
pyupgrade::rules::unicode_kind_prefix(checker, expr, value.unicode);
}
if checker.source_type.is_stub() {
if checker.enabled(Rule::StringOrBytesTooLong) {
flake8_pyi::rules::string_or_bytes_too_long(checker, expr);
flake8_pyi::rules::string_or_bytes_too_long(
checker,
constant.as_any_node_ref(),
);
}
}
}
Expand Down
11 changes: 0 additions & 11 deletions crates/ruff_linter/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1278,17 +1278,6 @@ where
self.semantic.flags = flags_snapshot;
}

fn visit_format_spec(&mut self, format_spec: &'b Expr) {
match format_spec {
Expr::FString(ast::ExprFString { values, .. }) => {
for value in values {
self.visit_expr(value);
}
}
_ => unreachable!("Unexpected expression for format_spec"),
}
}

fn visit_parameters(&mut self, parameters: &'b Parameters) {
// Step 1: Binding.
// Bind, but intentionally avoid walking default expressions, as we handle them
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::TextRange;

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;

Expand Down Expand Up @@ -52,7 +52,7 @@ impl Violation for HardcodedTempFile {
}

/// S108
pub(crate) fn hardcoded_tmp_directory(checker: &mut Checker, expr: &Expr, value: &str) {
pub(crate) fn hardcoded_tmp_directory(checker: &mut Checker, range: TextRange, value: &str) {
if !checker
.settings
.flake8_bandit
Expand All @@ -79,6 +79,6 @@ pub(crate) fn hardcoded_tmp_directory(checker: &mut Checker, expr: &Expr, value:
HardcodedTempFile {
string: value.to_string(),
},
expr.range(),
range,
));
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ S104.py:9:1: S104 Possible binding to all interfaces
9 | "0.0.0.0"
| ^^^^^^^^^ S104
10 | '0.0.0.0'
11 | f"0.0.0.0"
|

S104.py:10:1: S104 Possible binding to all interfaces
Expand All @@ -15,21 +16,30 @@ S104.py:10:1: S104 Possible binding to all interfaces
9 | "0.0.0.0"
10 | '0.0.0.0'
| ^^^^^^^^^ S104
11 | f"0.0.0.0"
|

S104.py:14:6: S104 Possible binding to all interfaces
S104.py:11:3: S104 Possible binding to all interfaces
|
13 | # Error
14 | func("0.0.0.0")
9 | "0.0.0.0"
10 | '0.0.0.0'
11 | f"0.0.0.0"
| ^^^^^^^ S104
|

S104.py:15:6: S104 Possible binding to all interfaces
dhruvmanila marked this conversation as resolved.
Show resolved Hide resolved
|
14 | # Error
15 | func("0.0.0.0")
| ^^^^^^^^^ S104
|

S104.py:18:9: S104 Possible binding to all interfaces
S104.py:19:9: S104 Possible binding to all interfaces
|
17 | def my_func():
18 | x = "0.0.0.0"
18 | def my_func():
19 | x = "0.0.0.0"
| ^^^^^^^^^ S104
19 | print(x)
20 | print(x)
|


Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,31 @@ S108.py:5:11: S108 Probable insecure usage of temporary file or directory: "/tmp
6 | f.write("def")
|

S108.py:8:11: S108 Probable insecure usage of temporary file or directory: "/var/tmp/123"
S108.py:8:13: S108 Probable insecure usage of temporary file or directory: "/tmp/abc"
|
6 | f.write("def")
7 |
8 | with open("/var/tmp/123", "w") as f:
| ^^^^^^^^^^^^^^ S108
8 | with open(f"/tmp/abc", "w") as f:
| ^^^^^^^^ S108
9 | f.write("def")
|

S108.py:11:11: S108 Probable insecure usage of temporary file or directory: "/dev/shm/unit/test"
S108.py:11:11: S108 Probable insecure usage of temporary file or directory: "/var/tmp/123"
|
9 | f.write("def")
10 |
11 | with open("/dev/shm/unit/test", "w") as f:
| ^^^^^^^^^^^^^^^^^^^^ S108
11 | with open("/var/tmp/123", "w") as f:
| ^^^^^^^^^^^^^^ S108
12 | f.write("def")
|

S108.py:14:11: S108 Probable insecure usage of temporary file or directory: "/dev/shm/unit/test"
|
12 | f.write("def")
13 |
14 | with open("/dev/shm/unit/test", "w") as f:
| ^^^^^^^^^^^^^^^^^^^^ S108
15 | f.write("def")
|


Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,39 @@ S108.py:5:11: S108 Probable insecure usage of temporary file or directory: "/tmp
6 | f.write("def")
|

S108.py:8:11: S108 Probable insecure usage of temporary file or directory: "/var/tmp/123"
S108.py:8:13: S108 Probable insecure usage of temporary file or directory: "/tmp/abc"
|
6 | f.write("def")
7 |
8 | with open("/var/tmp/123", "w") as f:
| ^^^^^^^^^^^^^^ S108
8 | with open(f"/tmp/abc", "w") as f:
| ^^^^^^^^ S108
9 | f.write("def")
|

S108.py:11:11: S108 Probable insecure usage of temporary file or directory: "/dev/shm/unit/test"
S108.py:11:11: S108 Probable insecure usage of temporary file or directory: "/var/tmp/123"
|
9 | f.write("def")
10 |
11 | with open("/dev/shm/unit/test", "w") as f:
| ^^^^^^^^^^^^^^^^^^^^ S108
11 | with open("/var/tmp/123", "w") as f:
| ^^^^^^^^^^^^^^ S108
12 | f.write("def")
|

S108.py:14:11: S108 Probable insecure usage of temporary file or directory: "/dev/shm/unit/test"
|
12 | f.write("def")
13 |
14 | with open("/dev/shm/unit/test", "w") as f:
| ^^^^^^^^^^^^^^^^^^^^ S108
15 | f.write("def")
|

S108.py:15:11: S108 Probable insecure usage of temporary file or directory: "/foo/bar"
S108.py:18:11: S108 Probable insecure usage of temporary file or directory: "/foo/bar"
|
14 | # not ok by config
15 | with open("/foo/bar", "w") as f:
17 | # not ok by config
18 | with open("/foo/bar", "w") as f:
| ^^^^^^^^^^ S108
16 | f.write("def")
19 | f.write("def")
|


Original file line number Diff line number Diff line change
Expand Up @@ -1076,7 +1076,7 @@ pub(crate) fn fix_unnecessary_map(
// If the expression is embedded in an f-string, surround it with spaces to avoid
// syntax errors.
if matches!(object_type, ObjectType::Set | ObjectType::Dict) {
if parent.is_some_and(Expr::is_formatted_value_expr) {
if parent.is_some_and(Expr::is_f_string_expr) {
content = format!(" {content} ");
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use ruff_python_ast::{self as ast, Constant, Expr};
use ruff_python_ast::{self as ast, Constant};

use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::is_docstring_stmt;
use ruff_python_ast::node::AnyNodeRef;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
Expand Down Expand Up @@ -42,32 +43,35 @@ impl AlwaysAutofixableViolation for StringOrBytesTooLong {
}

/// PYI053
pub(crate) fn string_or_bytes_too_long(checker: &mut Checker, expr: &Expr) {
pub(crate) fn string_or_bytes_too_long(checker: &mut Checker, node: AnyNodeRef) {
// Ignore docstrings.
if is_docstring_stmt(checker.semantic().current_statement()) {
return;
}

let length = match expr {
Expr::Constant(ast::ExprConstant {
let length = match node {
AnyNodeRef::ExprConstant(ast::ExprConstant {
value: Constant::Str(s),
..
}) => s.chars().count(),
Expr::Constant(ast::ExprConstant {
AnyNodeRef::ExprConstant(ast::ExprConstant {
value: Constant::Bytes(bytes),
..
}) => bytes.len(),
AnyNodeRef::FStringLiteralElement(ast::FStringLiteralElement { value, .. }) => {
value.chars().count()
}
_ => return,
};
if length <= 50 {
return;
}

let mut diagnostic = Diagnostic::new(StringOrBytesTooLong, expr.range());
let mut diagnostic = Diagnostic::new(StringOrBytesTooLong, node.range());
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
"...".to_string(),
expr.range(),
node.range(),
)));
}
checker.diagnostics.push(diagnostic);
Expand Down
Loading
Loading