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

Use char index rather than position for indent slice #11645

Merged
merged 1 commit into from
May 31, 2024
Merged
Changes from all 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
22 changes: 21 additions & 1 deletion crates/ruff_python_codegen/src/stylist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,13 @@ fn detect_indention(tokens: &[LexResult], locator: &Locator) -> Indentation {
}
TokenKind::NonLogicalNewline => {
let line = locator.line(range.end());
let indent_index = line.chars().position(|c| !c.is_whitespace());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you could do line.find(|c| !c.is_whitespace())

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow TIL.

let indent_index = line.char_indices().find_map(|(i, c)| {
if c.is_whitespace() {
None
} else {
Some(i)
}
});
if let Some(indent_index) = indent_index {
if indent_index > 0 {
let whitespace = &line[..indent_index];
Expand Down Expand Up @@ -223,6 +229,20 @@ x = (
&Indentation(" ".to_string())
);

let contents = r"
x = (
 1,
 2,
 3,
)
";
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
assert_eq!(
Stylist::from_tokens(&tokens, &locator).indentation(),
&Indentation(" ".to_string())
);

// formfeed indent, see `detect_indention` comment.
let contents = r"
class FormFeedIndent:
Expand Down
Loading