Skip to content

Commit

Permalink
Update Stylist quote detection with new f-string token (#7328)
Browse files Browse the repository at this point in the history
## Summary

This PR updates `Stylist` quote detection to include the f-string
tokens.

As f-strings cannot be used as docstrings, we'll skip the check for
triple-quoted f-strings.

## Test Plan

Add new test cases with f-strings.

fixes: #7293
  • Loading branch information
dhruvmanila committed Sep 29, 2023
1 parent 846948f commit 658435e
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions crates/ruff_python_codegen/src/stylist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ fn detect_quote(tokens: &[LexResult], locator: &Locator) -> Quote {
triple_quoted: false,
..
} => Some(*range),
// No need to check if it's triple-quoted as f-strings cannot be used
// as docstrings.
Tok::FStringStart => Some(*range),
_ => None,
});

Expand Down Expand Up @@ -275,6 +278,14 @@ class FormFeedIndent:
Quote::Single
);

let contents = r#"x = f'1'"#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
assert_eq!(
Stylist::from_tokens(&tokens, &locator).quote(),
Quote::Single
);

let contents = r#"x = "1""#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
Expand All @@ -283,6 +294,14 @@ class FormFeedIndent:
Quote::Double
);

let contents = r#"x = f"1""#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
assert_eq!(
Stylist::from_tokens(&tokens, &locator).quote(),
Quote::Double
);

let contents = r#"s = "It's done.""#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
Expand Down Expand Up @@ -328,6 +347,41 @@ a = "v"
Stylist::from_tokens(&tokens, &locator).quote(),
Quote::Double
);

// Detect from f-string appearing after docstring
let contents = r#"
"""Module docstring."""
a = f'v'
"#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
assert_eq!(
Stylist::from_tokens(&tokens, &locator).quote(),
Quote::Single
);

let contents = r#"
'''Module docstring.'''
a = f"v"
"#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
assert_eq!(
Stylist::from_tokens(&tokens, &locator).quote(),
Quote::Double
);

let contents = r#"
f'''Module docstring.'''
"#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
assert_eq!(
Stylist::from_tokens(&tokens, &locator).quote(),
Quote::Single
);
}

#[test]
Expand Down

0 comments on commit 658435e

Please sign in to comment.