aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_assists/src/assists/add_missing_impl_members.rs5
-rw-r--r--crates/ra_assists/src/assists/fill_match_arms.rs2
-rw-r--r--crates/ra_assists/src/assists/move_bounds.rs2
-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.rs1
-rw-r--r--crates/ra_ide_api/src/diagnostics.rs2
7 files changed, 237 insertions, 235 deletions
diff --git a/crates/ra_assists/src/assists/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/assists/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/assists/fill_match_arms.rs b/crates/ra_assists/src/assists/fill_match_arms.rs
index f59062bb9..771aa625f 100644
--- a/crates/ra_assists/src/assists/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/assists/move_bounds.rs b/crates/ra_assists/src/assists/move_bounds.rs
index 526de1d98..aa9036fed 100644
--- a/crates/ra_assists/src/assists/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/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 5e4e8bc92..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
diff --git a/crates/ra_ide_api/src/diagnostics.rs b/crates/ra_ide_api/src/diagnostics.rs
index 93e1e7c2d..30b95a215 100644
--- a/crates/ra_ide_api/src/diagnostics.rs
+++ b/crates/ra_ide_api/src/diagnostics.rs
@@ -2,7 +2,7 @@ use std::cell::RefCell;
2 2
3use hir::diagnostics::{AstDiagnostic, Diagnostic as _, DiagnosticSink}; 3use hir::diagnostics::{AstDiagnostic, Diagnostic as _, DiagnosticSink};
4use itertools::Itertools; 4use itertools::Itertools;
5use ra_assists::ast_editor::{AstBuilder, AstEditor}; 5use ra_assists::{ast_builder::AstBuilder, ast_editor::AstEditor};
6use ra_db::SourceDatabase; 6use ra_db::SourceDatabase;
7use ra_prof::profile; 7use ra_prof::profile;
8use ra_syntax::{ 8use ra_syntax::{