Skip to content

Reduce allocations in "Expand macro" formatter #8421

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 1 commit into from
Apr 8, 2021
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
43 changes: 30 additions & 13 deletions crates/ide/src/expand_macro.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::iter;

use hir::Semantics;
use ide_db::RootDatabase;
use syntax::{
Expand Down Expand Up @@ -91,27 +93,42 @@ fn insert_whitespaces(syn: SyntaxNode) -> String {
let is_last =
|f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };

res += &match token.kind() {
k if is_text(k) && is_next(|it| !it.is_punct(), true) => token.text().to_string() + " ",
match token.kind() {
k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
res.push_str(token.text());
res.push(' ');
}
L_CURLY if is_next(|it| it != R_CURLY, true) => {
indent += 1;
let leading_space = if is_last(is_text, false) { " " } else { "" };
format!("{}{{\n{}", leading_space, " ".repeat(indent))
if is_last(is_text, false) {
res.push(' ');
}
res.push_str("{\n");
res.extend(iter::repeat(" ").take(2 * indent));
Copy link
Member Author

Choose a reason for hiding this comment

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

Not sure why we indent these at two and not four spaces.

Copy link
Member

Choose a reason for hiding this comment

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

Because normally it will display in another pane, shorter should be better. But Im okay to change it to match rustfmt default.

}
R_CURLY if is_last(|it| it != L_CURLY, true) => {
indent = indent.saturating_sub(1);
format!("\n{}}}", " ".repeat(indent))
res.push('\n');
res.extend(iter::repeat(" ").take(2 * indent));
res.push_str("}");
}
R_CURLY => {
res.push_str("}\n");
res.extend(iter::repeat(" ").take(2 * indent));
}
R_CURLY => format!("}}\n{}", " ".repeat(indent)),
LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
format!("{} ", token.text().to_string())
res.push_str(token.text());
res.push(' ');
}
T![;] => format!(";\n{}", " ".repeat(indent)),
T![->] => " -> ".to_string(),
T![=] => " = ".to_string(),
T![=>] => " => ".to_string(),
_ => token.text().to_string(),
};
T![;] => {
res.push_str(";\n");
res.extend(iter::repeat(" ").take(2 * indent));
}
T![->] => res.push_str(" -> "),
T![=] => res.push_str(" = "),
T![=>] => res.push_str(" => "),
_ => res.push_str(token.text()),
}

last = Some(token.kind());
}
Expand Down