Skip to content

Commit b764c38

Browse files
committed
Start stdx
This crate will hold everything to small to be worth publishing
1 parent a1fea0d commit b764c38

File tree

13 files changed

+163
-104
lines changed

13 files changed

+163
-104
lines changed

Cargo.lock

Lines changed: 6 additions & 16 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/ra_assists/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ authors = ["rust-analyzer developers"]
88
doctest = false
99

1010
[dependencies]
11-
format-buf = "1.0.0"
12-
join_to_string = "0.1.3"
1311
rustc-hash = "1.1.0"
1412
itertools = "0.9.0"
1513
either = "1.5.3"
1614

15+
stdx = { path = "../stdx" }
16+
1717
ra_syntax = { path = "../ra_syntax" }
1818
ra_text_edit = { path = "../ra_text_edit" }
1919
ra_fmt = { path = "../ra_fmt" }

crates/ra_assists/src/handlers/add_custom_impl.rs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
1-
//! FIXME: write short doc here
2-
3-
use join_to_string::join;
41
use ra_syntax::{
52
ast::{self, AstNode},
63
Direction, SmolStr,
74
SyntaxKind::{IDENT, WHITESPACE},
85
TextRange, TextUnit,
96
};
7+
use stdx::SepBy;
108

119
use crate::{Assist, AssistCtx, AssistId};
1210

13-
const DERIVE_TRAIT: &str = "derive";
14-
1511
// Assist: add_custom_impl
1612
//
1713
// Adds impl block for derived trait.
@@ -38,7 +34,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option<Assist> {
3834
.descendants_with_tokens()
3935
.filter(|t| t.kind() == IDENT)
4036
.find_map(|i| i.into_token())
41-
.filter(|t| *t.text() == DERIVE_TRAIT)?
37+
.filter(|t| *t.text() == "derive")?
4238
.text()
4339
.clone();
4440

@@ -63,8 +59,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option<Assist> {
6359
.filter(|t| t != trait_token.text())
6460
.collect::<Vec<SmolStr>>();
6561
let has_more_derives = !new_attr_input.is_empty();
66-
let new_attr_input =
67-
join(new_attr_input.iter()).separator(", ").surround_with("(", ")").to_string();
62+
let new_attr_input = new_attr_input.iter().sep_by(", ").surround_with("(", ")").to_string();
6863
let new_attr_input_len = new_attr_input.len();
6964

7065
let mut buf = String::new();
@@ -100,9 +95,10 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option<Assist> {
10095

10196
#[cfg(test)]
10297
mod tests {
103-
use super::*;
10498
use crate::helpers::{check_assist, check_assist_not_applicable};
10599

100+
use super::*;
101+
106102
#[test]
107103
fn add_custom_impl_for_unique_input() {
108104
check_assist(

crates/ra_assists/src/handlers/add_impl.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
use format_buf::format;
2-
use join_to_string::join;
31
use ra_syntax::{
42
ast::{self, AstNode, NameOwner, TypeParamsOwner},
53
TextUnit,
64
};
5+
use stdx::{format_to, SepBy};
76

87
use crate::{Assist, AssistCtx, AssistId};
98

@@ -36,7 +35,7 @@ pub(crate) fn add_impl(ctx: AssistCtx) -> Option<Assist> {
3635
let mut buf = String::new();
3736
buf.push_str("\n\nimpl");
3837
if let Some(type_params) = &type_params {
39-
format!(buf, "{}", type_params.syntax());
38+
format_to!(buf, "{}", type_params.syntax());
4039
}
4140
buf.push_str(" ");
4241
buf.push_str(name.text().as_str());
@@ -47,7 +46,9 @@ pub(crate) fn add_impl(ctx: AssistCtx) -> Option<Assist> {
4746
.map(|it| it.text().clone());
4847
let type_params =
4948
type_params.type_params().filter_map(|it| it.name()).map(|it| it.text().clone());
50-
join(lifetime_params.chain(type_params)).surround_with("<", ">").to_buf(&mut buf);
49+
50+
let generic_params = lifetime_params.chain(type_params).sep_by(", ");
51+
format_to!(buf, "<{}>", generic_params)
5152
}
5253
buf.push_str(" {\n");
5354
edit.set_cursor(start_offset + TextUnit::of_str(&buf));

crates/ra_assists/src/handlers/add_new.rs

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
use std::fmt::Write;
2-
3-
use format_buf::format;
41
use hir::Adt;
5-
use join_to_string::join;
62
use ra_syntax::{
73
ast::{
84
self, AstNode, NameOwner, StructKind, TypeAscriptionOwner, TypeParamsOwner, VisibilityOwner,
95
},
106
TextUnit, T,
117
};
8+
use stdx::{format_to, SepBy};
129

1310
use crate::{Assist, AssistCtx, AssistId};
1411

@@ -53,24 +50,22 @@ pub(crate) fn add_new(ctx: AssistCtx) -> Option<Assist> {
5350
buf.push('\n');
5451
}
5552

56-
let vis = strukt.visibility().map(|v| format!("{} ", v.syntax()));
53+
let vis = strukt.visibility().map(|v| format!("{} ", v));
5754
let vis = vis.as_deref().unwrap_or("");
58-
write!(&mut buf, " {}fn new(", vis).unwrap();
59-
60-
join(field_list.fields().filter_map(|f| {
61-
Some(format!("{}: {}", f.name()?.syntax().text(), f.ascribed_type()?.syntax().text()))
62-
}))
63-
.separator(", ")
64-
.to_buf(&mut buf);
6555

66-
buf.push_str(") -> Self { Self {");
67-
68-
join(field_list.fields().filter_map(|f| Some(f.name()?.syntax().text())))
69-
.separator(", ")
70-
.surround_with(" ", " ")
71-
.to_buf(&mut buf);
56+
let params = field_list
57+
.fields()
58+
.filter_map(|f| {
59+
Some(format!(
60+
"{}: {}",
61+
f.name()?.syntax().text(),
62+
f.ascribed_type()?.syntax().text()
63+
))
64+
})
65+
.sep_by(", ");
66+
let fields = field_list.fields().filter_map(|f| f.name()).sep_by(", ");
7267

73-
buf.push_str("} }");
68+
format_to!(buf, " {}fn new({}) -> Self {{ Self {{ {} }} }}", vis, params, fields);
7469

7570
let (start_offset, end_offset) = impl_def
7671
.and_then(|impl_def| {
@@ -103,7 +98,7 @@ fn generate_impl_text(strukt: &ast::StructDef, code: &str) -> String {
10398
let mut buf = String::with_capacity(code.len());
10499
buf.push_str("\n\nimpl");
105100
if let Some(type_params) = &type_params {
106-
format!(buf, "{}", type_params.syntax());
101+
format_to!(buf, "{}", type_params.syntax());
107102
}
108103
buf.push_str(" ");
109104
buf.push_str(strukt.name().unwrap().text().as_str());
@@ -114,10 +109,10 @@ fn generate_impl_text(strukt: &ast::StructDef, code: &str) -> String {
114109
.map(|it| it.text().clone());
115110
let type_params =
116111
type_params.type_params().filter_map(|it| it.name()).map(|it| it.text().clone());
117-
join(lifetime_params.chain(type_params)).surround_with("<", ">").to_buf(&mut buf);
112+
format_to!(buf, "<{}>", lifetime_params.chain(type_params).sep_by(", "))
118113
}
119114

120-
format!(&mut buf, " {{\n{}\n}}\n", code);
115+
format_to!(buf, " {{\n{}\n}}\n", code);
121116

122117
buf
123118
}

crates/ra_assists/src/handlers/introduce_variable.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use format_buf::format;
21
use ra_syntax::{
32
ast::{self, AstNode},
43
SyntaxKind::{
@@ -7,6 +6,7 @@ use ra_syntax::{
76
},
87
SyntaxNode, TextUnit,
98
};
9+
use stdx::format_to;
1010
use test_utils::tested_by;
1111

1212
use crate::{Assist, AssistCtx, AssistId};
@@ -52,7 +52,7 @@ pub(crate) fn introduce_variable(ctx: AssistCtx) -> Option<Assist> {
5252
buf.push_str("let var_name = ");
5353
TextUnit::of_str("let ")
5454
};
55-
format!(buf, "{}", expr.syntax());
55+
format_to!(buf, "{}", expr.syntax());
5656
let full_stmt = ast::ExprStmt::cast(anchor_stmt.clone());
5757
let is_full_stmt = if let Some(expr_stmt) = &full_stmt {
5858
Some(expr.syntax().clone()) == expr_stmt.expr().map(|e| e.syntax().clone())

crates/ra_ide/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@ wasm = []
1212

1313
[dependencies]
1414
either = "1.5.3"
15-
format-buf = "1.0.0"
1615
indexmap = "1.3.2"
1716
itertools = "0.9.0"
18-
join_to_string = "0.1.3"
1917
log = "0.4.8"
2018
rustc-hash = "1.1.0"
2119
rand = { version = "0.7.3", features = ["small_rng"] }
2220

21+
stdx = { path = "../stdx" }
22+
2323
ra_syntax = { path = "../ra_syntax" }
2424
ra_text_edit = { path = "../ra_text_edit" }
2525
ra_db = { path = "../ra_db" }

crates/ra_ide/src/completion/presentation.rs

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
//! This modules takes care of rendering various definitions as completion items.
22
33
use hir::{Docs, HasAttrs, HasSource, HirDisplay, ScopeDef, StructKind, Type};
4-
use join_to_string::join;
54
use ra_syntax::ast::NameOwner;
5+
use stdx::SepBy;
66
use test_utils::tested_by;
77

8-
use crate::completion::{
9-
CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions,
10-
};
11-
128
use crate::{
9+
completion::{
10+
CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions,
11+
},
1312
display::{const_label, macro_label, type_label, FunctionSignature},
1413
RootDatabase,
1514
};
@@ -221,13 +220,13 @@ impl Completions {
221220
builder = builder.trigger_call_info();
222221
let snippet = if ctx.options.add_call_argument_snippets {
223222
let to_skip = if has_self_param { 1 } else { 0 };
224-
let function_params_snippet = join(
225-
function_signature.parameter_names.iter().skip(to_skip).enumerate().map(
226-
|(index, param_name)| format!("${{{}:{}}}", index + 1, param_name),
227-
),
228-
)
229-
.separator(", ")
230-
.to_string();
223+
let function_params_snippet = function_signature
224+
.parameter_names
225+
.iter()
226+
.skip(to_skip)
227+
.enumerate()
228+
.map(|(index, param_name)| format!("${{{}:{}}}", index + 1, param_name))
229+
.sep_by(", ");
231230
format!("{}({})$0", name, function_params_snippet)
232231
} else {
233232
format!("{}($0)", name)
@@ -281,18 +280,16 @@ impl Completions {
281280
.into_iter()
282281
.map(|field| (field.name(ctx.db), field.signature_ty(ctx.db)));
283282
let detail = match variant.kind(ctx.db) {
284-
StructKind::Tuple | StructKind::Unit => {
285-
join(detail_types.map(|(_, t)| t.display(ctx.db).to_string()))
286-
.separator(", ")
287-
.surround_with("(", ")")
288-
.to_string()
289-
}
290-
StructKind::Record => {
291-
join(detail_types.map(|(n, t)| format!("{}: {}", n, t.display(ctx.db).to_string())))
292-
.separator(", ")
293-
.surround_with("{ ", " }")
294-
.to_string()
295-
}
283+
StructKind::Tuple | StructKind::Unit => detail_types
284+
.map(|(_, t)| t.display(ctx.db).to_string())
285+
.sep_by(", ")
286+
.surround_with("(", ")")
287+
.to_string(),
288+
StructKind::Record => detail_types
289+
.map(|(n, t)| format!("{}: {}", n, t.display(ctx.db).to_string()))
290+
.sep_by(", ")
291+
.surround_with("{ ", " }")
292+
.to_string(),
296293
};
297294
CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string())
298295
.kind(CompletionItemKind::EnumVariant)

crates/ra_ide/src/diagnostics.rs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,8 @@ fn check_struct_shorthand_initialization(
200200
#[cfg(test)]
201201
mod tests {
202202
use insta::assert_debug_snapshot;
203-
use join_to_string::join;
204203
use ra_syntax::SourceFile;
204+
use stdx::SepBy;
205205
use test_utils::assert_eq_text;
206206

207207
use crate::mock_analysis::{analysis_and_position, single_file};
@@ -254,16 +254,12 @@ mod tests {
254254
.map(|it| it.len() - it.trim_start().len())
255255
.next()
256256
.expect("empty fixture");
257-
let after = join(after.lines().filter_map(|line| {
258-
if line.len() > margin {
259-
Some(&line[margin..])
260-
} else {
261-
None
262-
}
263-
}))
264-
.separator("\n")
265-
.suffix("\n")
266-
.to_string();
257+
let after = after
258+
.lines()
259+
.filter_map(|line| if line.len() > margin { Some(&line[margin..]) } else { None })
260+
.sep_by("\n")
261+
.suffix("\n")
262+
.to_string();
267263

268264
assert_eq_text!(&after, &actual);
269265
assert!(

0 commit comments

Comments
 (0)