aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-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)9
-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)25
-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)9
-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.rs218
-rw-r--r--crates/ra_assists/src/ast_editor.rs231
-rw-r--r--crates/ra_assists/src/lib.rs101
-rw-r--r--crates/ra_ide_api/src/completion/complete_scope.rs4
-rw-r--r--crates/ra_ide_api/src/diagnostics.rs10
23 files changed, 301 insertions, 306 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..22d20909d 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::Make, 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 {
@@ -105,9 +102,7 @@ fn strip_docstring(item: ast::ImplItem) -> ast::ImplItem {
105fn add_body(fn_def: ast::FnDef) -> ast::FnDef { 102fn add_body(fn_def: ast::FnDef) -> ast::FnDef {
106 let mut ast_editor = AstEditor::new(fn_def.clone()); 103 let mut ast_editor = AstEditor::new(fn_def.clone());
107 if fn_def.body().is_none() { 104 if fn_def.body().is_none() {
108 ast_editor.set_body(&AstBuilder::<ast::Block>::single_expr( 105 ast_editor.set_body(&Make::<ast::Block>::single_expr(Make::<ast::Expr>::unimplemented()));
109 &AstBuilder::<ast::Expr>::unimplemented(),
110 ));
111 } 106 }
112 ast_editor.ast().to_owned() 107 ast_editor.ast().to_owned()
113} 108}
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..817433526 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::Make, 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>()?;
@@ -29,13 +29,10 @@ pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
29 29
30 ctx.add_action(AssistId("fill_match_arms"), "fill match arms", |edit| { 30 ctx.add_action(AssistId("fill_match_arms"), "fill match arms", |edit| {
31 let variants = variant_list.variants(); 31 let variants = variant_list.variants();
32 let arms = variants.filter_map(build_pat).map(|pat| { 32 let arms = variants
33 AstBuilder::<ast::MatchArm>::from_pieces( 33 .filter_map(build_pat)
34 iter::once(pat), 34 .map(|pat| Make::<ast::MatchArm>::from(iter::once(pat), Make::<ast::Expr>::unit()));
35 &AstBuilder::<ast::Expr>::unit(), 35 let new_arm_list = Make::<ast::MatchArmList>::from_arms(arms);
36 )
37 });
38 let new_arm_list = AstBuilder::<ast::MatchArmList>::from_arms(arms);
39 36
40 edit.target(match_expr.syntax().text_range()); 37 edit.target(match_expr.syntax().text_range());
41 edit.set_cursor(expr.syntax().text_range().start()); 38 edit.set_cursor(expr.syntax().text_range().start());
@@ -66,21 +63,21 @@ fn resolve_enum_def(
66} 63}
67 64
68fn build_pat(var: ast::EnumVariant) -> Option<ast::Pat> { 65fn build_pat(var: ast::EnumVariant) -> Option<ast::Pat> {
69 let path = &AstBuilder::<ast::Path>::from_pieces(var.parent_enum().name()?, var.name()?); 66 let path = Make::<ast::Path>::from(var.parent_enum().name()?, var.name()?);
70 67
71 let pat: ast::Pat = match var.kind() { 68 let pat: ast::Pat = match var.kind() {
72 ast::StructKind::Tuple(field_list) => { 69 ast::StructKind::Tuple(field_list) => {
73 let pats = iter::repeat(AstBuilder::<ast::PlaceholderPat>::placeholder().into()) 70 let pats = iter::repeat(Make::<ast::PlaceholderPat>::placeholder().into())
74 .take(field_list.fields().count()); 71 .take(field_list.fields().count());
75 AstBuilder::<ast::TupleStructPat>::from_pieces(path, pats).into() 72 Make::<ast::TupleStructPat>::from(path, pats).into()
76 } 73 }
77 ast::StructKind::Named(field_list) => { 74 ast::StructKind::Named(field_list) => {
78 let pats = field_list 75 let pats = field_list
79 .fields() 76 .fields()
80 .map(|f| AstBuilder::<ast::BindPat>::from_name(&f.name().unwrap()).into()); 77 .map(|f| Make::<ast::BindPat>::from_name(f.name().unwrap()).into());
81 AstBuilder::<ast::RecordPat>::from_pieces(path, pats).into() 78 Make::<ast::RecordPat>::from(path, pats).into()
82 } 79 }
83 ast::StructKind::Unit => AstBuilder::<ast::PathPat>::from_path(path).into(), 80 ast::StructKind::Unit => Make::<ast::PathPat>::from_path(path).into(),
84 }; 81 };
85 82
86 Some(pat) 83 Some(pat)
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..6fd2fb72b 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::Make, 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>()?;
@@ -52,7 +52,7 @@ pub(crate) fn move_bounds_to_where_clause(mut ctx: AssistCtx<impl HirDatabase>)
52 } 52 }
53 53
54 let predicates = type_params.iter().filter_map(build_predicate); 54 let predicates = type_params.iter().filter_map(build_predicate);
55 let where_clause = AstBuilder::<ast::WhereClause>::from_predicates(predicates); 55 let where_clause = Make::<ast::WhereClause>::from_predicates(predicates);
56 56
57 let to_insert = match anchor.prev_sibling_or_token() { 57 let to_insert = match anchor.prev_sibling_or_token() {
58 Some(ref elem) if elem.kind() == WHITESPACE => { 58 Some(ref elem) if elem.kind() == WHITESPACE => {
@@ -69,9 +69,8 @@ pub(crate) fn move_bounds_to_where_clause(mut ctx: AssistCtx<impl HirDatabase>)
69} 69}
70 70
71fn build_predicate(param: &ast::TypeParam) -> Option<ast::WherePred> { 71fn build_predicate(param: &ast::TypeParam) -> Option<ast::WherePred> {
72 let path = AstBuilder::<ast::Path>::from_name(param.name()?); 72 let path = Make::<ast::Path>::from_name(param.name()?);
73 let predicate = 73 let predicate = Make::<ast::WherePred>::from(path, param.type_bound_list()?.bounds());
74 AstBuilder::<ast::WherePred>::from_pieces(path, param.type_bound_list()?.bounds());
75 Some(predicate) 74 Some(predicate)
76} 75}
77 76
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..9a62b96b3
--- /dev/null
+++ b/crates/ra_assists/src/ast_builder.rs
@@ -0,0 +1,218 @@
1use itertools::Itertools;
2
3use ra_syntax::{ast, AstNode, SourceFile};
4
5pub struct Make<N: AstNode> {
6 _phantom: std::marker::PhantomData<N>,
7}
8
9impl Make<ast::RecordField> {
10 pub fn from(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordField {
11 match expr {
12 Some(expr) => Self::from_text(&format!("{}: {}", name.syntax(), expr.syntax())),
13 None => Self::from_text(&name.syntax().to_string()),
14 }
15 }
16
17 fn from_text(text: &str) -> ast::RecordField {
18 ast_node_from_file_text(&format!("fn f() {{ S {{ {}, }} }}", text))
19 }
20}
21
22impl Make<ast::Block> {
23 pub fn single_expr(e: ast::Expr) -> ast::Block {
24 Self::from_text(&format!("{{ {} }}", e.syntax()))
25 }
26
27 fn from_text(text: &str) -> ast::Block {
28 ast_node_from_file_text(&format!("fn f() {}", text))
29 }
30}
31
32impl Make<ast::Expr> {
33 pub fn unit() -> ast::Expr {
34 Self::from_text("()")
35 }
36
37 pub fn unimplemented() -> ast::Expr {
38 Self::from_text("unimplemented!()")
39 }
40
41 fn from_text(text: &str) -> ast::Expr {
42 ast_node_from_file_text(&format!("const C: () = {};", text))
43 }
44}
45
46impl Make<ast::NameRef> {
47 pub fn from(text: &str) -> ast::NameRef {
48 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text))
49 }
50}
51
52impl Make<ast::Path> {
53 pub fn from_name(name: ast::Name) -> ast::Path {
54 let name = name.syntax().to_string();
55 Self::from_text(name.as_str())
56 }
57
58 pub fn from(enum_name: ast::Name, var_name: ast::Name) -> ast::Path {
59 Self::from_text(&format!("{}::{}", enum_name.syntax(), var_name.syntax()))
60 }
61
62 fn from_text(text: &str) -> ast::Path {
63 ast_node_from_file_text(text)
64 }
65}
66
67impl Make<ast::BindPat> {
68 pub fn from_name(name: ast::Name) -> ast::BindPat {
69 Self::from_text(name.text())
70 }
71
72 fn from_text(text: &str) -> ast::BindPat {
73 ast_node_from_file_text(&format!("fn f({}: ())", text))
74 }
75}
76
77impl Make<ast::PlaceholderPat> {
78 pub fn placeholder() -> ast::PlaceholderPat {
79 Self::from_text("_")
80 }
81
82 fn from_text(text: &str) -> ast::PlaceholderPat {
83 ast_node_from_file_text(&format!("fn f({}: ())", text))
84 }
85}
86
87impl Make<ast::TupleStructPat> {
88 pub fn from(path: ast::Path, pats: impl Iterator<Item = ast::Pat>) -> ast::TupleStructPat {
89 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
90 Self::from_text(&format!("{}({})", path.syntax(), pats_str))
91 }
92
93 fn from_text(text: &str) -> ast::TupleStructPat {
94 ast_node_from_file_text(&format!("fn f({}: ())", text))
95 }
96}
97
98impl Make<ast::RecordPat> {
99 pub fn from(path: ast::Path, pats: impl Iterator<Item = ast::Pat>) -> ast::RecordPat {
100 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
101 Self::from_text(&format!("{}{{ {} }}", path.syntax(), pats_str))
102 }
103
104 fn from_text(text: &str) -> ast::RecordPat {
105 ast_node_from_file_text(&format!("fn f({}: ())", text))
106 }
107}
108
109impl Make<ast::PathPat> {
110 pub fn from_path(path: ast::Path) -> ast::PathPat {
111 let path_str = path.syntax().text().to_string();
112 Self::from_text(path_str.as_str())
113 }
114
115 fn from_text(text: &str) -> ast::PathPat {
116 ast_node_from_file_text(&format!("fn f({}: ())", text))
117 }
118}
119
120impl Make<ast::MatchArm> {
121 pub fn from(pats: impl Iterator<Item = ast::Pat>, expr: ast::Expr) -> ast::MatchArm {
122 let pats_str = pats.map(|p| p.syntax().to_string()).join(" | ");
123 Self::from_text(&format!("{} => {}", pats_str, expr.syntax()))
124 }
125
126 fn from_text(text: &str) -> ast::MatchArm {
127 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
128 }
129}
130
131impl Make<ast::MatchArmList> {
132 pub fn from_arms(arms: impl Iterator<Item = ast::MatchArm>) -> ast::MatchArmList {
133 let arms_str = arms.map(|arm| format!("\n {}", arm.syntax())).join(",");
134 Self::from_text(&format!("{},\n", arms_str))
135 }
136
137 fn from_text(text: &str) -> ast::MatchArmList {
138 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
139 }
140}
141
142impl Make<ast::WherePred> {
143 pub fn from(path: ast::Path, bounds: impl Iterator<Item = ast::TypeBound>) -> ast::WherePred {
144 let bounds = bounds.map(|b| b.syntax().to_string()).collect::<Vec<_>>().join(" + ");
145 Self::from_text(&format!("{}: {}", path.syntax(), bounds))
146 }
147
148 fn from_text(text: &str) -> ast::WherePred {
149 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
150 }
151}
152
153impl Make<ast::WhereClause> {
154 pub fn from_predicates(preds: impl Iterator<Item = ast::WherePred>) -> ast::WhereClause {
155 let preds = preds.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
156 Self::from_text(preds.as_str())
157 }
158
159 fn from_text(text: &str) -> ast::WhereClause {
160 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
161 }
162}
163
164fn ast_node_from_file_text<N: AstNode>(text: &str) -> N {
165 let parse = SourceFile::parse(text);
166 let res = parse.tree().syntax().descendants().find_map(N::cast).unwrap();
167 res
168}
169
170pub(crate) mod tokens {
171 use once_cell::sync::Lazy;
172 use ra_syntax::{AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken, T};
173
174 static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| SourceFile::parse(",\n; ;"));
175
176 pub(crate) fn comma() -> SyntaxToken {
177 SOURCE_FILE
178 .tree()
179 .syntax()
180 .descendants_with_tokens()
181 .filter_map(|it| it.into_token())
182 .find(|it| it.kind() == T![,])
183 .unwrap()
184 }
185
186 pub(crate) fn single_space() -> SyntaxToken {
187 SOURCE_FILE
188 .tree()
189 .syntax()
190 .descendants_with_tokens()
191 .filter_map(|it| it.into_token())
192 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == " ")
193 .unwrap()
194 }
195
196 #[allow(unused)]
197 pub(crate) fn single_newline() -> 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() == "\n")
204 .unwrap()
205 }
206
207 pub(crate) struct WsBuilder(SourceFile);
208
209 impl WsBuilder {
210 pub(crate) fn new(text: &str) -> WsBuilder {
211 WsBuilder(SourceFile::parse(text).ok().unwrap())
212 }
213 pub(crate) fn ws(&self) -> SyntaxToken {
214 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
215 }
216 }
217
218}
diff --git a/crates/ra_assists/src/ast_editor.rs b/crates/ra_assists/src/ast_editor.rs
index cf32ea52d..55c0aa59f 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)]
diff --git a/crates/ra_ide_api/src/completion/complete_scope.rs b/crates/ra_ide_api/src/completion/complete_scope.rs
index c1f48b026..cb70a1f21 100644
--- a/crates/ra_ide_api/src/completion/complete_scope.rs
+++ b/crates/ra_ide_api/src/completion/complete_scope.rs
@@ -1,4 +1,4 @@
1use ra_assists::auto_import; 1use ra_assists::auto_import_text_edit;
2use ra_syntax::{ast, AstNode, SmolStr}; 2use ra_syntax::{ast, AstNode, SmolStr};
3use ra_text_edit::TextEditBuilder; 3use ra_text_edit::TextEditBuilder;
4use rustc_hash::FxHashMap; 4use rustc_hash::FxHashMap;
@@ -23,7 +23,7 @@ pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) {
23 let edit = { 23 let edit = {
24 let mut builder = TextEditBuilder::default(); 24 let mut builder = TextEditBuilder::default();
25 builder.replace(ctx.source_range(), name.to_string()); 25 builder.replace(ctx.source_range(), name.to_string());
26 auto_import::auto_import_text_edit( 26 auto_import_text_edit(
27 &ctx.token.parent(), 27 &ctx.token.parent(),
28 &ctx.token.parent(), 28 &ctx.token.parent(),
29 &path, 29 &path,
diff --git a/crates/ra_ide_api/src/diagnostics.rs b/crates/ra_ide_api/src/diagnostics.rs
index 93e1e7c2d..f07061e99 100644
--- a/crates/ra_ide_api/src/diagnostics.rs
+++ b/crates/ra_ide_api/src/diagnostics.rs
@@ -2,11 +2,11 @@ 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::Make, 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::{
9 ast::{self, AstNode, RecordField}, 9 ast::{self, AstNode},
10 Location, SyntaxNode, TextRange, T, 10 Location, SyntaxNode, TextRange, T,
11}; 11};
12use ra_text_edit::{TextEdit, TextEditBuilder}; 12use ra_text_edit::{TextEdit, TextEditBuilder};
@@ -59,7 +59,11 @@ pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic>
59 let node = d.ast(db); 59 let node = d.ast(db);
60 let mut ast_editor = AstEditor::new(node); 60 let mut ast_editor = AstEditor::new(node);
61 for f in d.missed_fields.iter() { 61 for f in d.missed_fields.iter() {
62 ast_editor.append_field(&AstBuilder::<RecordField>::from_name(f)); 62 let field = Make::<ast::RecordField>::from(
63 Make::<ast::NameRef>::from(&f.to_string()),
64 Some(Make::<ast::Expr>::unit()),
65 );
66 ast_editor.append_field(&field);
63 } 67 }
64 68
65 let mut builder = TextEditBuilder::default(); 69 let mut builder = TextEditBuilder::default();