aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists')
-rw-r--r--crates/ra_assists/src/assists/add_derive.rs (renamed from crates/ra_assists/src/add_derive.rs)0
-rw-r--r--crates/ra_assists/src/assists/add_explicit_type.rs (renamed from crates/ra_assists/src/add_explicit_type.rs)0
-rw-r--r--crates/ra_assists/src/assists/add_impl.rs (renamed from crates/ra_assists/src/add_impl.rs)0
-rw-r--r--crates/ra_assists/src/assists/add_missing_impl_members.rs (renamed from crates/ra_assists/src/add_missing_impl_members.rs)5
-rw-r--r--crates/ra_assists/src/assists/auto_import.rs (renamed from crates/ra_assists/src/auto_import.rs)0
-rw-r--r--crates/ra_assists/src/assists/change_visibility.rs (renamed from crates/ra_assists/src/change_visibility.rs)0
-rw-r--r--crates/ra_assists/src/assists/fill_match_arms.rs (renamed from crates/ra_assists/src/fill_match_arms.rs)2
-rw-r--r--crates/ra_assists/src/assists/flip_binexpr.rs (renamed from crates/ra_assists/src/flip_binexpr.rs)0
-rw-r--r--crates/ra_assists/src/assists/flip_comma.rs (renamed from crates/ra_assists/src/flip_comma.rs)0
-rw-r--r--crates/ra_assists/src/assists/inline_local_variable.rs (renamed from crates/ra_assists/src/inline_local_variable.rs)0
-rw-r--r--crates/ra_assists/src/assists/introduce_variable.rs (renamed from crates/ra_assists/src/introduce_variable.rs)0
-rw-r--r--crates/ra_assists/src/assists/merge_match_arms.rs (renamed from crates/ra_assists/src/merge_match_arms.rs)0
-rw-r--r--crates/ra_assists/src/assists/move_bounds.rs (renamed from crates/ra_assists/src/move_bounds.rs)2
-rw-r--r--crates/ra_assists/src/assists/move_guard.rs (renamed from crates/ra_assists/src/move_guard.rs)0
-rw-r--r--crates/ra_assists/src/assists/raw_string.rs (renamed from crates/ra_assists/src/raw_string.rs)0
-rw-r--r--crates/ra_assists/src/assists/remove_dbg.rs (renamed from crates/ra_assists/src/remove_dbg.rs)0
-rw-r--r--crates/ra_assists/src/assists/replace_if_let_with_match.rs (renamed from crates/ra_assists/src/replace_if_let_with_match.rs)0
-rw-r--r--crates/ra_assists/src/assists/split_import.rs (renamed from crates/ra_assists/src/split_import.rs)0
-rw-r--r--crates/ra_assists/src/ast_builder.rs229
-rw-r--r--crates/ra_assists/src/ast_editor.rs231
-rw-r--r--crates/ra_assists/src/lib.rs101
21 files changed, 289 insertions, 281 deletions
diff --git a/crates/ra_assists/src/add_derive.rs b/crates/ra_assists/src/assists/add_derive.rs
index 9c88644df..9c88644df 100644
--- a/crates/ra_assists/src/add_derive.rs
+++ b/crates/ra_assists/src/assists/add_derive.rs
diff --git a/crates/ra_assists/src/add_explicit_type.rs b/crates/ra_assists/src/assists/add_explicit_type.rs
index 78f0f7f28..78f0f7f28 100644
--- a/crates/ra_assists/src/add_explicit_type.rs
+++ b/crates/ra_assists/src/assists/add_explicit_type.rs
diff --git a/crates/ra_assists/src/add_impl.rs b/crates/ra_assists/src/assists/add_impl.rs
index 4b61f4031..4b61f4031 100644
--- a/crates/ra_assists/src/add_impl.rs
+++ b/crates/ra_assists/src/assists/add_impl.rs
diff --git a/crates/ra_assists/src/add_missing_impl_members.rs b/crates/ra_assists/src/assists/add_missing_impl_members.rs
index cbeb7054f..2894bdd8a 100644
--- a/crates/ra_assists/src/add_missing_impl_members.rs
+++ b/crates/ra_assists/src/assists/add_missing_impl_members.rs
@@ -4,10 +4,7 @@ use ra_syntax::{
4 SmolStr, 4 SmolStr,
5}; 5};
6 6
7use crate::{ 7use crate::{ast_builder::AstBuilder, ast_editor::AstEditor, Assist, AssistCtx, AssistId};
8 ast_editor::{AstBuilder, AstEditor},
9 Assist, AssistCtx, AssistId,
10};
11 8
12#[derive(PartialEq)] 9#[derive(PartialEq)]
13enum AddMissingImplMembersMode { 10enum AddMissingImplMembersMode {
diff --git a/crates/ra_assists/src/auto_import.rs b/crates/ra_assists/src/assists/auto_import.rs
index 5aae98546..5aae98546 100644
--- a/crates/ra_assists/src/auto_import.rs
+++ b/crates/ra_assists/src/assists/auto_import.rs
diff --git a/crates/ra_assists/src/change_visibility.rs b/crates/ra_assists/src/assists/change_visibility.rs
index 60c74debc..60c74debc 100644
--- a/crates/ra_assists/src/change_visibility.rs
+++ b/crates/ra_assists/src/assists/change_visibility.rs
diff --git a/crates/ra_assists/src/fill_match_arms.rs b/crates/ra_assists/src/assists/fill_match_arms.rs
index f59062bb9..771aa625f 100644
--- a/crates/ra_assists/src/fill_match_arms.rs
+++ b/crates/ra_assists/src/assists/fill_match_arms.rs
@@ -3,7 +3,7 @@ use std::iter;
3use hir::{db::HirDatabase, Adt, HasSource}; 3use hir::{db::HirDatabase, Adt, HasSource};
4use ra_syntax::ast::{self, AstNode, NameOwner}; 4use ra_syntax::ast::{self, AstNode, NameOwner};
5 5
6use crate::{ast_editor::AstBuilder, Assist, AssistCtx, AssistId}; 6use crate::{ast_builder::AstBuilder, Assist, AssistCtx, AssistId};
7 7
8pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 8pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
9 let match_expr = ctx.node_at_offset::<ast::MatchExpr>()?; 9 let match_expr = ctx.node_at_offset::<ast::MatchExpr>()?;
diff --git a/crates/ra_assists/src/flip_binexpr.rs b/crates/ra_assists/src/assists/flip_binexpr.rs
index b55b36a8e..b55b36a8e 100644
--- a/crates/ra_assists/src/flip_binexpr.rs
+++ b/crates/ra_assists/src/assists/flip_binexpr.rs
diff --git a/crates/ra_assists/src/flip_comma.rs b/crates/ra_assists/src/assists/flip_comma.rs
index 5ee7561bc..5ee7561bc 100644
--- a/crates/ra_assists/src/flip_comma.rs
+++ b/crates/ra_assists/src/assists/flip_comma.rs
diff --git a/crates/ra_assists/src/inline_local_variable.rs b/crates/ra_assists/src/assists/inline_local_variable.rs
index eedb29199..eedb29199 100644
--- a/crates/ra_assists/src/inline_local_variable.rs
+++ b/crates/ra_assists/src/assists/inline_local_variable.rs
diff --git a/crates/ra_assists/src/introduce_variable.rs b/crates/ra_assists/src/assists/introduce_variable.rs
index 470ffe120..470ffe120 100644
--- a/crates/ra_assists/src/introduce_variable.rs
+++ b/crates/ra_assists/src/assists/introduce_variable.rs
diff --git a/crates/ra_assists/src/merge_match_arms.rs b/crates/ra_assists/src/assists/merge_match_arms.rs
index 3b6a99895..3b6a99895 100644
--- a/crates/ra_assists/src/merge_match_arms.rs
+++ b/crates/ra_assists/src/assists/merge_match_arms.rs
diff --git a/crates/ra_assists/src/move_bounds.rs b/crates/ra_assists/src/assists/move_bounds.rs
index 526de1d98..aa9036fed 100644
--- a/crates/ra_assists/src/move_bounds.rs
+++ b/crates/ra_assists/src/assists/move_bounds.rs
@@ -6,7 +6,7 @@ use ra_syntax::{
6 TextRange, 6 TextRange,
7}; 7};
8 8
9use crate::{ast_editor::AstBuilder, Assist, AssistCtx, AssistId}; 9use crate::{ast_builder::AstBuilder, Assist, AssistCtx, AssistId};
10 10
11pub(crate) fn move_bounds_to_where_clause(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 11pub(crate) fn move_bounds_to_where_clause(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
12 let type_param_list = ctx.node_at_offset::<ast::TypeParamList>()?; 12 let type_param_list = ctx.node_at_offset::<ast::TypeParamList>()?;
diff --git a/crates/ra_assists/src/move_guard.rs b/crates/ra_assists/src/assists/move_guard.rs
index 699221e33..699221e33 100644
--- a/crates/ra_assists/src/move_guard.rs
+++ b/crates/ra_assists/src/assists/move_guard.rs
diff --git a/crates/ra_assists/src/raw_string.rs b/crates/ra_assists/src/assists/raw_string.rs
index 965a64c98..965a64c98 100644
--- a/crates/ra_assists/src/raw_string.rs
+++ b/crates/ra_assists/src/assists/raw_string.rs
diff --git a/crates/ra_assists/src/remove_dbg.rs b/crates/ra_assists/src/assists/remove_dbg.rs
index 870133fda..870133fda 100644
--- a/crates/ra_assists/src/remove_dbg.rs
+++ b/crates/ra_assists/src/assists/remove_dbg.rs
diff --git a/crates/ra_assists/src/replace_if_let_with_match.rs b/crates/ra_assists/src/assists/replace_if_let_with_match.rs
index 401835c57..401835c57 100644
--- a/crates/ra_assists/src/replace_if_let_with_match.rs
+++ b/crates/ra_assists/src/assists/replace_if_let_with_match.rs
diff --git a/crates/ra_assists/src/split_import.rs b/crates/ra_assists/src/assists/split_import.rs
index 2c1edddb9..2c1edddb9 100644
--- a/crates/ra_assists/src/split_import.rs
+++ b/crates/ra_assists/src/assists/split_import.rs
diff --git a/crates/ra_assists/src/ast_builder.rs b/crates/ra_assists/src/ast_builder.rs
new file mode 100644
index 000000000..e4ea1fca9
--- /dev/null
+++ b/crates/ra_assists/src/ast_builder.rs
@@ -0,0 +1,229 @@
1use itertools::Itertools;
2
3use hir::Name;
4use ra_syntax::{ast, AstNode, SourceFile};
5
6pub struct AstBuilder<N: AstNode> {
7 _phantom: std::marker::PhantomData<N>,
8}
9
10impl AstBuilder<ast::RecordField> {
11 pub fn from_name(name: &Name) -> ast::RecordField {
12 ast_node_from_file_text(&format!("fn f() {{ S {{ {}: (), }} }}", name))
13 }
14
15 fn from_text(text: &str) -> ast::RecordField {
16 ast_node_from_file_text(&format!("fn f() {{ S {{ {}, }} }}", text))
17 }
18
19 pub fn from_pieces(name: &ast::NameRef, expr: Option<&ast::Expr>) -> ast::RecordField {
20 match expr {
21 Some(expr) => Self::from_text(&format!("{}: {}", name.syntax(), expr.syntax())),
22 None => Self::from_text(&name.syntax().to_string()),
23 }
24 }
25}
26
27impl AstBuilder<ast::Block> {
28 fn from_text(text: &str) -> ast::Block {
29 ast_node_from_file_text(&format!("fn f() {}", text))
30 }
31
32 pub fn single_expr(e: &ast::Expr) -> ast::Block {
33 Self::from_text(&format!("{{ {} }}", e.syntax()))
34 }
35}
36
37impl AstBuilder<ast::Expr> {
38 fn from_text(text: &str) -> ast::Expr {
39 ast_node_from_file_text(&format!("const C: () = {};", text))
40 }
41
42 pub fn unit() -> ast::Expr {
43 Self::from_text("()")
44 }
45
46 pub fn unimplemented() -> ast::Expr {
47 Self::from_text("unimplemented!()")
48 }
49}
50
51impl AstBuilder<ast::NameRef> {
52 pub fn new(text: &str) -> ast::NameRef {
53 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text))
54 }
55}
56
57impl AstBuilder<ast::Path> {
58 fn from_text(text: &str) -> ast::Path {
59 ast_node_from_file_text(text)
60 }
61
62 pub fn from_name(name: ast::Name) -> ast::Path {
63 let name = name.syntax().to_string();
64 Self::from_text(name.as_str())
65 }
66
67 pub fn from_pieces(enum_name: ast::Name, var_name: ast::Name) -> ast::Path {
68 Self::from_text(&format!("{}::{}", enum_name.syntax(), var_name.syntax()))
69 }
70}
71
72impl AstBuilder<ast::BindPat> {
73 fn from_text(text: &str) -> ast::BindPat {
74 ast_node_from_file_text(&format!("fn f({}: ())", text))
75 }
76
77 pub fn from_name(name: &ast::Name) -> ast::BindPat {
78 Self::from_text(name.text())
79 }
80}
81
82impl AstBuilder<ast::PlaceholderPat> {
83 fn from_text(text: &str) -> ast::PlaceholderPat {
84 ast_node_from_file_text(&format!("fn f({}: ())", text))
85 }
86
87 pub fn placeholder() -> ast::PlaceholderPat {
88 Self::from_text("_")
89 }
90}
91
92impl AstBuilder<ast::TupleStructPat> {
93 fn from_text(text: &str) -> ast::TupleStructPat {
94 ast_node_from_file_text(&format!("fn f({}: ())", text))
95 }
96
97 pub fn from_pieces(
98 path: &ast::Path,
99 pats: impl Iterator<Item = ast::Pat>,
100 ) -> ast::TupleStructPat {
101 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
102 Self::from_text(&format!("{}({})", path.syntax(), pats_str))
103 }
104}
105
106impl AstBuilder<ast::RecordPat> {
107 fn from_text(text: &str) -> ast::RecordPat {
108 ast_node_from_file_text(&format!("fn f({}: ())", text))
109 }
110
111 pub fn from_pieces(path: &ast::Path, pats: impl Iterator<Item = ast::Pat>) -> ast::RecordPat {
112 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
113 Self::from_text(&format!("{}{{ {} }}", path.syntax(), pats_str))
114 }
115}
116
117impl AstBuilder<ast::PathPat> {
118 fn from_text(text: &str) -> ast::PathPat {
119 ast_node_from_file_text(&format!("fn f({}: ())", text))
120 }
121
122 pub fn from_path(path: &ast::Path) -> ast::PathPat {
123 let path_str = path.syntax().text().to_string();
124 Self::from_text(path_str.as_str())
125 }
126}
127
128impl AstBuilder<ast::MatchArm> {
129 fn from_text(text: &str) -> ast::MatchArm {
130 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
131 }
132
133 pub fn from_pieces(pats: impl Iterator<Item = ast::Pat>, expr: &ast::Expr) -> ast::MatchArm {
134 let pats_str = pats.map(|p| p.syntax().to_string()).join(" | ");
135 Self::from_text(&format!("{} => {}", pats_str, expr.syntax()))
136 }
137}
138
139impl AstBuilder<ast::MatchArmList> {
140 fn from_text(text: &str) -> ast::MatchArmList {
141 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
142 }
143
144 pub fn from_arms(arms: impl Iterator<Item = ast::MatchArm>) -> ast::MatchArmList {
145 let arms_str = arms.map(|arm| format!("\n {}", arm.syntax())).join(",");
146 Self::from_text(&format!("{},\n", arms_str))
147 }
148}
149
150impl AstBuilder<ast::WherePred> {
151 fn from_text(text: &str) -> ast::WherePred {
152 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
153 }
154
155 pub fn from_pieces(
156 path: ast::Path,
157 bounds: impl Iterator<Item = ast::TypeBound>,
158 ) -> ast::WherePred {
159 let bounds = bounds.map(|b| b.syntax().to_string()).collect::<Vec<_>>().join(" + ");
160 Self::from_text(&format!("{}: {}", path.syntax(), bounds))
161 }
162}
163
164impl AstBuilder<ast::WhereClause> {
165 fn from_text(text: &str) -> ast::WhereClause {
166 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
167 }
168
169 pub fn from_predicates(preds: impl Iterator<Item = ast::WherePred>) -> ast::WhereClause {
170 let preds = preds.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
171 Self::from_text(preds.as_str())
172 }
173}
174
175fn ast_node_from_file_text<N: AstNode>(text: &str) -> N {
176 let parse = SourceFile::parse(text);
177 let res = parse.tree().syntax().descendants().find_map(N::cast).unwrap();
178 res
179}
180
181pub(crate) mod tokens {
182 use once_cell::sync::Lazy;
183 use ra_syntax::{AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken, T};
184
185 static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| SourceFile::parse(",\n; ;"));
186
187 pub(crate) fn comma() -> SyntaxToken {
188 SOURCE_FILE
189 .tree()
190 .syntax()
191 .descendants_with_tokens()
192 .filter_map(|it| it.into_token())
193 .find(|it| it.kind() == T![,])
194 .unwrap()
195 }
196
197 pub(crate) fn single_space() -> SyntaxToken {
198 SOURCE_FILE
199 .tree()
200 .syntax()
201 .descendants_with_tokens()
202 .filter_map(|it| it.into_token())
203 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == " ")
204 .unwrap()
205 }
206
207 #[allow(unused)]
208 pub(crate) fn single_newline() -> SyntaxToken {
209 SOURCE_FILE
210 .tree()
211 .syntax()
212 .descendants_with_tokens()
213 .filter_map(|it| it.into_token())
214 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == "\n")
215 .unwrap()
216 }
217
218 pub(crate) struct WsBuilder(SourceFile);
219
220 impl WsBuilder {
221 pub(crate) fn new(text: &str) -> WsBuilder {
222 WsBuilder(SourceFile::parse(text).ok().unwrap())
223 }
224 pub(crate) fn ws(&self) -> SyntaxToken {
225 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
226 }
227 }
228
229}
diff --git a/crates/ra_assists/src/ast_editor.rs b/crates/ra_assists/src/ast_editor.rs
index a710edce8..81621afef 100644
--- a/crates/ra_assists/src/ast_editor.rs
+++ b/crates/ra_assists/src/ast_editor.rs
@@ -1,18 +1,18 @@
1use std::{iter, ops::RangeInclusive}; 1use std::{iter, ops::RangeInclusive};
2 2
3use arrayvec::ArrayVec; 3use arrayvec::ArrayVec;
4use itertools::Itertools;
5 4
6use hir::Name;
7use ra_fmt::leading_indent; 5use ra_fmt::leading_indent;
8use ra_syntax::{ 6use ra_syntax::{
9 algo::{insert_children, replace_children}, 7 algo::{insert_children, replace_children},
10 ast, AstNode, Direction, InsertPosition, SourceFile, SyntaxElement, 8 ast, AstNode, Direction, InsertPosition, SyntaxElement,
11 SyntaxKind::*, 9 SyntaxKind::*,
12 T, 10 T,
13}; 11};
14use ra_text_edit::TextEditBuilder; 12use ra_text_edit::TextEditBuilder;
15 13
14use crate::ast_builder::tokens;
15
16pub struct AstEditor<N: AstNode> { 16pub struct AstEditor<N: AstNode> {
17 original_ast: N, 17 original_ast: N,
18 ast: N, 18 ast: N,
@@ -240,228 +240,3 @@ impl AstEditor<ast::FnDef> {
240 self.ast = self.replace_children(replace_range, to_insert.into_iter()) 240 self.ast = self.replace_children(replace_range, to_insert.into_iter())
241 } 241 }
242} 242}
243
244pub struct AstBuilder<N: AstNode> {
245 _phantom: std::marker::PhantomData<N>,
246}
247
248impl AstBuilder<ast::RecordField> {
249 pub fn from_name(name: &Name) -> ast::RecordField {
250 ast_node_from_file_text(&format!("fn f() {{ S {{ {}: (), }} }}", name))
251 }
252
253 fn from_text(text: &str) -> ast::RecordField {
254 ast_node_from_file_text(&format!("fn f() {{ S {{ {}, }} }}", text))
255 }
256
257 pub fn from_pieces(name: &ast::NameRef, expr: Option<&ast::Expr>) -> ast::RecordField {
258 match expr {
259 Some(expr) => Self::from_text(&format!("{}: {}", name.syntax(), expr.syntax())),
260 None => Self::from_text(&name.syntax().to_string()),
261 }
262 }
263}
264
265impl AstBuilder<ast::Block> {
266 fn from_text(text: &str) -> ast::Block {
267 ast_node_from_file_text(&format!("fn f() {}", text))
268 }
269
270 pub fn single_expr(e: &ast::Expr) -> ast::Block {
271 Self::from_text(&format!("{{ {} }}", e.syntax()))
272 }
273}
274
275impl AstBuilder<ast::Expr> {
276 fn from_text(text: &str) -> ast::Expr {
277 ast_node_from_file_text(&format!("const C: () = {};", text))
278 }
279
280 pub fn unit() -> ast::Expr {
281 Self::from_text("()")
282 }
283
284 pub fn unimplemented() -> ast::Expr {
285 Self::from_text("unimplemented!()")
286 }
287}
288
289impl AstBuilder<ast::NameRef> {
290 pub fn new(text: &str) -> ast::NameRef {
291 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text))
292 }
293}
294
295impl AstBuilder<ast::Path> {
296 fn from_text(text: &str) -> ast::Path {
297 ast_node_from_file_text(text)
298 }
299
300 pub fn from_name(name: ast::Name) -> ast::Path {
301 let name = name.syntax().to_string();
302 Self::from_text(name.as_str())
303 }
304
305 pub fn from_pieces(enum_name: ast::Name, var_name: ast::Name) -> ast::Path {
306 Self::from_text(&format!("{}::{}", enum_name.syntax(), var_name.syntax()))
307 }
308}
309
310impl AstBuilder<ast::BindPat> {
311 fn from_text(text: &str) -> ast::BindPat {
312 ast_node_from_file_text(&format!("fn f({}: ())", text))
313 }
314
315 pub fn from_name(name: &ast::Name) -> ast::BindPat {
316 Self::from_text(name.text())
317 }
318}
319
320impl AstBuilder<ast::PlaceholderPat> {
321 fn from_text(text: &str) -> ast::PlaceholderPat {
322 ast_node_from_file_text(&format!("fn f({}: ())", text))
323 }
324
325 pub fn placeholder() -> ast::PlaceholderPat {
326 Self::from_text("_")
327 }
328}
329
330impl AstBuilder<ast::TupleStructPat> {
331 fn from_text(text: &str) -> ast::TupleStructPat {
332 ast_node_from_file_text(&format!("fn f({}: ())", text))
333 }
334
335 pub fn from_pieces(
336 path: &ast::Path,
337 pats: impl Iterator<Item = ast::Pat>,
338 ) -> ast::TupleStructPat {
339 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
340 Self::from_text(&format!("{}({})", path.syntax(), pats_str))
341 }
342}
343
344impl AstBuilder<ast::RecordPat> {
345 fn from_text(text: &str) -> ast::RecordPat {
346 ast_node_from_file_text(&format!("fn f({}: ())", text))
347 }
348
349 pub fn from_pieces(path: &ast::Path, pats: impl Iterator<Item = ast::Pat>) -> ast::RecordPat {
350 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
351 Self::from_text(&format!("{}{{ {} }}", path.syntax(), pats_str))
352 }
353}
354
355impl AstBuilder<ast::PathPat> {
356 fn from_text(text: &str) -> ast::PathPat {
357 ast_node_from_file_text(&format!("fn f({}: ())", text))
358 }
359
360 pub fn from_path(path: &ast::Path) -> ast::PathPat {
361 let path_str = path.syntax().text().to_string();
362 Self::from_text(path_str.as_str())
363 }
364}
365
366impl AstBuilder<ast::MatchArm> {
367 fn from_text(text: &str) -> ast::MatchArm {
368 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
369 }
370
371 pub fn from_pieces(pats: impl Iterator<Item = ast::Pat>, expr: &ast::Expr) -> ast::MatchArm {
372 let pats_str = pats.map(|p| p.syntax().to_string()).join(" | ");
373 Self::from_text(&format!("{} => {}", pats_str, expr.syntax()))
374 }
375}
376
377impl AstBuilder<ast::MatchArmList> {
378 fn from_text(text: &str) -> ast::MatchArmList {
379 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
380 }
381
382 pub fn from_arms(arms: impl Iterator<Item = ast::MatchArm>) -> ast::MatchArmList {
383 let arms_str = arms.map(|arm| format!("\n {}", arm.syntax())).join(",");
384 Self::from_text(&format!("{},\n", arms_str))
385 }
386}
387
388impl AstBuilder<ast::WherePred> {
389 fn from_text(text: &str) -> ast::WherePred {
390 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
391 }
392
393 pub fn from_pieces(
394 path: ast::Path,
395 bounds: impl Iterator<Item = ast::TypeBound>,
396 ) -> ast::WherePred {
397 let bounds = bounds.map(|b| b.syntax().to_string()).collect::<Vec<_>>().join(" + ");
398 Self::from_text(&format!("{}: {}", path.syntax(), bounds))
399 }
400}
401
402impl AstBuilder<ast::WhereClause> {
403 fn from_text(text: &str) -> ast::WhereClause {
404 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
405 }
406
407 pub fn from_predicates(preds: impl Iterator<Item = ast::WherePred>) -> ast::WhereClause {
408 let preds = preds.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
409 Self::from_text(preds.as_str())
410 }
411}
412
413fn ast_node_from_file_text<N: AstNode>(text: &str) -> N {
414 let parse = SourceFile::parse(text);
415 let res = parse.tree().syntax().descendants().find_map(N::cast).unwrap();
416 res
417}
418
419mod tokens {
420 use once_cell::sync::Lazy;
421 use ra_syntax::{AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken, T};
422
423 static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| SourceFile::parse(",\n; ;"));
424
425 pub(crate) fn comma() -> SyntaxToken {
426 SOURCE_FILE
427 .tree()
428 .syntax()
429 .descendants_with_tokens()
430 .filter_map(|it| it.into_token())
431 .find(|it| it.kind() == T![,])
432 .unwrap()
433 }
434
435 pub(crate) fn single_space() -> SyntaxToken {
436 SOURCE_FILE
437 .tree()
438 .syntax()
439 .descendants_with_tokens()
440 .filter_map(|it| it.into_token())
441 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == " ")
442 .unwrap()
443 }
444
445 #[allow(unused)]
446 pub(crate) fn single_newline() -> SyntaxToken {
447 SOURCE_FILE
448 .tree()
449 .syntax()
450 .descendants_with_tokens()
451 .filter_map(|it| it.into_token())
452 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == "\n")
453 .unwrap()
454 }
455
456 pub(crate) struct WsBuilder(SourceFile);
457
458 impl WsBuilder {
459 pub(crate) fn new(text: &str) -> WsBuilder {
460 WsBuilder(SourceFile::parse(text).ok().unwrap())
461 }
462 pub(crate) fn ws(&self) -> SyntaxToken {
463 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
464 }
465 }
466
467}
diff --git a/crates/ra_assists/src/lib.rs b/crates/ra_assists/src/lib.rs
index 756acf415..71b017076 100644
--- a/crates/ra_assists/src/lib.rs
+++ b/crates/ra_assists/src/lib.rs
@@ -8,6 +8,7 @@
8mod assist_ctx; 8mod assist_ctx;
9mod marks; 9mod marks;
10pub mod ast_editor; 10pub mod ast_editor;
11pub mod ast_builder;
11 12
12use itertools::Itertools; 13use itertools::Itertools;
13 14
@@ -17,6 +18,7 @@ use ra_syntax::{TextRange, TextUnit};
17use ra_text_edit::TextEdit; 18use ra_text_edit::TextEdit;
18 19
19pub(crate) use crate::assist_ctx::{Assist, AssistCtx}; 20pub(crate) use crate::assist_ctx::{Assist, AssistCtx};
21pub use crate::assists::auto_import::auto_import_text_edit;
20 22
21/// Unique identifier of the assist, should not be shown to the user 23/// Unique identifier of the assist, should not be shown to the user
22/// directly. 24/// directly.
@@ -46,7 +48,7 @@ where
46 H: HirDatabase + 'static, 48 H: HirDatabase + 'static,
47{ 49{
48 AssistCtx::with_ctx(db, range, false, |ctx| { 50 AssistCtx::with_ctx(db, range, false, |ctx| {
49 all_assists() 51 assists::all()
50 .iter() 52 .iter()
51 .filter_map(|f| f(ctx.clone())) 53 .filter_map(|f| f(ctx.clone()))
52 .map(|a| match a { 54 .map(|a| match a {
@@ -68,7 +70,7 @@ where
68 use std::cmp::Ordering; 70 use std::cmp::Ordering;
69 71
70 AssistCtx::with_ctx(db, range, true, |ctx| { 72 AssistCtx::with_ctx(db, range, true, |ctx| {
71 let mut a = all_assists() 73 let mut a = assists::all()
72 .iter() 74 .iter()
73 .filter_map(|f| f(ctx.clone())) 75 .filter_map(|f| f(ctx.clone()))
74 .map(|a| match a { 76 .map(|a| match a {
@@ -86,51 +88,56 @@ where
86 }) 88 })
87} 89}
88 90
89mod add_derive; 91mod assists {
90mod add_explicit_type; 92 use crate::{Assist, AssistCtx};
91mod add_impl; 93 use hir::db::HirDatabase;
92mod flip_comma; 94
93mod flip_binexpr; 95 mod add_derive;
94mod change_visibility; 96 mod add_explicit_type;
95mod fill_match_arms; 97 mod add_impl;
96mod merge_match_arms; 98 mod flip_comma;
97mod introduce_variable; 99 mod flip_binexpr;
98mod inline_local_variable; 100 mod change_visibility;
99mod raw_string; 101 mod fill_match_arms;
100mod replace_if_let_with_match; 102 mod merge_match_arms;
101mod split_import; 103 mod introduce_variable;
102mod remove_dbg; 104 mod inline_local_variable;
103pub mod auto_import; 105 mod raw_string;
104mod add_missing_impl_members; 106 mod replace_if_let_with_match;
105mod move_guard; 107 mod split_import;
106mod move_bounds; 108 mod remove_dbg;
107 109 pub(crate) mod auto_import;
108fn all_assists<DB: HirDatabase>() -> &'static [fn(AssistCtx<DB>) -> Option<Assist>] { 110 mod add_missing_impl_members;
109 &[ 111 mod move_guard;
110 add_derive::add_derive, 112 mod move_bounds;
111 add_explicit_type::add_explicit_type, 113
112 add_impl::add_impl, 114 pub(crate) fn all<DB: HirDatabase>() -> &'static [fn(AssistCtx<DB>) -> Option<Assist>] {
113 change_visibility::change_visibility, 115 &[
114 fill_match_arms::fill_match_arms, 116 add_derive::add_derive,
115 merge_match_arms::merge_match_arms, 117 add_explicit_type::add_explicit_type,
116 flip_comma::flip_comma, 118 add_impl::add_impl,
117 flip_binexpr::flip_binexpr, 119 change_visibility::change_visibility,
118 introduce_variable::introduce_variable, 120 fill_match_arms::fill_match_arms,
119 replace_if_let_with_match::replace_if_let_with_match, 121 merge_match_arms::merge_match_arms,
120 split_import::split_import, 122 flip_comma::flip_comma,
121 remove_dbg::remove_dbg, 123 flip_binexpr::flip_binexpr,
122 auto_import::auto_import, 124 introduce_variable::introduce_variable,
123 add_missing_impl_members::add_missing_impl_members, 125 replace_if_let_with_match::replace_if_let_with_match,
124 add_missing_impl_members::add_missing_default_members, 126 split_import::split_import,
125 inline_local_variable::inline_local_varialbe, 127 remove_dbg::remove_dbg,
126 move_guard::move_guard_to_arm_body, 128 auto_import::auto_import,
127 move_guard::move_arm_cond_to_match_guard, 129 add_missing_impl_members::add_missing_impl_members,
128 move_bounds::move_bounds_to_where_clause, 130 add_missing_impl_members::add_missing_default_members,
129 raw_string::add_hash, 131 inline_local_variable::inline_local_varialbe,
130 raw_string::make_raw_string, 132 move_guard::move_guard_to_arm_body,
131 raw_string::make_usual_string, 133 move_guard::move_arm_cond_to_match_guard,
132 raw_string::remove_hash, 134 move_bounds::move_bounds_to_where_clause,
133 ] 135 raw_string::add_hash,
136 raw_string::make_raw_string,
137 raw_string::make_usual_string,
138 raw_string::remove_hash,
139 ]
140 }
134} 141}
135 142
136#[cfg(test)] 143#[cfg(test)]