Skip to content

Commit 771c6c9

Browse files
committed
format_collect
1 parent d37f4e0 commit 771c6c9

File tree

8 files changed

+54
-39
lines changed

8 files changed

+54
-39
lines changed

Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,6 @@ new_ret_no_self = "allow"
169169
borrowed_box = "allow"
170170
derived_hash_with_manual_eq = "allow"
171171
forget_non_drop = "allow"
172-
format_collect = "allow"
173172
needless_doctest_main = "allow"
174173
non_canonical_clone_impl = "allow"
175174
non_canonical_partial_ord_impl = "allow"

crates/hir-def/src/macro_expansion_tests/mod.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use hir_expand::{
2525
InFile, MacroFileId, MacroFileIdExt,
2626
};
2727
use span::Span;
28-
use stdx::format_to;
28+
use stdx::{format_to, format_to_acc};
2929
use syntax::{
3030
ast::{self, edit::IndentLevel},
3131
AstNode,
@@ -149,8 +149,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
149149
if tree {
150150
let tree = format!("{:#?}", parse.syntax_node())
151151
.split_inclusive('\n')
152-
.map(|line| format!("// {line}"))
153-
.collect::<String>();
152+
.fold(String::new(), |mut acc, line| format_to_acc!(acc, "// {line}"));
154153
format_to!(expn_text, "\n{}", tree)
155154
}
156155
let range = call.syntax().text_range();

crates/ide-assists/src/tests/sourcegen.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use std::{fmt, fs, path::Path};
44

5+
use stdx::format_to_acc;
56
use test_utils::project_root;
67

78
#[test]
@@ -172,8 +173,7 @@ impl fmt::Display for Assist {
172173
fn hide_hash_comments(text: &str) -> String {
173174
text.split('\n') // want final newline
174175
.filter(|&it| !(it.starts_with("# ") || it == "#"))
175-
.map(|it| format!("{it}\n"))
176-
.collect()
176+
.fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n"))
177177
}
178178

179179
fn reveal_hash_comments(text: &str) -> String {
@@ -187,6 +187,5 @@ fn reveal_hash_comments(text: &str) -> String {
187187
it
188188
}
189189
})
190-
.map(|it| format!("{it}\n"))
191-
.collect()
190+
.fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n"))
192191
}

crates/rust-analyzer/src/config.rs

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ use project_model::{
3232
};
3333
use rustc_hash::{FxHashMap, FxHashSet};
3434
use serde::{de::DeserializeOwned, Deserialize};
35+
use stdx::format_to_acc;
3536
use vfs::{AbsPath, AbsPathBuf};
3637

3738
use crate::{
@@ -2563,14 +2564,13 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json
25632564

25642565
#[cfg(test)]
25652566
fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
2566-
fields
2567-
.iter()
2568-
.map(|(field, _ty, doc, default)| {
2569-
let name = format!("rust-analyzer.{}", field.replace('_', "."));
2570-
let doc = doc_comment_to_string(doc);
2571-
if default.contains('\n') {
2572-
format!(
2573-
r#"[[{name}]]{name}::
2567+
fields.iter().fold(String::new(), |mut acc, (field, _ty, doc, default)| {
2568+
let name = format!("rust-analyzer.{}", field.replace('_', "."));
2569+
let doc = doc_comment_to_string(doc);
2570+
if default.contains('\n') {
2571+
format_to_acc!(
2572+
acc,
2573+
r#"[[{name}]]{name}::
25742574
+
25752575
--
25762576
Default:
@@ -2580,16 +2580,17 @@ Default:
25802580
{doc}
25812581
--
25822582
"#
2583-
)
2584-
} else {
2585-
format!("[[{name}]]{name} (default: `{default}`)::\n+\n--\n{doc}--\n")
2586-
}
2587-
})
2588-
.collect::<String>()
2583+
)
2584+
} else {
2585+
format_to_acc!(acc, "[[{name}]]{name} (default: `{default}`)::\n+\n--\n{doc}--\n")
2586+
}
2587+
})
25892588
}
25902589

25912590
fn doc_comment_to_string(doc: &[&str]) -> String {
2592-
doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{it}\n")).collect()
2591+
doc.iter()
2592+
.map(|it| it.strip_prefix(' ').unwrap_or(it))
2593+
.fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n"))
25932594
}
25942595

25952596
#[cfg(test)]

crates/rust-analyzer/tests/slow-tests/main.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ use lsp_types::{
3131
};
3232
use rust_analyzer::lsp::ext::{OnEnter, Runnables, RunnablesParams};
3333
use serde_json::json;
34+
use stdx::format_to_acc;
3435
use test_utils::skip_slow_tests;
3536

3637
use crate::{
@@ -591,8 +592,10 @@ fn diagnostics_dont_block_typing() {
591592
return;
592593
}
593594

594-
let librs: String = (0..10).map(|i| format!("mod m{i};")).collect();
595-
let libs: String = (0..10).map(|i| format!("//- /src/m{i}.rs\nfn foo() {{}}\n\n")).collect();
595+
let librs: String = (0..10).fold(String::new(), |mut acc, i| format_to_acc!(acc, "mod m{i};"));
596+
let libs: String = (0..10).fold(String::new(), |mut acc, i| {
597+
format_to_acc!(acc, "//- /src/m{i}.rs\nfn foo() {{}}\n\n")
598+
});
596599
let server = Project::with_fixture(&format!(
597600
r#"
598601
//- /Cargo.toml

crates/stdx/src/macros.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,22 @@ macro_rules! format_to {
2424
};
2525
}
2626

27+
/// Appends formatted string to a `String` and returns the `String`.
28+
///
29+
/// Useful for folding iterators into a `String`.
30+
#[macro_export]
31+
macro_rules! format_to_acc {
32+
($buf:expr, $lit:literal $($arg:tt)*) => {
33+
{
34+
use ::std::fmt::Write as _;
35+
// We can't do ::std::fmt::Write::write_fmt($buf, format_args!($lit $($arg)*))
36+
// unfortunately, as that loses out on autoref behavior.
37+
_ = $buf.write_fmt(format_args!($lit $($arg)*));
38+
$buf
39+
}
40+
};
41+
}
42+
2743
/// Generates `From` impls for `Enum E { Foo(Foo), Bar(Bar) }` enums
2844
///
2945
/// # Example

crates/syntax/src/ast/make.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@
99
//! API should require to assemble every node piecewise. The trick of
1010
//! `parse(format!())` we use internally is an implementation detail -- long
1111
//! term, it will be replaced with direct tree manipulation.
12+
1213
use itertools::Itertools;
1314
use parser::T;
1415
use rowan::NodeOrToken;
15-
use stdx::{format_to, never};
16+
use stdx::{format_to, format_to_acc, never};
1617

1718
use crate::{ast, utils::is_raw_identifier, AstNode, SourceFile, SyntaxKind, SyntaxToken};
1819

@@ -759,15 +760,12 @@ pub fn match_arm_with_guard(
759760
}
760761

761762
pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
762-
let arms_str = arms
763-
.into_iter()
764-
.map(|arm| {
765-
let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
766-
let comma = if needs_comma { "," } else { "" };
767-
let arm = arm.syntax();
768-
format!(" {arm}{comma}\n")
769-
})
770-
.collect::<String>();
763+
let arms_str = arms.into_iter().fold(String::new(), |mut acc, arm| {
764+
let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
765+
let comma = if needs_comma { "," } else { "" };
766+
let arm = arm.syntax();
767+
format_to_acc!(acc, " {arm}{comma}\n")
768+
});
771769
return from_text(&arms_str);
772770

773771
fn from_text(text: &str) -> ast::MatchArmList {

crates/syntax/src/tests.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use std::{
1111
use ast::HasName;
1212
use expect_test::expect_file;
1313
use rayon::prelude::*;
14+
use stdx::format_to_acc;
1415
use test_utils::{bench, bench_fixture, project_root};
1516

1617
use crate::{ast, fuzz, AstNode, SourceFile, SyntaxError};
@@ -104,10 +105,9 @@ fn self_hosting_parsing() {
104105
.collect::<Vec<_>>();
105106

106107
if !errors.is_empty() {
107-
let errors = errors
108-
.into_iter()
109-
.map(|(path, err)| format!("{}: {:?}\n", path.display(), err[0]))
110-
.collect::<String>();
108+
let errors = errors.into_iter().fold(String::new(), |mut acc, (path, err)| {
109+
format_to_acc!(acc, "{}: {:?}\n", path.display(), err[0])
110+
});
111111
panic!("Parsing errors:\n{errors}\n");
112112
}
113113
}

0 commit comments

Comments
 (0)