diff options
author | Dmitry <[email protected]> | 2020-08-14 19:32:05 +0100 |
---|---|---|
committer | Dmitry <[email protected]> | 2020-08-14 19:32:05 +0100 |
commit | 178c3e135a2a249692f7784712492e7884ae0c00 (patch) | |
tree | ac6b769dbf7162150caa0c1624786a4dd79ff3be /crates/ra_assists/src | |
parent | 06ff8e6c760ff05f10e868b5d1f9d79e42fbb49c (diff) | |
parent | c2594daf2974dbd4ce3d9b7ec72481764abaceb5 (diff) |
Merge remote-tracking branch 'origin/master'
Diffstat (limited to 'crates/ra_assists/src')
47 files changed, 0 insertions, 16658 deletions
diff --git a/crates/ra_assists/src/assist_config.rs b/crates/ra_assists/src/assist_config.rs deleted file mode 100644 index cda2abfb9..000000000 --- a/crates/ra_assists/src/assist_config.rs +++ /dev/null | |||
@@ -1,30 +0,0 @@ | |||
1 | //! Settings for tweaking assists. | ||
2 | //! | ||
3 | //! The fun thing here is `SnippetCap` -- this type can only be created in this | ||
4 | //! module, and we use to statically check that we only produce snippet | ||
5 | //! assists if we are allowed to. | ||
6 | |||
7 | use crate::AssistKind; | ||
8 | |||
9 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
10 | pub struct AssistConfig { | ||
11 | pub snippet_cap: Option<SnippetCap>, | ||
12 | pub allowed: Option<Vec<AssistKind>>, | ||
13 | } | ||
14 | |||
15 | impl AssistConfig { | ||
16 | pub fn allow_snippets(&mut self, yes: bool) { | ||
17 | self.snippet_cap = if yes { Some(SnippetCap { _private: () }) } else { None } | ||
18 | } | ||
19 | } | ||
20 | |||
21 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
22 | pub struct SnippetCap { | ||
23 | _private: (), | ||
24 | } | ||
25 | |||
26 | impl Default for AssistConfig { | ||
27 | fn default() -> Self { | ||
28 | AssistConfig { snippet_cap: Some(SnippetCap { _private: () }), allowed: None } | ||
29 | } | ||
30 | } | ||
diff --git a/crates/ra_assists/src/assist_context.rs b/crates/ra_assists/src/assist_context.rs deleted file mode 100644 index afd3fd4b9..000000000 --- a/crates/ra_assists/src/assist_context.rs +++ /dev/null | |||
@@ -1,306 +0,0 @@ | |||
1 | //! See `AssistContext` | ||
2 | |||
3 | use std::mem; | ||
4 | |||
5 | use algo::find_covering_element; | ||
6 | use hir::Semantics; | ||
7 | use ra_db::{FileId, FileRange}; | ||
8 | use ra_fmt::{leading_indent, reindent}; | ||
9 | use ra_ide_db::{ | ||
10 | source_change::{SourceChange, SourceFileEdit}, | ||
11 | RootDatabase, | ||
12 | }; | ||
13 | use ra_syntax::{ | ||
14 | algo::{self, find_node_at_offset, SyntaxRewriter}, | ||
15 | AstNode, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize, | ||
16 | TokenAtOffset, | ||
17 | }; | ||
18 | use ra_text_edit::TextEditBuilder; | ||
19 | |||
20 | use crate::{ | ||
21 | assist_config::{AssistConfig, SnippetCap}, | ||
22 | Assist, AssistId, AssistKind, GroupLabel, ResolvedAssist, | ||
23 | }; | ||
24 | |||
25 | /// `AssistContext` allows to apply an assist or check if it could be applied. | ||
26 | /// | ||
27 | /// Assists use a somewhat over-engineered approach, given the current needs. | ||
28 | /// The assists workflow consists of two phases. In the first phase, a user asks | ||
29 | /// for the list of available assists. In the second phase, the user picks a | ||
30 | /// particular assist and it gets applied. | ||
31 | /// | ||
32 | /// There are two peculiarities here: | ||
33 | /// | ||
34 | /// * first, we ideally avoid computing more things then necessary to answer "is | ||
35 | /// assist applicable" in the first phase. | ||
36 | /// * second, when we are applying assist, we don't have a guarantee that there | ||
37 | /// weren't any changes between the point when user asked for assists and when | ||
38 | /// they applied a particular assist. So, when applying assist, we need to do | ||
39 | /// all the checks from scratch. | ||
40 | /// | ||
41 | /// To avoid repeating the same code twice for both "check" and "apply" | ||
42 | /// functions, we use an approach reminiscent of that of Django's function based | ||
43 | /// views dealing with forms. Each assist receives a runtime parameter, | ||
44 | /// `resolve`. It first check if an edit is applicable (potentially computing | ||
45 | /// info required to compute the actual edit). If it is applicable, and | ||
46 | /// `resolve` is `true`, it then computes the actual edit. | ||
47 | /// | ||
48 | /// So, to implement the original assists workflow, we can first apply each edit | ||
49 | /// with `resolve = false`, and then applying the selected edit again, with | ||
50 | /// `resolve = true` this time. | ||
51 | /// | ||
52 | /// Note, however, that we don't actually use such two-phase logic at the | ||
53 | /// moment, because the LSP API is pretty awkward in this place, and it's much | ||
54 | /// easier to just compute the edit eagerly :-) | ||
55 | pub(crate) struct AssistContext<'a> { | ||
56 | pub(crate) config: &'a AssistConfig, | ||
57 | pub(crate) sema: Semantics<'a, RootDatabase>, | ||
58 | pub(crate) frange: FileRange, | ||
59 | source_file: SourceFile, | ||
60 | } | ||
61 | |||
62 | impl<'a> AssistContext<'a> { | ||
63 | pub(crate) fn new( | ||
64 | sema: Semantics<'a, RootDatabase>, | ||
65 | config: &'a AssistConfig, | ||
66 | frange: FileRange, | ||
67 | ) -> AssistContext<'a> { | ||
68 | let source_file = sema.parse(frange.file_id); | ||
69 | AssistContext { config, sema, frange, source_file } | ||
70 | } | ||
71 | |||
72 | pub(crate) fn db(&self) -> &RootDatabase { | ||
73 | self.sema.db | ||
74 | } | ||
75 | |||
76 | pub(crate) fn source_file(&self) -> &SourceFile { | ||
77 | &self.source_file | ||
78 | } | ||
79 | |||
80 | // NB, this ignores active selection. | ||
81 | pub(crate) fn offset(&self) -> TextSize { | ||
82 | self.frange.range.start() | ||
83 | } | ||
84 | |||
85 | pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> { | ||
86 | self.source_file.syntax().token_at_offset(self.offset()) | ||
87 | } | ||
88 | pub(crate) fn find_token_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> { | ||
89 | self.token_at_offset().find(|it| it.kind() == kind) | ||
90 | } | ||
91 | pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> { | ||
92 | find_node_at_offset(self.source_file.syntax(), self.offset()) | ||
93 | } | ||
94 | pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> { | ||
95 | self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset()) | ||
96 | } | ||
97 | pub(crate) fn covering_element(&self) -> SyntaxElement { | ||
98 | find_covering_element(self.source_file.syntax(), self.frange.range) | ||
99 | } | ||
100 | // FIXME: remove | ||
101 | pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement { | ||
102 | find_covering_element(self.source_file.syntax(), range) | ||
103 | } | ||
104 | } | ||
105 | |||
106 | pub(crate) struct Assists { | ||
107 | resolve: bool, | ||
108 | file: FileId, | ||
109 | buf: Vec<(Assist, Option<SourceChange>)>, | ||
110 | allowed: Option<Vec<AssistKind>>, | ||
111 | } | ||
112 | |||
113 | impl Assists { | ||
114 | pub(crate) fn new_resolved(ctx: &AssistContext) -> Assists { | ||
115 | Assists { | ||
116 | resolve: true, | ||
117 | file: ctx.frange.file_id, | ||
118 | buf: Vec::new(), | ||
119 | allowed: ctx.config.allowed.clone(), | ||
120 | } | ||
121 | } | ||
122 | |||
123 | pub(crate) fn new_unresolved(ctx: &AssistContext) -> Assists { | ||
124 | Assists { | ||
125 | resolve: false, | ||
126 | file: ctx.frange.file_id, | ||
127 | buf: Vec::new(), | ||
128 | allowed: ctx.config.allowed.clone(), | ||
129 | } | ||
130 | } | ||
131 | |||
132 | pub(crate) fn finish_unresolved(self) -> Vec<Assist> { | ||
133 | assert!(!self.resolve); | ||
134 | self.finish() | ||
135 | .into_iter() | ||
136 | .map(|(label, edit)| { | ||
137 | assert!(edit.is_none()); | ||
138 | label | ||
139 | }) | ||
140 | .collect() | ||
141 | } | ||
142 | |||
143 | pub(crate) fn finish_resolved(self) -> Vec<ResolvedAssist> { | ||
144 | assert!(self.resolve); | ||
145 | self.finish() | ||
146 | .into_iter() | ||
147 | .map(|(label, edit)| ResolvedAssist { assist: label, source_change: edit.unwrap() }) | ||
148 | .collect() | ||
149 | } | ||
150 | |||
151 | pub(crate) fn add( | ||
152 | &mut self, | ||
153 | id: AssistId, | ||
154 | label: impl Into<String>, | ||
155 | target: TextRange, | ||
156 | f: impl FnOnce(&mut AssistBuilder), | ||
157 | ) -> Option<()> { | ||
158 | if !self.is_allowed(&id) { | ||
159 | return None; | ||
160 | } | ||
161 | let label = Assist::new(id, label.into(), None, target); | ||
162 | self.add_impl(label, f) | ||
163 | } | ||
164 | |||
165 | pub(crate) fn add_group( | ||
166 | &mut self, | ||
167 | group: &GroupLabel, | ||
168 | id: AssistId, | ||
169 | label: impl Into<String>, | ||
170 | target: TextRange, | ||
171 | f: impl FnOnce(&mut AssistBuilder), | ||
172 | ) -> Option<()> { | ||
173 | if !self.is_allowed(&id) { | ||
174 | return None; | ||
175 | } | ||
176 | |||
177 | let label = Assist::new(id, label.into(), Some(group.clone()), target); | ||
178 | self.add_impl(label, f) | ||
179 | } | ||
180 | |||
181 | fn add_impl(&mut self, label: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> { | ||
182 | let source_change = if self.resolve { | ||
183 | let mut builder = AssistBuilder::new(self.file); | ||
184 | f(&mut builder); | ||
185 | Some(builder.finish()) | ||
186 | } else { | ||
187 | None | ||
188 | }; | ||
189 | |||
190 | self.buf.push((label, source_change)); | ||
191 | Some(()) | ||
192 | } | ||
193 | |||
194 | fn finish(mut self) -> Vec<(Assist, Option<SourceChange>)> { | ||
195 | self.buf.sort_by_key(|(label, _edit)| label.target.len()); | ||
196 | self.buf | ||
197 | } | ||
198 | |||
199 | fn is_allowed(&self, id: &AssistId) -> bool { | ||
200 | match &self.allowed { | ||
201 | Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)), | ||
202 | None => true, | ||
203 | } | ||
204 | } | ||
205 | } | ||
206 | |||
207 | pub(crate) struct AssistBuilder { | ||
208 | edit: TextEditBuilder, | ||
209 | file_id: FileId, | ||
210 | is_snippet: bool, | ||
211 | change: SourceChange, | ||
212 | } | ||
213 | |||
214 | impl AssistBuilder { | ||
215 | pub(crate) fn new(file_id: FileId) -> AssistBuilder { | ||
216 | AssistBuilder { | ||
217 | edit: TextEditBuilder::default(), | ||
218 | file_id, | ||
219 | is_snippet: false, | ||
220 | change: SourceChange::default(), | ||
221 | } | ||
222 | } | ||
223 | |||
224 | pub(crate) fn edit_file(&mut self, file_id: FileId) { | ||
225 | self.file_id = file_id; | ||
226 | } | ||
227 | |||
228 | fn commit(&mut self) { | ||
229 | let edit = mem::take(&mut self.edit).finish(); | ||
230 | if !edit.is_empty() { | ||
231 | let new_edit = SourceFileEdit { file_id: self.file_id, edit }; | ||
232 | assert!(!self.change.source_file_edits.iter().any(|it| it.file_id == new_edit.file_id)); | ||
233 | self.change.source_file_edits.push(new_edit); | ||
234 | } | ||
235 | } | ||
236 | |||
237 | /// Remove specified `range` of text. | ||
238 | pub(crate) fn delete(&mut self, range: TextRange) { | ||
239 | self.edit.delete(range) | ||
240 | } | ||
241 | /// Append specified `text` at the given `offset` | ||
242 | pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) { | ||
243 | self.edit.insert(offset, text.into()) | ||
244 | } | ||
245 | /// Append specified `snippet` at the given `offset` | ||
246 | pub(crate) fn insert_snippet( | ||
247 | &mut self, | ||
248 | _cap: SnippetCap, | ||
249 | offset: TextSize, | ||
250 | snippet: impl Into<String>, | ||
251 | ) { | ||
252 | self.is_snippet = true; | ||
253 | self.insert(offset, snippet); | ||
254 | } | ||
255 | /// Replaces specified `range` of text with a given string. | ||
256 | pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) { | ||
257 | self.edit.replace(range, replace_with.into()) | ||
258 | } | ||
259 | /// Replaces specified `range` of text with a given `snippet`. | ||
260 | pub(crate) fn replace_snippet( | ||
261 | &mut self, | ||
262 | _cap: SnippetCap, | ||
263 | range: TextRange, | ||
264 | snippet: impl Into<String>, | ||
265 | ) { | ||
266 | self.is_snippet = true; | ||
267 | self.replace(range, snippet); | ||
268 | } | ||
269 | pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) { | ||
270 | algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit) | ||
271 | } | ||
272 | /// Replaces specified `node` of text with a given string, reindenting the | ||
273 | /// string to maintain `node`'s existing indent. | ||
274 | // FIXME: remove in favor of ra_syntax::edit::IndentLevel::increase_indent | ||
275 | pub(crate) fn replace_node_and_indent( | ||
276 | &mut self, | ||
277 | node: &SyntaxNode, | ||
278 | replace_with: impl Into<String>, | ||
279 | ) { | ||
280 | let mut replace_with = replace_with.into(); | ||
281 | if let Some(indent) = leading_indent(node) { | ||
282 | replace_with = reindent(&replace_with, &indent) | ||
283 | } | ||
284 | self.replace(node.text_range(), replace_with) | ||
285 | } | ||
286 | pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) { | ||
287 | let node = rewriter.rewrite_root().unwrap(); | ||
288 | let new = rewriter.rewrite(&node); | ||
289 | algo::diff(&node, &new).into_text_edit(&mut self.edit); | ||
290 | } | ||
291 | |||
292 | // FIXME: kill this API | ||
293 | /// Get access to the raw `TextEditBuilder`. | ||
294 | pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder { | ||
295 | &mut self.edit | ||
296 | } | ||
297 | |||
298 | fn finish(mut self) -> SourceChange { | ||
299 | self.commit(); | ||
300 | let mut change = mem::take(&mut self.change); | ||
301 | if self.is_snippet { | ||
302 | change.is_snippet = true; | ||
303 | } | ||
304 | change | ||
305 | } | ||
306 | } | ||
diff --git a/crates/ra_assists/src/ast_transform.rs b/crates/ra_assists/src/ast_transform.rs deleted file mode 100644 index 15ec75c95..000000000 --- a/crates/ra_assists/src/ast_transform.rs +++ /dev/null | |||
@@ -1,212 +0,0 @@ | |||
1 | //! `AstTransformer`s are functions that replace nodes in an AST and can be easily combined. | ||
2 | use rustc_hash::FxHashMap; | ||
3 | |||
4 | use hir::{HirDisplay, PathResolution, SemanticsScope}; | ||
5 | use ra_syntax::{ | ||
6 | algo::SyntaxRewriter, | ||
7 | ast::{self, AstNode}, | ||
8 | }; | ||
9 | |||
10 | pub trait AstTransform<'a> { | ||
11 | fn get_substitution(&self, node: &ra_syntax::SyntaxNode) -> Option<ra_syntax::SyntaxNode>; | ||
12 | |||
13 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a>; | ||
14 | fn or<T: AstTransform<'a> + 'a>(self, other: T) -> Box<dyn AstTransform<'a> + 'a> | ||
15 | where | ||
16 | Self: Sized + 'a, | ||
17 | { | ||
18 | self.chain_before(Box::new(other)) | ||
19 | } | ||
20 | } | ||
21 | |||
22 | struct NullTransformer; | ||
23 | |||
24 | impl<'a> AstTransform<'a> for NullTransformer { | ||
25 | fn get_substitution(&self, _node: &ra_syntax::SyntaxNode) -> Option<ra_syntax::SyntaxNode> { | ||
26 | None | ||
27 | } | ||
28 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
29 | other | ||
30 | } | ||
31 | } | ||
32 | |||
33 | pub struct SubstituteTypeParams<'a> { | ||
34 | source_scope: &'a SemanticsScope<'a>, | ||
35 | substs: FxHashMap<hir::TypeParam, ast::Type>, | ||
36 | previous: Box<dyn AstTransform<'a> + 'a>, | ||
37 | } | ||
38 | |||
39 | impl<'a> SubstituteTypeParams<'a> { | ||
40 | pub fn for_trait_impl( | ||
41 | source_scope: &'a SemanticsScope<'a>, | ||
42 | // FIXME: there's implicit invariant that `trait_` and `source_scope` match... | ||
43 | trait_: hir::Trait, | ||
44 | impl_def: ast::Impl, | ||
45 | ) -> SubstituteTypeParams<'a> { | ||
46 | let substs = get_syntactic_substs(impl_def).unwrap_or_default(); | ||
47 | let generic_def: hir::GenericDef = trait_.into(); | ||
48 | let substs_by_param: FxHashMap<_, _> = generic_def | ||
49 | .params(source_scope.db) | ||
50 | .into_iter() | ||
51 | // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky | ||
52 | .skip(1) | ||
53 | // The actual list of trait type parameters may be longer than the one | ||
54 | // used in the `impl` block due to trailing default type parametrs. | ||
55 | // For that case we extend the `substs` with an empty iterator so we | ||
56 | // can still hit those trailing values and check if they actually have | ||
57 | // a default type. If they do, go for that type from `hir` to `ast` so | ||
58 | // the resulting change can be applied correctly. | ||
59 | .zip(substs.into_iter().map(Some).chain(std::iter::repeat(None))) | ||
60 | .filter_map(|(k, v)| match v { | ||
61 | Some(v) => Some((k, v)), | ||
62 | None => { | ||
63 | let default = k.default(source_scope.db)?; | ||
64 | Some(( | ||
65 | k, | ||
66 | ast::make::ty( | ||
67 | &default | ||
68 | .display_source_code(source_scope.db, source_scope.module()?.into()) | ||
69 | .ok()?, | ||
70 | ), | ||
71 | )) | ||
72 | } | ||
73 | }) | ||
74 | .collect(); | ||
75 | return SubstituteTypeParams { | ||
76 | source_scope, | ||
77 | substs: substs_by_param, | ||
78 | previous: Box::new(NullTransformer), | ||
79 | }; | ||
80 | |||
81 | // FIXME: It would probably be nicer if we could get this via HIR (i.e. get the | ||
82 | // trait ref, and then go from the types in the substs back to the syntax). | ||
83 | fn get_syntactic_substs(impl_def: ast::Impl) -> Option<Vec<ast::Type>> { | ||
84 | let target_trait = impl_def.trait_()?; | ||
85 | let path_type = match target_trait { | ||
86 | ast::Type::PathType(path) => path, | ||
87 | _ => return None, | ||
88 | }; | ||
89 | let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?; | ||
90 | |||
91 | let mut result = Vec::new(); | ||
92 | for generic_arg in generic_arg_list.generic_args() { | ||
93 | match generic_arg { | ||
94 | ast::GenericArg::TypeArg(type_arg) => result.push(type_arg.ty()?), | ||
95 | ast::GenericArg::AssocTypeArg(_) | ||
96 | | ast::GenericArg::LifetimeArg(_) | ||
97 | | ast::GenericArg::ConstArg(_) => (), | ||
98 | } | ||
99 | } | ||
100 | |||
101 | Some(result) | ||
102 | } | ||
103 | } | ||
104 | fn get_substitution_inner( | ||
105 | &self, | ||
106 | node: &ra_syntax::SyntaxNode, | ||
107 | ) -> Option<ra_syntax::SyntaxNode> { | ||
108 | let type_ref = ast::Type::cast(node.clone())?; | ||
109 | let path = match &type_ref { | ||
110 | ast::Type::PathType(path_type) => path_type.path()?, | ||
111 | _ => return None, | ||
112 | }; | ||
113 | // FIXME: use `hir::Path::from_src` instead. | ||
114 | #[allow(deprecated)] | ||
115 | let path = hir::Path::from_ast(path)?; | ||
116 | let resolution = self.source_scope.resolve_hir_path(&path)?; | ||
117 | match resolution { | ||
118 | hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()), | ||
119 | _ => None, | ||
120 | } | ||
121 | } | ||
122 | } | ||
123 | |||
124 | impl<'a> AstTransform<'a> for SubstituteTypeParams<'a> { | ||
125 | fn get_substitution(&self, node: &ra_syntax::SyntaxNode) -> Option<ra_syntax::SyntaxNode> { | ||
126 | self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node)) | ||
127 | } | ||
128 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
129 | Box::new(SubstituteTypeParams { previous: other, ..self }) | ||
130 | } | ||
131 | } | ||
132 | |||
133 | pub struct QualifyPaths<'a> { | ||
134 | target_scope: &'a SemanticsScope<'a>, | ||
135 | source_scope: &'a SemanticsScope<'a>, | ||
136 | previous: Box<dyn AstTransform<'a> + 'a>, | ||
137 | } | ||
138 | |||
139 | impl<'a> QualifyPaths<'a> { | ||
140 | pub fn new(target_scope: &'a SemanticsScope<'a>, source_scope: &'a SemanticsScope<'a>) -> Self { | ||
141 | Self { target_scope, source_scope, previous: Box::new(NullTransformer) } | ||
142 | } | ||
143 | |||
144 | fn get_substitution_inner( | ||
145 | &self, | ||
146 | node: &ra_syntax::SyntaxNode, | ||
147 | ) -> Option<ra_syntax::SyntaxNode> { | ||
148 | // FIXME handle value ns? | ||
149 | let from = self.target_scope.module()?; | ||
150 | let p = ast::Path::cast(node.clone())?; | ||
151 | if p.segment().and_then(|s| s.param_list()).is_some() { | ||
152 | // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway | ||
153 | return None; | ||
154 | } | ||
155 | // FIXME: use `hir::Path::from_src` instead. | ||
156 | #[allow(deprecated)] | ||
157 | let hir_path = hir::Path::from_ast(p.clone()); | ||
158 | let resolution = self.source_scope.resolve_hir_path(&hir_path?)?; | ||
159 | match resolution { | ||
160 | PathResolution::Def(def) => { | ||
161 | let found_path = from.find_use_path(self.source_scope.db.upcast(), def)?; | ||
162 | let mut path = path_to_ast(found_path); | ||
163 | |||
164 | let type_args = p | ||
165 | .segment() | ||
166 | .and_then(|s| s.generic_arg_list()) | ||
167 | .map(|arg_list| apply(self, arg_list)); | ||
168 | if let Some(type_args) = type_args { | ||
169 | let last_segment = path.segment().unwrap(); | ||
170 | path = path.with_segment(last_segment.with_type_args(type_args)) | ||
171 | } | ||
172 | |||
173 | Some(path.syntax().clone()) | ||
174 | } | ||
175 | PathResolution::Local(_) | ||
176 | | PathResolution::TypeParam(_) | ||
177 | | PathResolution::SelfType(_) => None, | ||
178 | PathResolution::Macro(_) => None, | ||
179 | PathResolution::AssocItem(_) => None, | ||
180 | } | ||
181 | } | ||
182 | } | ||
183 | |||
184 | pub fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: N) -> N { | ||
185 | SyntaxRewriter::from_fn(|element| match element { | ||
186 | ra_syntax::SyntaxElement::Node(n) => { | ||
187 | let replacement = transformer.get_substitution(&n)?; | ||
188 | Some(replacement.into()) | ||
189 | } | ||
190 | _ => None, | ||
191 | }) | ||
192 | .rewrite_ast(&node) | ||
193 | } | ||
194 | |||
195 | impl<'a> AstTransform<'a> for QualifyPaths<'a> { | ||
196 | fn get_substitution(&self, node: &ra_syntax::SyntaxNode) -> Option<ra_syntax::SyntaxNode> { | ||
197 | self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node)) | ||
198 | } | ||
199 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
200 | Box::new(QualifyPaths { previous: other, ..self }) | ||
201 | } | ||
202 | } | ||
203 | |||
204 | pub(crate) fn path_to_ast(path: hir::ModPath) -> ast::Path { | ||
205 | let parse = ast::SourceFile::parse(&path.to_string()); | ||
206 | parse | ||
207 | .tree() | ||
208 | .syntax() | ||
209 | .descendants() | ||
210 | .find_map(ast::Path::cast) | ||
211 | .unwrap_or_else(|| panic!("failed to parse path {:?}, `{}`", path, path)) | ||
212 | } | ||
diff --git a/crates/ra_assists/src/handlers/add_custom_impl.rs b/crates/ra_assists/src/handlers/add_custom_impl.rs deleted file mode 100644 index b67438b6b..000000000 --- a/crates/ra_assists/src/handlers/add_custom_impl.rs +++ /dev/null | |||
@@ -1,208 +0,0 @@ | |||
1 | use ra_syntax::{ | ||
2 | ast::{self, AstNode}, | ||
3 | Direction, SmolStr, | ||
4 | SyntaxKind::{IDENT, WHITESPACE}, | ||
5 | TextRange, TextSize, | ||
6 | }; | ||
7 | use stdx::SepBy; | ||
8 | |||
9 | use crate::{ | ||
10 | assist_context::{AssistContext, Assists}, | ||
11 | AssistId, AssistKind, | ||
12 | }; | ||
13 | |||
14 | // Assist: add_custom_impl | ||
15 | // | ||
16 | // Adds impl block for derived trait. | ||
17 | // | ||
18 | // ``` | ||
19 | // #[derive(Deb<|>ug, Display)] | ||
20 | // struct S; | ||
21 | // ``` | ||
22 | // -> | ||
23 | // ``` | ||
24 | // #[derive(Display)] | ||
25 | // struct S; | ||
26 | // | ||
27 | // impl Debug for S { | ||
28 | // $0 | ||
29 | // } | ||
30 | // ``` | ||
31 | pub(crate) fn add_custom_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
32 | let attr = ctx.find_node_at_offset::<ast::Attr>()?; | ||
33 | let input = attr.token_tree()?; | ||
34 | |||
35 | let attr_name = attr | ||
36 | .syntax() | ||
37 | .descendants_with_tokens() | ||
38 | .filter(|t| t.kind() == IDENT) | ||
39 | .find_map(|i| i.into_token()) | ||
40 | .filter(|t| *t.text() == "derive")? | ||
41 | .text() | ||
42 | .clone(); | ||
43 | |||
44 | let trait_token = | ||
45 | ctx.token_at_offset().find(|t| t.kind() == IDENT && *t.text() != attr_name)?; | ||
46 | |||
47 | let annotated = attr.syntax().siblings(Direction::Next).find_map(ast::Name::cast)?; | ||
48 | let annotated_name = annotated.syntax().text().to_string(); | ||
49 | let start_offset = annotated.syntax().parent()?.text_range().end(); | ||
50 | |||
51 | let label = | ||
52 | format!("Add custom impl `{}` for `{}`", trait_token.text().as_str(), annotated_name); | ||
53 | |||
54 | let target = attr.syntax().text_range(); | ||
55 | acc.add(AssistId("add_custom_impl", AssistKind::Refactor), label, target, |builder| { | ||
56 | let new_attr_input = input | ||
57 | .syntax() | ||
58 | .descendants_with_tokens() | ||
59 | .filter(|t| t.kind() == IDENT) | ||
60 | .filter_map(|t| t.into_token().map(|t| t.text().clone())) | ||
61 | .filter(|t| t != trait_token.text()) | ||
62 | .collect::<Vec<SmolStr>>(); | ||
63 | let has_more_derives = !new_attr_input.is_empty(); | ||
64 | let new_attr_input = new_attr_input.iter().sep_by(", ").surround_with("(", ")").to_string(); | ||
65 | |||
66 | if has_more_derives { | ||
67 | builder.replace(input.syntax().text_range(), new_attr_input); | ||
68 | } else { | ||
69 | let attr_range = attr.syntax().text_range(); | ||
70 | builder.delete(attr_range); | ||
71 | |||
72 | let line_break_range = attr | ||
73 | .syntax() | ||
74 | .next_sibling_or_token() | ||
75 | .filter(|t| t.kind() == WHITESPACE) | ||
76 | .map(|t| t.text_range()) | ||
77 | .unwrap_or_else(|| TextRange::new(TextSize::from(0), TextSize::from(0))); | ||
78 | builder.delete(line_break_range); | ||
79 | } | ||
80 | |||
81 | match ctx.config.snippet_cap { | ||
82 | Some(cap) => { | ||
83 | builder.insert_snippet( | ||
84 | cap, | ||
85 | start_offset, | ||
86 | format!("\n\nimpl {} for {} {{\n $0\n}}", trait_token, annotated_name), | ||
87 | ); | ||
88 | } | ||
89 | None => { | ||
90 | builder.insert( | ||
91 | start_offset, | ||
92 | format!("\n\nimpl {} for {} {{\n\n}}", trait_token, annotated_name), | ||
93 | ); | ||
94 | } | ||
95 | } | ||
96 | }) | ||
97 | } | ||
98 | |||
99 | #[cfg(test)] | ||
100 | mod tests { | ||
101 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
102 | |||
103 | use super::*; | ||
104 | |||
105 | #[test] | ||
106 | fn add_custom_impl_for_unique_input() { | ||
107 | check_assist( | ||
108 | add_custom_impl, | ||
109 | " | ||
110 | #[derive(Debu<|>g)] | ||
111 | struct Foo { | ||
112 | bar: String, | ||
113 | } | ||
114 | ", | ||
115 | " | ||
116 | struct Foo { | ||
117 | bar: String, | ||
118 | } | ||
119 | |||
120 | impl Debug for Foo { | ||
121 | $0 | ||
122 | } | ||
123 | ", | ||
124 | ) | ||
125 | } | ||
126 | |||
127 | #[test] | ||
128 | fn add_custom_impl_for_with_visibility_modifier() { | ||
129 | check_assist( | ||
130 | add_custom_impl, | ||
131 | " | ||
132 | #[derive(Debug<|>)] | ||
133 | pub struct Foo { | ||
134 | bar: String, | ||
135 | } | ||
136 | ", | ||
137 | " | ||
138 | pub struct Foo { | ||
139 | bar: String, | ||
140 | } | ||
141 | |||
142 | impl Debug for Foo { | ||
143 | $0 | ||
144 | } | ||
145 | ", | ||
146 | ) | ||
147 | } | ||
148 | |||
149 | #[test] | ||
150 | fn add_custom_impl_when_multiple_inputs() { | ||
151 | check_assist( | ||
152 | add_custom_impl, | ||
153 | " | ||
154 | #[derive(Display, Debug<|>, Serialize)] | ||
155 | struct Foo {} | ||
156 | ", | ||
157 | " | ||
158 | #[derive(Display, Serialize)] | ||
159 | struct Foo {} | ||
160 | |||
161 | impl Debug for Foo { | ||
162 | $0 | ||
163 | } | ||
164 | ", | ||
165 | ) | ||
166 | } | ||
167 | |||
168 | #[test] | ||
169 | fn test_ignore_derive_macro_without_input() { | ||
170 | check_assist_not_applicable( | ||
171 | add_custom_impl, | ||
172 | " | ||
173 | #[derive(<|>)] | ||
174 | struct Foo {} | ||
175 | ", | ||
176 | ) | ||
177 | } | ||
178 | |||
179 | #[test] | ||
180 | fn test_ignore_if_cursor_on_param() { | ||
181 | check_assist_not_applicable( | ||
182 | add_custom_impl, | ||
183 | " | ||
184 | #[derive<|>(Debug)] | ||
185 | struct Foo {} | ||
186 | ", | ||
187 | ); | ||
188 | |||
189 | check_assist_not_applicable( | ||
190 | add_custom_impl, | ||
191 | " | ||
192 | #[derive(Debug)<|>] | ||
193 | struct Foo {} | ||
194 | ", | ||
195 | ) | ||
196 | } | ||
197 | |||
198 | #[test] | ||
199 | fn test_ignore_if_not_derive() { | ||
200 | check_assist_not_applicable( | ||
201 | add_custom_impl, | ||
202 | " | ||
203 | #[allow(non_camel_<|>case_types)] | ||
204 | struct Foo {} | ||
205 | ", | ||
206 | ) | ||
207 | } | ||
208 | } | ||
diff --git a/crates/ra_assists/src/handlers/add_explicit_type.rs b/crates/ra_assists/src/handlers/add_explicit_type.rs deleted file mode 100644 index 135a2ac9c..000000000 --- a/crates/ra_assists/src/handlers/add_explicit_type.rs +++ /dev/null | |||
@@ -1,211 +0,0 @@ | |||
1 | use hir::HirDisplay; | ||
2 | use ra_syntax::{ | ||
3 | ast::{self, AstNode, LetStmt, NameOwner}, | ||
4 | TextRange, | ||
5 | }; | ||
6 | |||
7 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
8 | |||
9 | // Assist: add_explicit_type | ||
10 | // | ||
11 | // Specify type for a let binding. | ||
12 | // | ||
13 | // ``` | ||
14 | // fn main() { | ||
15 | // let x<|> = 92; | ||
16 | // } | ||
17 | // ``` | ||
18 | // -> | ||
19 | // ``` | ||
20 | // fn main() { | ||
21 | // let x: i32 = 92; | ||
22 | // } | ||
23 | // ``` | ||
24 | pub(crate) fn add_explicit_type(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
25 | let let_stmt = ctx.find_node_at_offset::<LetStmt>()?; | ||
26 | let module = ctx.sema.scope(let_stmt.syntax()).module()?; | ||
27 | let expr = let_stmt.initializer()?; | ||
28 | // Must be a binding | ||
29 | let pat = match let_stmt.pat()? { | ||
30 | ast::Pat::IdentPat(bind_pat) => bind_pat, | ||
31 | _ => return None, | ||
32 | }; | ||
33 | let pat_range = pat.syntax().text_range(); | ||
34 | // The binding must have a name | ||
35 | let name = pat.name()?; | ||
36 | let name_range = name.syntax().text_range(); | ||
37 | let stmt_range = let_stmt.syntax().text_range(); | ||
38 | let eq_range = let_stmt.eq_token()?.text_range(); | ||
39 | // Assist should only be applicable if cursor is between 'let' and '=' | ||
40 | let let_range = TextRange::new(stmt_range.start(), eq_range.start()); | ||
41 | let cursor_in_range = let_range.contains_range(ctx.frange.range); | ||
42 | if !cursor_in_range { | ||
43 | return None; | ||
44 | } | ||
45 | // Assist not applicable if the type has already been specified | ||
46 | // and it has no placeholders | ||
47 | let ascribed_ty = let_stmt.ty(); | ||
48 | if let Some(ty) = &ascribed_ty { | ||
49 | if ty.syntax().descendants().find_map(ast::InferType::cast).is_none() { | ||
50 | return None; | ||
51 | } | ||
52 | } | ||
53 | // Infer type | ||
54 | let ty = ctx.sema.type_of_expr(&expr)?; | ||
55 | |||
56 | if ty.contains_unknown() || ty.is_closure() { | ||
57 | return None; | ||
58 | } | ||
59 | |||
60 | let inferred_type = ty.display_source_code(ctx.db(), module.into()).ok()?; | ||
61 | acc.add( | ||
62 | AssistId("add_explicit_type", AssistKind::RefactorRewrite), | ||
63 | format!("Insert explicit type `{}`", inferred_type), | ||
64 | pat_range, | ||
65 | |builder| match ascribed_ty { | ||
66 | Some(ascribed_ty) => { | ||
67 | builder.replace(ascribed_ty.syntax().text_range(), inferred_type); | ||
68 | } | ||
69 | None => { | ||
70 | builder.insert(name_range.end(), format!(": {}", inferred_type)); | ||
71 | } | ||
72 | }, | ||
73 | ) | ||
74 | } | ||
75 | |||
76 | #[cfg(test)] | ||
77 | mod tests { | ||
78 | use super::*; | ||
79 | |||
80 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
81 | |||
82 | #[test] | ||
83 | fn add_explicit_type_target() { | ||
84 | check_assist_target(add_explicit_type, "fn f() { let a<|> = 1; }", "a"); | ||
85 | } | ||
86 | |||
87 | #[test] | ||
88 | fn add_explicit_type_works_for_simple_expr() { | ||
89 | check_assist(add_explicit_type, "fn f() { let a<|> = 1; }", "fn f() { let a: i32 = 1; }"); | ||
90 | } | ||
91 | |||
92 | #[test] | ||
93 | fn add_explicit_type_works_for_underscore() { | ||
94 | check_assist( | ||
95 | add_explicit_type, | ||
96 | "fn f() { let a<|>: _ = 1; }", | ||
97 | "fn f() { let a: i32 = 1; }", | ||
98 | ); | ||
99 | } | ||
100 | |||
101 | #[test] | ||
102 | fn add_explicit_type_works_for_nested_underscore() { | ||
103 | check_assist( | ||
104 | add_explicit_type, | ||
105 | r#" | ||
106 | enum Option<T> { | ||
107 | Some(T), | ||
108 | None | ||
109 | } | ||
110 | |||
111 | fn f() { | ||
112 | let a<|>: Option<_> = Option::Some(1); | ||
113 | }"#, | ||
114 | r#" | ||
115 | enum Option<T> { | ||
116 | Some(T), | ||
117 | None | ||
118 | } | ||
119 | |||
120 | fn f() { | ||
121 | let a: Option<i32> = Option::Some(1); | ||
122 | }"#, | ||
123 | ); | ||
124 | } | ||
125 | |||
126 | #[test] | ||
127 | fn add_explicit_type_works_for_macro_call() { | ||
128 | check_assist( | ||
129 | add_explicit_type, | ||
130 | r"macro_rules! v { () => {0u64} } fn f() { let a<|> = v!(); }", | ||
131 | r"macro_rules! v { () => {0u64} } fn f() { let a: u64 = v!(); }", | ||
132 | ); | ||
133 | } | ||
134 | |||
135 | #[test] | ||
136 | fn add_explicit_type_works_for_macro_call_recursive() { | ||
137 | check_assist( | ||
138 | add_explicit_type, | ||
139 | r#"macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a<|> = v!(); }"#, | ||
140 | r#"macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a: u64 = v!(); }"#, | ||
141 | ); | ||
142 | } | ||
143 | |||
144 | #[test] | ||
145 | fn add_explicit_type_not_applicable_if_ty_not_inferred() { | ||
146 | check_assist_not_applicable(add_explicit_type, "fn f() { let a<|> = None; }"); | ||
147 | } | ||
148 | |||
149 | #[test] | ||
150 | fn add_explicit_type_not_applicable_if_ty_already_specified() { | ||
151 | check_assist_not_applicable(add_explicit_type, "fn f() { let a<|>: i32 = 1; }"); | ||
152 | } | ||
153 | |||
154 | #[test] | ||
155 | fn add_explicit_type_not_applicable_if_specified_ty_is_tuple() { | ||
156 | check_assist_not_applicable(add_explicit_type, "fn f() { let a<|>: (i32, i32) = (3, 4); }"); | ||
157 | } | ||
158 | |||
159 | #[test] | ||
160 | fn add_explicit_type_not_applicable_if_cursor_after_equals() { | ||
161 | check_assist_not_applicable( | ||
162 | add_explicit_type, | ||
163 | "fn f() {let a =<|> match 1 {2 => 3, 3 => 5};}", | ||
164 | ) | ||
165 | } | ||
166 | |||
167 | #[test] | ||
168 | fn add_explicit_type_not_applicable_if_cursor_before_let() { | ||
169 | check_assist_not_applicable( | ||
170 | add_explicit_type, | ||
171 | "fn f() <|>{let a = match 1 {2 => 3, 3 => 5};}", | ||
172 | ) | ||
173 | } | ||
174 | |||
175 | #[test] | ||
176 | fn closure_parameters_are_not_added() { | ||
177 | check_assist_not_applicable( | ||
178 | add_explicit_type, | ||
179 | r#" | ||
180 | fn main() { | ||
181 | let multiply_by_two<|> = |i| i * 3; | ||
182 | let six = multiply_by_two(2); | ||
183 | }"#, | ||
184 | ) | ||
185 | } | ||
186 | |||
187 | #[test] | ||
188 | fn default_generics_should_not_be_added() { | ||
189 | check_assist( | ||
190 | add_explicit_type, | ||
191 | r#" | ||
192 | struct Test<K, T = u8> { | ||
193 | k: K, | ||
194 | t: T, | ||
195 | } | ||
196 | |||
197 | fn main() { | ||
198 | let test<|> = Test { t: 23u8, k: 33 }; | ||
199 | }"#, | ||
200 | r#" | ||
201 | struct Test<K, T = u8> { | ||
202 | k: K, | ||
203 | t: T, | ||
204 | } | ||
205 | |||
206 | fn main() { | ||
207 | let test: Test<i32> = Test { t: 23u8, k: 33 }; | ||
208 | }"#, | ||
209 | ); | ||
210 | } | ||
211 | } | ||
diff --git a/crates/ra_assists/src/handlers/add_missing_impl_members.rs b/crates/ra_assists/src/handlers/add_missing_impl_members.rs deleted file mode 100644 index 95a750aee..000000000 --- a/crates/ra_assists/src/handlers/add_missing_impl_members.rs +++ /dev/null | |||
@@ -1,711 +0,0 @@ | |||
1 | use hir::HasSource; | ||
2 | use ra_syntax::{ | ||
3 | ast::{ | ||
4 | self, | ||
5 | edit::{self, AstNodeEdit, IndentLevel}, | ||
6 | make, AstNode, NameOwner, | ||
7 | }, | ||
8 | SmolStr, | ||
9 | }; | ||
10 | |||
11 | use crate::{ | ||
12 | assist_context::{AssistContext, Assists}, | ||
13 | ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams}, | ||
14 | utils::{get_missing_assoc_items, render_snippet, resolve_target_trait, Cursor}, | ||
15 | AssistId, AssistKind, | ||
16 | }; | ||
17 | |||
18 | #[derive(PartialEq)] | ||
19 | enum AddMissingImplMembersMode { | ||
20 | DefaultMethodsOnly, | ||
21 | NoDefaultMethods, | ||
22 | } | ||
23 | |||
24 | // Assist: add_impl_missing_members | ||
25 | // | ||
26 | // Adds scaffold for required impl members. | ||
27 | // | ||
28 | // ``` | ||
29 | // trait Trait<T> { | ||
30 | // Type X; | ||
31 | // fn foo(&self) -> T; | ||
32 | // fn bar(&self) {} | ||
33 | // } | ||
34 | // | ||
35 | // impl Trait<u32> for () {<|> | ||
36 | // | ||
37 | // } | ||
38 | // ``` | ||
39 | // -> | ||
40 | // ``` | ||
41 | // trait Trait<T> { | ||
42 | // Type X; | ||
43 | // fn foo(&self) -> T; | ||
44 | // fn bar(&self) {} | ||
45 | // } | ||
46 | // | ||
47 | // impl Trait<u32> for () { | ||
48 | // fn foo(&self) -> u32 { | ||
49 | // ${0:todo!()} | ||
50 | // } | ||
51 | // | ||
52 | // } | ||
53 | // ``` | ||
54 | pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
55 | add_missing_impl_members_inner( | ||
56 | acc, | ||
57 | ctx, | ||
58 | AddMissingImplMembersMode::NoDefaultMethods, | ||
59 | "add_impl_missing_members", | ||
60 | "Implement missing members", | ||
61 | ) | ||
62 | } | ||
63 | |||
64 | // Assist: add_impl_default_members | ||
65 | // | ||
66 | // Adds scaffold for overriding default impl members. | ||
67 | // | ||
68 | // ``` | ||
69 | // trait Trait { | ||
70 | // Type X; | ||
71 | // fn foo(&self); | ||
72 | // fn bar(&self) {} | ||
73 | // } | ||
74 | // | ||
75 | // impl Trait for () { | ||
76 | // Type X = (); | ||
77 | // fn foo(&self) {}<|> | ||
78 | // | ||
79 | // } | ||
80 | // ``` | ||
81 | // -> | ||
82 | // ``` | ||
83 | // trait Trait { | ||
84 | // Type X; | ||
85 | // fn foo(&self); | ||
86 | // fn bar(&self) {} | ||
87 | // } | ||
88 | // | ||
89 | // impl Trait for () { | ||
90 | // Type X = (); | ||
91 | // fn foo(&self) {} | ||
92 | // $0fn bar(&self) {} | ||
93 | // | ||
94 | // } | ||
95 | // ``` | ||
96 | pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
97 | add_missing_impl_members_inner( | ||
98 | acc, | ||
99 | ctx, | ||
100 | AddMissingImplMembersMode::DefaultMethodsOnly, | ||
101 | "add_impl_default_members", | ||
102 | "Implement default members", | ||
103 | ) | ||
104 | } | ||
105 | |||
106 | fn add_missing_impl_members_inner( | ||
107 | acc: &mut Assists, | ||
108 | ctx: &AssistContext, | ||
109 | mode: AddMissingImplMembersMode, | ||
110 | assist_id: &'static str, | ||
111 | label: &'static str, | ||
112 | ) -> Option<()> { | ||
113 | let _p = ra_prof::profile("add_missing_impl_members_inner"); | ||
114 | let impl_def = ctx.find_node_at_offset::<ast::Impl>()?; | ||
115 | let impl_item_list = impl_def.assoc_item_list()?; | ||
116 | |||
117 | let trait_ = resolve_target_trait(&ctx.sema, &impl_def)?; | ||
118 | |||
119 | let def_name = |item: &ast::AssocItem| -> Option<SmolStr> { | ||
120 | match item { | ||
121 | ast::AssocItem::Fn(def) => def.name(), | ||
122 | ast::AssocItem::TypeAlias(def) => def.name(), | ||
123 | ast::AssocItem::Const(def) => def.name(), | ||
124 | ast::AssocItem::MacroCall(_) => None, | ||
125 | } | ||
126 | .map(|it| it.text().clone()) | ||
127 | }; | ||
128 | |||
129 | let missing_items = get_missing_assoc_items(&ctx.sema, &impl_def) | ||
130 | .iter() | ||
131 | .map(|i| match i { | ||
132 | hir::AssocItem::Function(i) => ast::AssocItem::Fn(i.source(ctx.db()).value), | ||
133 | hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(i.source(ctx.db()).value), | ||
134 | hir::AssocItem::Const(i) => ast::AssocItem::Const(i.source(ctx.db()).value), | ||
135 | }) | ||
136 | .filter(|t| def_name(&t).is_some()) | ||
137 | .filter(|t| match t { | ||
138 | ast::AssocItem::Fn(def) => match mode { | ||
139 | AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(), | ||
140 | AddMissingImplMembersMode::NoDefaultMethods => def.body().is_none(), | ||
141 | }, | ||
142 | _ => mode == AddMissingImplMembersMode::NoDefaultMethods, | ||
143 | }) | ||
144 | .collect::<Vec<_>>(); | ||
145 | |||
146 | if missing_items.is_empty() { | ||
147 | return None; | ||
148 | } | ||
149 | |||
150 | let target = impl_def.syntax().text_range(); | ||
151 | acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| { | ||
152 | let n_existing_items = impl_item_list.assoc_items().count(); | ||
153 | let source_scope = ctx.sema.scope_for_def(trait_); | ||
154 | let target_scope = ctx.sema.scope(impl_item_list.syntax()); | ||
155 | let ast_transform = QualifyPaths::new(&target_scope, &source_scope) | ||
156 | .or(SubstituteTypeParams::for_trait_impl(&source_scope, trait_, impl_def)); | ||
157 | let items = missing_items | ||
158 | .into_iter() | ||
159 | .map(|it| ast_transform::apply(&*ast_transform, it)) | ||
160 | .map(|it| match it { | ||
161 | ast::AssocItem::Fn(def) => ast::AssocItem::Fn(add_body(def)), | ||
162 | ast::AssocItem::TypeAlias(def) => ast::AssocItem::TypeAlias(def.remove_bounds()), | ||
163 | _ => it, | ||
164 | }) | ||
165 | .map(|it| edit::remove_attrs_and_docs(&it)); | ||
166 | let new_impl_item_list = impl_item_list.append_items(items); | ||
167 | let first_new_item = new_impl_item_list.assoc_items().nth(n_existing_items).unwrap(); | ||
168 | |||
169 | let original_range = impl_item_list.syntax().text_range(); | ||
170 | match ctx.config.snippet_cap { | ||
171 | None => builder.replace(original_range, new_impl_item_list.to_string()), | ||
172 | Some(cap) => { | ||
173 | let mut cursor = Cursor::Before(first_new_item.syntax()); | ||
174 | let placeholder; | ||
175 | if let ast::AssocItem::Fn(func) = &first_new_item { | ||
176 | if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) { | ||
177 | if m.syntax().text() == "todo!()" { | ||
178 | placeholder = m; | ||
179 | cursor = Cursor::Replace(placeholder.syntax()); | ||
180 | } | ||
181 | } | ||
182 | } | ||
183 | builder.replace_snippet( | ||
184 | cap, | ||
185 | original_range, | ||
186 | render_snippet(cap, new_impl_item_list.syntax(), cursor), | ||
187 | ) | ||
188 | } | ||
189 | }; | ||
190 | }) | ||
191 | } | ||
192 | |||
193 | fn add_body(fn_def: ast::Fn) -> ast::Fn { | ||
194 | if fn_def.body().is_some() { | ||
195 | return fn_def; | ||
196 | } | ||
197 | let body = make::block_expr(None, Some(make::expr_todo())).indent(IndentLevel(1)); | ||
198 | fn_def.with_body(body) | ||
199 | } | ||
200 | |||
201 | #[cfg(test)] | ||
202 | mod tests { | ||
203 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
204 | |||
205 | use super::*; | ||
206 | |||
207 | #[test] | ||
208 | fn test_add_missing_impl_members() { | ||
209 | check_assist( | ||
210 | add_missing_impl_members, | ||
211 | r#" | ||
212 | trait Foo { | ||
213 | type Output; | ||
214 | |||
215 | const CONST: usize = 42; | ||
216 | |||
217 | fn foo(&self); | ||
218 | fn bar(&self); | ||
219 | fn baz(&self); | ||
220 | } | ||
221 | |||
222 | struct S; | ||
223 | |||
224 | impl Foo for S { | ||
225 | fn bar(&self) {} | ||
226 | <|> | ||
227 | }"#, | ||
228 | r#" | ||
229 | trait Foo { | ||
230 | type Output; | ||
231 | |||
232 | const CONST: usize = 42; | ||
233 | |||
234 | fn foo(&self); | ||
235 | fn bar(&self); | ||
236 | fn baz(&self); | ||
237 | } | ||
238 | |||
239 | struct S; | ||
240 | |||
241 | impl Foo for S { | ||
242 | fn bar(&self) {} | ||
243 | $0type Output; | ||
244 | const CONST: usize = 42; | ||
245 | fn foo(&self) { | ||
246 | todo!() | ||
247 | } | ||
248 | fn baz(&self) { | ||
249 | todo!() | ||
250 | } | ||
251 | |||
252 | }"#, | ||
253 | ); | ||
254 | } | ||
255 | |||
256 | #[test] | ||
257 | fn test_copied_overriden_members() { | ||
258 | check_assist( | ||
259 | add_missing_impl_members, | ||
260 | r#" | ||
261 | trait Foo { | ||
262 | fn foo(&self); | ||
263 | fn bar(&self) -> bool { true } | ||
264 | fn baz(&self) -> u32 { 42 } | ||
265 | } | ||
266 | |||
267 | struct S; | ||
268 | |||
269 | impl Foo for S { | ||
270 | fn bar(&self) {} | ||
271 | <|> | ||
272 | }"#, | ||
273 | r#" | ||
274 | trait Foo { | ||
275 | fn foo(&self); | ||
276 | fn bar(&self) -> bool { true } | ||
277 | fn baz(&self) -> u32 { 42 } | ||
278 | } | ||
279 | |||
280 | struct S; | ||
281 | |||
282 | impl Foo for S { | ||
283 | fn bar(&self) {} | ||
284 | fn foo(&self) { | ||
285 | ${0:todo!()} | ||
286 | } | ||
287 | |||
288 | }"#, | ||
289 | ); | ||
290 | } | ||
291 | |||
292 | #[test] | ||
293 | fn test_empty_impl_def() { | ||
294 | check_assist( | ||
295 | add_missing_impl_members, | ||
296 | r#" | ||
297 | trait Foo { fn foo(&self); } | ||
298 | struct S; | ||
299 | impl Foo for S { <|> }"#, | ||
300 | r#" | ||
301 | trait Foo { fn foo(&self); } | ||
302 | struct S; | ||
303 | impl Foo for S { | ||
304 | fn foo(&self) { | ||
305 | ${0:todo!()} | ||
306 | } | ||
307 | }"#, | ||
308 | ); | ||
309 | } | ||
310 | |||
311 | #[test] | ||
312 | fn fill_in_type_params_1() { | ||
313 | check_assist( | ||
314 | add_missing_impl_members, | ||
315 | r#" | ||
316 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
317 | struct S; | ||
318 | impl Foo<u32> for S { <|> }"#, | ||
319 | r#" | ||
320 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
321 | struct S; | ||
322 | impl Foo<u32> for S { | ||
323 | fn foo(&self, t: u32) -> &u32 { | ||
324 | ${0:todo!()} | ||
325 | } | ||
326 | }"#, | ||
327 | ); | ||
328 | } | ||
329 | |||
330 | #[test] | ||
331 | fn fill_in_type_params_2() { | ||
332 | check_assist( | ||
333 | add_missing_impl_members, | ||
334 | r#" | ||
335 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
336 | struct S; | ||
337 | impl<U> Foo<U> for S { <|> }"#, | ||
338 | r#" | ||
339 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
340 | struct S; | ||
341 | impl<U> Foo<U> for S { | ||
342 | fn foo(&self, t: U) -> &U { | ||
343 | ${0:todo!()} | ||
344 | } | ||
345 | }"#, | ||
346 | ); | ||
347 | } | ||
348 | |||
349 | #[test] | ||
350 | fn test_cursor_after_empty_impl_def() { | ||
351 | check_assist( | ||
352 | add_missing_impl_members, | ||
353 | r#" | ||
354 | trait Foo { fn foo(&self); } | ||
355 | struct S; | ||
356 | impl Foo for S {}<|>"#, | ||
357 | r#" | ||
358 | trait Foo { fn foo(&self); } | ||
359 | struct S; | ||
360 | impl Foo for S { | ||
361 | fn foo(&self) { | ||
362 | ${0:todo!()} | ||
363 | } | ||
364 | }"#, | ||
365 | ) | ||
366 | } | ||
367 | |||
368 | #[test] | ||
369 | fn test_qualify_path_1() { | ||
370 | check_assist( | ||
371 | add_missing_impl_members, | ||
372 | r#" | ||
373 | mod foo { | ||
374 | pub struct Bar; | ||
375 | trait Foo { fn foo(&self, bar: Bar); } | ||
376 | } | ||
377 | struct S; | ||
378 | impl foo::Foo for S { <|> }"#, | ||
379 | r#" | ||
380 | mod foo { | ||
381 | pub struct Bar; | ||
382 | trait Foo { fn foo(&self, bar: Bar); } | ||
383 | } | ||
384 | struct S; | ||
385 | impl foo::Foo for S { | ||
386 | fn foo(&self, bar: foo::Bar) { | ||
387 | ${0:todo!()} | ||
388 | } | ||
389 | }"#, | ||
390 | ); | ||
391 | } | ||
392 | |||
393 | #[test] | ||
394 | fn test_qualify_path_generic() { | ||
395 | check_assist( | ||
396 | add_missing_impl_members, | ||
397 | r#" | ||
398 | mod foo { | ||
399 | pub struct Bar<T>; | ||
400 | trait Foo { fn foo(&self, bar: Bar<u32>); } | ||
401 | } | ||
402 | struct S; | ||
403 | impl foo::Foo for S { <|> }"#, | ||
404 | r#" | ||
405 | mod foo { | ||
406 | pub struct Bar<T>; | ||
407 | trait Foo { fn foo(&self, bar: Bar<u32>); } | ||
408 | } | ||
409 | struct S; | ||
410 | impl foo::Foo for S { | ||
411 | fn foo(&self, bar: foo::Bar<u32>) { | ||
412 | ${0:todo!()} | ||
413 | } | ||
414 | }"#, | ||
415 | ); | ||
416 | } | ||
417 | |||
418 | #[test] | ||
419 | fn test_qualify_path_and_substitute_param() { | ||
420 | check_assist( | ||
421 | add_missing_impl_members, | ||
422 | r#" | ||
423 | mod foo { | ||
424 | pub struct Bar<T>; | ||
425 | trait Foo<T> { fn foo(&self, bar: Bar<T>); } | ||
426 | } | ||
427 | struct S; | ||
428 | impl foo::Foo<u32> for S { <|> }"#, | ||
429 | r#" | ||
430 | mod foo { | ||
431 | pub struct Bar<T>; | ||
432 | trait Foo<T> { fn foo(&self, bar: Bar<T>); } | ||
433 | } | ||
434 | struct S; | ||
435 | impl foo::Foo<u32> for S { | ||
436 | fn foo(&self, bar: foo::Bar<u32>) { | ||
437 | ${0:todo!()} | ||
438 | } | ||
439 | }"#, | ||
440 | ); | ||
441 | } | ||
442 | |||
443 | #[test] | ||
444 | fn test_substitute_param_no_qualify() { | ||
445 | // when substituting params, the substituted param should not be qualified! | ||
446 | check_assist( | ||
447 | add_missing_impl_members, | ||
448 | r#" | ||
449 | mod foo { | ||
450 | trait Foo<T> { fn foo(&self, bar: T); } | ||
451 | pub struct Param; | ||
452 | } | ||
453 | struct Param; | ||
454 | struct S; | ||
455 | impl foo::Foo<Param> for S { <|> }"#, | ||
456 | r#" | ||
457 | mod foo { | ||
458 | trait Foo<T> { fn foo(&self, bar: T); } | ||
459 | pub struct Param; | ||
460 | } | ||
461 | struct Param; | ||
462 | struct S; | ||
463 | impl foo::Foo<Param> for S { | ||
464 | fn foo(&self, bar: Param) { | ||
465 | ${0:todo!()} | ||
466 | } | ||
467 | }"#, | ||
468 | ); | ||
469 | } | ||
470 | |||
471 | #[test] | ||
472 | fn test_qualify_path_associated_item() { | ||
473 | check_assist( | ||
474 | add_missing_impl_members, | ||
475 | r#" | ||
476 | mod foo { | ||
477 | pub struct Bar<T>; | ||
478 | impl Bar<T> { type Assoc = u32; } | ||
479 | trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); } | ||
480 | } | ||
481 | struct S; | ||
482 | impl foo::Foo for S { <|> }"#, | ||
483 | r#" | ||
484 | mod foo { | ||
485 | pub struct Bar<T>; | ||
486 | impl Bar<T> { type Assoc = u32; } | ||
487 | trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); } | ||
488 | } | ||
489 | struct S; | ||
490 | impl foo::Foo for S { | ||
491 | fn foo(&self, bar: foo::Bar<u32>::Assoc) { | ||
492 | ${0:todo!()} | ||
493 | } | ||
494 | }"#, | ||
495 | ); | ||
496 | } | ||
497 | |||
498 | #[test] | ||
499 | fn test_qualify_path_nested() { | ||
500 | check_assist( | ||
501 | add_missing_impl_members, | ||
502 | r#" | ||
503 | mod foo { | ||
504 | pub struct Bar<T>; | ||
505 | pub struct Baz; | ||
506 | trait Foo { fn foo(&self, bar: Bar<Baz>); } | ||
507 | } | ||
508 | struct S; | ||
509 | impl foo::Foo for S { <|> }"#, | ||
510 | r#" | ||
511 | mod foo { | ||
512 | pub struct Bar<T>; | ||
513 | pub struct Baz; | ||
514 | trait Foo { fn foo(&self, bar: Bar<Baz>); } | ||
515 | } | ||
516 | struct S; | ||
517 | impl foo::Foo for S { | ||
518 | fn foo(&self, bar: foo::Bar<foo::Baz>) { | ||
519 | ${0:todo!()} | ||
520 | } | ||
521 | }"#, | ||
522 | ); | ||
523 | } | ||
524 | |||
525 | #[test] | ||
526 | fn test_qualify_path_fn_trait_notation() { | ||
527 | check_assist( | ||
528 | add_missing_impl_members, | ||
529 | r#" | ||
530 | mod foo { | ||
531 | pub trait Fn<Args> { type Output; } | ||
532 | trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } | ||
533 | } | ||
534 | struct S; | ||
535 | impl foo::Foo for S { <|> }"#, | ||
536 | r#" | ||
537 | mod foo { | ||
538 | pub trait Fn<Args> { type Output; } | ||
539 | trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } | ||
540 | } | ||
541 | struct S; | ||
542 | impl foo::Foo for S { | ||
543 | fn foo(&self, bar: dyn Fn(u32) -> i32) { | ||
544 | ${0:todo!()} | ||
545 | } | ||
546 | }"#, | ||
547 | ); | ||
548 | } | ||
549 | |||
550 | #[test] | ||
551 | fn test_empty_trait() { | ||
552 | check_assist_not_applicable( | ||
553 | add_missing_impl_members, | ||
554 | r#" | ||
555 | trait Foo; | ||
556 | struct S; | ||
557 | impl Foo for S { <|> }"#, | ||
558 | ) | ||
559 | } | ||
560 | |||
561 | #[test] | ||
562 | fn test_ignore_unnamed_trait_members_and_default_methods() { | ||
563 | check_assist_not_applicable( | ||
564 | add_missing_impl_members, | ||
565 | r#" | ||
566 | trait Foo { | ||
567 | fn (arg: u32); | ||
568 | fn valid(some: u32) -> bool { false } | ||
569 | } | ||
570 | struct S; | ||
571 | impl Foo for S { <|> }"#, | ||
572 | ) | ||
573 | } | ||
574 | |||
575 | #[test] | ||
576 | fn test_with_docstring_and_attrs() { | ||
577 | check_assist( | ||
578 | add_missing_impl_members, | ||
579 | r#" | ||
580 | #[doc(alias = "test alias")] | ||
581 | trait Foo { | ||
582 | /// doc string | ||
583 | type Output; | ||
584 | |||
585 | #[must_use] | ||
586 | fn foo(&self); | ||
587 | } | ||
588 | struct S; | ||
589 | impl Foo for S {}<|>"#, | ||
590 | r#" | ||
591 | #[doc(alias = "test alias")] | ||
592 | trait Foo { | ||
593 | /// doc string | ||
594 | type Output; | ||
595 | |||
596 | #[must_use] | ||
597 | fn foo(&self); | ||
598 | } | ||
599 | struct S; | ||
600 | impl Foo for S { | ||
601 | $0type Output; | ||
602 | fn foo(&self) { | ||
603 | todo!() | ||
604 | } | ||
605 | }"#, | ||
606 | ) | ||
607 | } | ||
608 | |||
609 | #[test] | ||
610 | fn test_default_methods() { | ||
611 | check_assist( | ||
612 | add_missing_default_members, | ||
613 | r#" | ||
614 | trait Foo { | ||
615 | type Output; | ||
616 | |||
617 | const CONST: usize = 42; | ||
618 | |||
619 | fn valid(some: u32) -> bool { false } | ||
620 | fn foo(some: u32) -> bool; | ||
621 | } | ||
622 | struct S; | ||
623 | impl Foo for S { <|> }"#, | ||
624 | r#" | ||
625 | trait Foo { | ||
626 | type Output; | ||
627 | |||
628 | const CONST: usize = 42; | ||
629 | |||
630 | fn valid(some: u32) -> bool { false } | ||
631 | fn foo(some: u32) -> bool; | ||
632 | } | ||
633 | struct S; | ||
634 | impl Foo for S { | ||
635 | $0fn valid(some: u32) -> bool { false } | ||
636 | }"#, | ||
637 | ) | ||
638 | } | ||
639 | |||
640 | #[test] | ||
641 | fn test_generic_single_default_parameter() { | ||
642 | check_assist( | ||
643 | add_missing_impl_members, | ||
644 | r#" | ||
645 | trait Foo<T = Self> { | ||
646 | fn bar(&self, other: &T); | ||
647 | } | ||
648 | |||
649 | struct S; | ||
650 | impl Foo for S { <|> }"#, | ||
651 | r#" | ||
652 | trait Foo<T = Self> { | ||
653 | fn bar(&self, other: &T); | ||
654 | } | ||
655 | |||
656 | struct S; | ||
657 | impl Foo for S { | ||
658 | fn bar(&self, other: &Self) { | ||
659 | ${0:todo!()} | ||
660 | } | ||
661 | }"#, | ||
662 | ) | ||
663 | } | ||
664 | |||
665 | #[test] | ||
666 | fn test_generic_default_parameter_is_second() { | ||
667 | check_assist( | ||
668 | add_missing_impl_members, | ||
669 | r#" | ||
670 | trait Foo<T1, T2 = Self> { | ||
671 | fn bar(&self, this: &T1, that: &T2); | ||
672 | } | ||
673 | |||
674 | struct S<T>; | ||
675 | impl Foo<T> for S<T> { <|> }"#, | ||
676 | r#" | ||
677 | trait Foo<T1, T2 = Self> { | ||
678 | fn bar(&self, this: &T1, that: &T2); | ||
679 | } | ||
680 | |||
681 | struct S<T>; | ||
682 | impl Foo<T> for S<T> { | ||
683 | fn bar(&self, this: &T, that: &Self) { | ||
684 | ${0:todo!()} | ||
685 | } | ||
686 | }"#, | ||
687 | ) | ||
688 | } | ||
689 | |||
690 | #[test] | ||
691 | fn test_assoc_type_bounds_are_removed() { | ||
692 | check_assist( | ||
693 | add_missing_impl_members, | ||
694 | r#" | ||
695 | trait Tr { | ||
696 | type Ty: Copy + 'static; | ||
697 | } | ||
698 | |||
699 | impl Tr for ()<|> { | ||
700 | }"#, | ||
701 | r#" | ||
702 | trait Tr { | ||
703 | type Ty: Copy + 'static; | ||
704 | } | ||
705 | |||
706 | impl Tr for () { | ||
707 | $0type Ty; | ||
708 | }"#, | ||
709 | ) | ||
710 | } | ||
711 | } | ||
diff --git a/crates/ra_assists/src/handlers/add_turbo_fish.rs b/crates/ra_assists/src/handlers/add_turbo_fish.rs deleted file mode 100644 index 0c565e89a..000000000 --- a/crates/ra_assists/src/handlers/add_turbo_fish.rs +++ /dev/null | |||
@@ -1,164 +0,0 @@ | |||
1 | use ra_ide_db::defs::{classify_name_ref, Definition, NameRefClass}; | ||
2 | use ra_syntax::{ast, AstNode, SyntaxKind, T}; | ||
3 | use test_utils::mark; | ||
4 | |||
5 | use crate::{ | ||
6 | assist_context::{AssistContext, Assists}, | ||
7 | AssistId, AssistKind, | ||
8 | }; | ||
9 | |||
10 | // Assist: add_turbo_fish | ||
11 | // | ||
12 | // Adds `::<_>` to a call of a generic method or function. | ||
13 | // | ||
14 | // ``` | ||
15 | // fn make<T>() -> T { todo!() } | ||
16 | // fn main() { | ||
17 | // let x = make<|>(); | ||
18 | // } | ||
19 | // ``` | ||
20 | // -> | ||
21 | // ``` | ||
22 | // fn make<T>() -> T { todo!() } | ||
23 | // fn main() { | ||
24 | // let x = make::<${0:_}>(); | ||
25 | // } | ||
26 | // ``` | ||
27 | pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
28 | let ident = ctx.find_token_at_offset(SyntaxKind::IDENT).or_else(|| { | ||
29 | let arg_list = ctx.find_node_at_offset::<ast::ArgList>()?; | ||
30 | if arg_list.args().count() > 0 { | ||
31 | return None; | ||
32 | } | ||
33 | mark::hit!(add_turbo_fish_after_call); | ||
34 | arg_list.l_paren_token()?.prev_token().filter(|it| it.kind() == SyntaxKind::IDENT) | ||
35 | })?; | ||
36 | let next_token = ident.next_token()?; | ||
37 | if next_token.kind() == T![::] { | ||
38 | mark::hit!(add_turbo_fish_one_fish_is_enough); | ||
39 | return None; | ||
40 | } | ||
41 | let name_ref = ast::NameRef::cast(ident.parent())?; | ||
42 | let def = match classify_name_ref(&ctx.sema, &name_ref)? { | ||
43 | NameRefClass::Definition(def) => def, | ||
44 | NameRefClass::FieldShorthand { .. } => return None, | ||
45 | }; | ||
46 | let fun = match def { | ||
47 | Definition::ModuleDef(hir::ModuleDef::Function(it)) => it, | ||
48 | _ => return None, | ||
49 | }; | ||
50 | let generics = hir::GenericDef::Function(fun).params(ctx.sema.db); | ||
51 | if generics.is_empty() { | ||
52 | mark::hit!(add_turbo_fish_non_generic); | ||
53 | return None; | ||
54 | } | ||
55 | acc.add( | ||
56 | AssistId("add_turbo_fish", AssistKind::RefactorRewrite), | ||
57 | "Add `::<>`", | ||
58 | ident.text_range(), | ||
59 | |builder| match ctx.config.snippet_cap { | ||
60 | Some(cap) => builder.insert_snippet(cap, ident.text_range().end(), "::<${0:_}>"), | ||
61 | None => builder.insert(ident.text_range().end(), "::<_>"), | ||
62 | }, | ||
63 | ) | ||
64 | } | ||
65 | |||
66 | #[cfg(test)] | ||
67 | mod tests { | ||
68 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
69 | |||
70 | use super::*; | ||
71 | use test_utils::mark; | ||
72 | |||
73 | #[test] | ||
74 | fn add_turbo_fish_function() { | ||
75 | check_assist( | ||
76 | add_turbo_fish, | ||
77 | r#" | ||
78 | fn make<T>() -> T {} | ||
79 | fn main() { | ||
80 | make<|>(); | ||
81 | } | ||
82 | "#, | ||
83 | r#" | ||
84 | fn make<T>() -> T {} | ||
85 | fn main() { | ||
86 | make::<${0:_}>(); | ||
87 | } | ||
88 | "#, | ||
89 | ); | ||
90 | } | ||
91 | |||
92 | #[test] | ||
93 | fn add_turbo_fish_after_call() { | ||
94 | mark::check!(add_turbo_fish_after_call); | ||
95 | check_assist( | ||
96 | add_turbo_fish, | ||
97 | r#" | ||
98 | fn make<T>() -> T {} | ||
99 | fn main() { | ||
100 | make()<|>; | ||
101 | } | ||
102 | "#, | ||
103 | r#" | ||
104 | fn make<T>() -> T {} | ||
105 | fn main() { | ||
106 | make::<${0:_}>(); | ||
107 | } | ||
108 | "#, | ||
109 | ); | ||
110 | } | ||
111 | |||
112 | #[test] | ||
113 | fn add_turbo_fish_method() { | ||
114 | check_assist( | ||
115 | add_turbo_fish, | ||
116 | r#" | ||
117 | struct S; | ||
118 | impl S { | ||
119 | fn make<T>(&self) -> T {} | ||
120 | } | ||
121 | fn main() { | ||
122 | S.make<|>(); | ||
123 | } | ||
124 | "#, | ||
125 | r#" | ||
126 | struct S; | ||
127 | impl S { | ||
128 | fn make<T>(&self) -> T {} | ||
129 | } | ||
130 | fn main() { | ||
131 | S.make::<${0:_}>(); | ||
132 | } | ||
133 | "#, | ||
134 | ); | ||
135 | } | ||
136 | |||
137 | #[test] | ||
138 | fn add_turbo_fish_one_fish_is_enough() { | ||
139 | mark::check!(add_turbo_fish_one_fish_is_enough); | ||
140 | check_assist_not_applicable( | ||
141 | add_turbo_fish, | ||
142 | r#" | ||
143 | fn make<T>() -> T {} | ||
144 | fn main() { | ||
145 | make<|>::<()>(); | ||
146 | } | ||
147 | "#, | ||
148 | ); | ||
149 | } | ||
150 | |||
151 | #[test] | ||
152 | fn add_turbo_fish_non_generic() { | ||
153 | mark::check!(add_turbo_fish_non_generic); | ||
154 | check_assist_not_applicable( | ||
155 | add_turbo_fish, | ||
156 | r#" | ||
157 | fn make() -> () {} | ||
158 | fn main() { | ||
159 | make<|>(); | ||
160 | } | ||
161 | "#, | ||
162 | ); | ||
163 | } | ||
164 | } | ||
diff --git a/crates/ra_assists/src/handlers/apply_demorgan.rs b/crates/ra_assists/src/handlers/apply_demorgan.rs deleted file mode 100644 index de701f8b8..000000000 --- a/crates/ra_assists/src/handlers/apply_demorgan.rs +++ /dev/null | |||
@@ -1,93 +0,0 @@ | |||
1 | use ra_syntax::ast::{self, AstNode}; | ||
2 | |||
3 | use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKind, Assists}; | ||
4 | |||
5 | // Assist: apply_demorgan | ||
6 | // | ||
7 | // Apply [De Morgan's law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws). | ||
8 | // This transforms expressions of the form `!l || !r` into `!(l && r)`. | ||
9 | // This also works with `&&`. This assist can only be applied with the cursor | ||
10 | // on either `||` or `&&`, with both operands being a negation of some kind. | ||
11 | // This means something of the form `!x` or `x != y`. | ||
12 | // | ||
13 | // ``` | ||
14 | // fn main() { | ||
15 | // if x != 4 ||<|> !y {} | ||
16 | // } | ||
17 | // ``` | ||
18 | // -> | ||
19 | // ``` | ||
20 | // fn main() { | ||
21 | // if !(x == 4 && y) {} | ||
22 | // } | ||
23 | // ``` | ||
24 | pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
25 | let expr = ctx.find_node_at_offset::<ast::BinExpr>()?; | ||
26 | let op = expr.op_kind()?; | ||
27 | let op_range = expr.op_token()?.text_range(); | ||
28 | let opposite_op = opposite_logic_op(op)?; | ||
29 | let cursor_in_range = op_range.contains_range(ctx.frange.range); | ||
30 | if !cursor_in_range { | ||
31 | return None; | ||
32 | } | ||
33 | |||
34 | let lhs = expr.lhs()?; | ||
35 | let lhs_range = lhs.syntax().text_range(); | ||
36 | let not_lhs = invert_boolean_expression(lhs); | ||
37 | |||
38 | let rhs = expr.rhs()?; | ||
39 | let rhs_range = rhs.syntax().text_range(); | ||
40 | let not_rhs = invert_boolean_expression(rhs); | ||
41 | |||
42 | acc.add( | ||
43 | AssistId("apply_demorgan", AssistKind::RefactorRewrite), | ||
44 | "Apply De Morgan's law", | ||
45 | op_range, | ||
46 | |edit| { | ||
47 | edit.replace(op_range, opposite_op); | ||
48 | edit.replace(lhs_range, format!("!({}", not_lhs.syntax().text())); | ||
49 | edit.replace(rhs_range, format!("{})", not_rhs.syntax().text())); | ||
50 | }, | ||
51 | ) | ||
52 | } | ||
53 | |||
54 | // Return the opposite text for a given logical operator, if it makes sense | ||
55 | fn opposite_logic_op(kind: ast::BinOp) -> Option<&'static str> { | ||
56 | match kind { | ||
57 | ast::BinOp::BooleanOr => Some("&&"), | ||
58 | ast::BinOp::BooleanAnd => Some("||"), | ||
59 | _ => None, | ||
60 | } | ||
61 | } | ||
62 | |||
63 | #[cfg(test)] | ||
64 | mod tests { | ||
65 | use super::*; | ||
66 | |||
67 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
68 | |||
69 | #[test] | ||
70 | fn demorgan_turns_and_into_or() { | ||
71 | check_assist(apply_demorgan, "fn f() { !x &&<|> !x }", "fn f() { !(x || x) }") | ||
72 | } | ||
73 | |||
74 | #[test] | ||
75 | fn demorgan_turns_or_into_and() { | ||
76 | check_assist(apply_demorgan, "fn f() { !x ||<|> !x }", "fn f() { !(x && x) }") | ||
77 | } | ||
78 | |||
79 | #[test] | ||
80 | fn demorgan_removes_inequality() { | ||
81 | check_assist(apply_demorgan, "fn f() { x != x ||<|> !x }", "fn f() { !(x == x && x) }") | ||
82 | } | ||
83 | |||
84 | #[test] | ||
85 | fn demorgan_general_case() { | ||
86 | check_assist(apply_demorgan, "fn f() { x ||<|> x }", "fn f() { !(!x && !x) }") | ||
87 | } | ||
88 | |||
89 | #[test] | ||
90 | fn demorgan_doesnt_apply_with_cursor_not_on_op() { | ||
91 | check_assist_not_applicable(apply_demorgan, "fn f() { <|> !x || !x }") | ||
92 | } | ||
93 | } | ||
diff --git a/crates/ra_assists/src/handlers/auto_import.rs b/crates/ra_assists/src/handlers/auto_import.rs deleted file mode 100644 index 01e7b7a44..000000000 --- a/crates/ra_assists/src/handlers/auto_import.rs +++ /dev/null | |||
@@ -1,1089 +0,0 @@ | |||
1 | use std::collections::BTreeSet; | ||
2 | |||
3 | use either::Either; | ||
4 | use hir::{ | ||
5 | AsAssocItem, AssocItemContainer, ModPath, Module, ModuleDef, PathResolution, Semantics, Trait, | ||
6 | Type, | ||
7 | }; | ||
8 | use ra_ide_db::{imports_locator, RootDatabase}; | ||
9 | use ra_prof::profile; | ||
10 | use ra_syntax::{ | ||
11 | ast::{self, AstNode}, | ||
12 | SyntaxNode, | ||
13 | }; | ||
14 | use rustc_hash::FxHashSet; | ||
15 | |||
16 | use crate::{ | ||
17 | utils::insert_use_statement, AssistContext, AssistId, AssistKind, Assists, GroupLabel, | ||
18 | }; | ||
19 | |||
20 | // Assist: auto_import | ||
21 | // | ||
22 | // If the name is unresolved, provides all possible imports for it. | ||
23 | // | ||
24 | // ``` | ||
25 | // fn main() { | ||
26 | // let map = HashMap<|>::new(); | ||
27 | // } | ||
28 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | ||
29 | // ``` | ||
30 | // -> | ||
31 | // ``` | ||
32 | // use std::collections::HashMap; | ||
33 | // | ||
34 | // fn main() { | ||
35 | // let map = HashMap::new(); | ||
36 | // } | ||
37 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | ||
38 | // ``` | ||
39 | pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
40 | let auto_import_assets = AutoImportAssets::new(ctx)?; | ||
41 | let proposed_imports = auto_import_assets.search_for_imports(ctx); | ||
42 | if proposed_imports.is_empty() { | ||
43 | return None; | ||
44 | } | ||
45 | |||
46 | let range = ctx.sema.original_range(&auto_import_assets.syntax_under_caret).range; | ||
47 | let group = auto_import_assets.get_import_group_message(); | ||
48 | for import in proposed_imports { | ||
49 | acc.add_group( | ||
50 | &group, | ||
51 | AssistId("auto_import", AssistKind::QuickFix), | ||
52 | format!("Import `{}`", &import), | ||
53 | range, | ||
54 | |builder| { | ||
55 | insert_use_statement( | ||
56 | &auto_import_assets.syntax_under_caret, | ||
57 | &import, | ||
58 | ctx, | ||
59 | builder.text_edit_builder(), | ||
60 | ); | ||
61 | }, | ||
62 | ); | ||
63 | } | ||
64 | Some(()) | ||
65 | } | ||
66 | |||
67 | #[derive(Debug)] | ||
68 | struct AutoImportAssets { | ||
69 | import_candidate: ImportCandidate, | ||
70 | module_with_name_to_import: Module, | ||
71 | syntax_under_caret: SyntaxNode, | ||
72 | } | ||
73 | |||
74 | impl AutoImportAssets { | ||
75 | fn new(ctx: &AssistContext) -> Option<Self> { | ||
76 | if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() { | ||
77 | Self::for_regular_path(path_under_caret, &ctx) | ||
78 | } else { | ||
79 | Self::for_method_call(ctx.find_node_at_offset_with_descend()?, &ctx) | ||
80 | } | ||
81 | } | ||
82 | |||
83 | fn for_method_call(method_call: ast::MethodCallExpr, ctx: &AssistContext) -> Option<Self> { | ||
84 | let syntax_under_caret = method_call.syntax().to_owned(); | ||
85 | let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?; | ||
86 | Some(Self { | ||
87 | import_candidate: ImportCandidate::for_method_call(&ctx.sema, &method_call)?, | ||
88 | module_with_name_to_import, | ||
89 | syntax_under_caret, | ||
90 | }) | ||
91 | } | ||
92 | |||
93 | fn for_regular_path(path_under_caret: ast::Path, ctx: &AssistContext) -> Option<Self> { | ||
94 | let syntax_under_caret = path_under_caret.syntax().to_owned(); | ||
95 | if syntax_under_caret.ancestors().find_map(ast::Use::cast).is_some() { | ||
96 | return None; | ||
97 | } | ||
98 | |||
99 | let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?; | ||
100 | Some(Self { | ||
101 | import_candidate: ImportCandidate::for_regular_path(&ctx.sema, &path_under_caret)?, | ||
102 | module_with_name_to_import, | ||
103 | syntax_under_caret, | ||
104 | }) | ||
105 | } | ||
106 | |||
107 | fn get_search_query(&self) -> &str { | ||
108 | match &self.import_candidate { | ||
109 | ImportCandidate::UnqualifiedName(name) => name, | ||
110 | ImportCandidate::QualifierStart(qualifier_start) => qualifier_start, | ||
111 | ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => trait_assoc_item_name, | ||
112 | ImportCandidate::TraitMethod(_, trait_method_name) => trait_method_name, | ||
113 | } | ||
114 | } | ||
115 | |||
116 | fn get_import_group_message(&self) -> GroupLabel { | ||
117 | let name = match &self.import_candidate { | ||
118 | ImportCandidate::UnqualifiedName(name) => format!("Import {}", name), | ||
119 | ImportCandidate::QualifierStart(qualifier_start) => { | ||
120 | format!("Import {}", qualifier_start) | ||
121 | } | ||
122 | ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => { | ||
123 | format!("Import a trait for item {}", trait_assoc_item_name) | ||
124 | } | ||
125 | ImportCandidate::TraitMethod(_, trait_method_name) => { | ||
126 | format!("Import a trait for method {}", trait_method_name) | ||
127 | } | ||
128 | }; | ||
129 | GroupLabel(name) | ||
130 | } | ||
131 | |||
132 | fn search_for_imports(&self, ctx: &AssistContext) -> BTreeSet<ModPath> { | ||
133 | let _p = profile("auto_import::search_for_imports"); | ||
134 | let db = ctx.db(); | ||
135 | let current_crate = self.module_with_name_to_import.krate(); | ||
136 | imports_locator::find_imports(&ctx.sema, current_crate, &self.get_search_query()) | ||
137 | .into_iter() | ||
138 | .filter_map(|candidate| match &self.import_candidate { | ||
139 | ImportCandidate::TraitAssocItem(assoc_item_type, _) => { | ||
140 | let located_assoc_item = match candidate { | ||
141 | Either::Left(ModuleDef::Function(located_function)) => located_function | ||
142 | .as_assoc_item(db) | ||
143 | .map(|assoc| assoc.container(db)) | ||
144 | .and_then(Self::assoc_to_trait), | ||
145 | Either::Left(ModuleDef::Const(located_const)) => located_const | ||
146 | .as_assoc_item(db) | ||
147 | .map(|assoc| assoc.container(db)) | ||
148 | .and_then(Self::assoc_to_trait), | ||
149 | _ => None, | ||
150 | }?; | ||
151 | |||
152 | let mut trait_candidates = FxHashSet::default(); | ||
153 | trait_candidates.insert(located_assoc_item.into()); | ||
154 | |||
155 | assoc_item_type | ||
156 | .iterate_path_candidates( | ||
157 | db, | ||
158 | current_crate, | ||
159 | &trait_candidates, | ||
160 | None, | ||
161 | |_, assoc| Self::assoc_to_trait(assoc.container(db)), | ||
162 | ) | ||
163 | .map(ModuleDef::from) | ||
164 | .map(Either::Left) | ||
165 | } | ||
166 | ImportCandidate::TraitMethod(function_callee, _) => { | ||
167 | let located_assoc_item = | ||
168 | if let Either::Left(ModuleDef::Function(located_function)) = candidate { | ||
169 | located_function | ||
170 | .as_assoc_item(db) | ||
171 | .map(|assoc| assoc.container(db)) | ||
172 | .and_then(Self::assoc_to_trait) | ||
173 | } else { | ||
174 | None | ||
175 | }?; | ||
176 | |||
177 | let mut trait_candidates = FxHashSet::default(); | ||
178 | trait_candidates.insert(located_assoc_item.into()); | ||
179 | |||
180 | function_callee | ||
181 | .iterate_method_candidates( | ||
182 | db, | ||
183 | current_crate, | ||
184 | &trait_candidates, | ||
185 | None, | ||
186 | |_, function| { | ||
187 | Self::assoc_to_trait(function.as_assoc_item(db)?.container(db)) | ||
188 | }, | ||
189 | ) | ||
190 | .map(ModuleDef::from) | ||
191 | .map(Either::Left) | ||
192 | } | ||
193 | _ => Some(candidate), | ||
194 | }) | ||
195 | .filter_map(|candidate| match candidate { | ||
196 | Either::Left(module_def) => { | ||
197 | self.module_with_name_to_import.find_use_path(db, module_def) | ||
198 | } | ||
199 | Either::Right(macro_def) => { | ||
200 | self.module_with_name_to_import.find_use_path(db, macro_def) | ||
201 | } | ||
202 | }) | ||
203 | .filter(|use_path| !use_path.segments.is_empty()) | ||
204 | .take(20) | ||
205 | .collect::<BTreeSet<_>>() | ||
206 | } | ||
207 | |||
208 | fn assoc_to_trait(assoc: AssocItemContainer) -> Option<Trait> { | ||
209 | if let AssocItemContainer::Trait(extracted_trait) = assoc { | ||
210 | Some(extracted_trait) | ||
211 | } else { | ||
212 | None | ||
213 | } | ||
214 | } | ||
215 | } | ||
216 | |||
217 | #[derive(Debug)] | ||
218 | enum ImportCandidate { | ||
219 | /// Simple name like 'HashMap' | ||
220 | UnqualifiedName(String), | ||
221 | /// First part of the qualified name. | ||
222 | /// For 'std::collections::HashMap', that will be 'std'. | ||
223 | QualifierStart(String), | ||
224 | /// A trait associated function (with no self parameter) or associated constant. | ||
225 | /// For 'test_mod::TestEnum::test_function', `Type` is the `test_mod::TestEnum` expression type | ||
226 | /// and `String` is the `test_function` | ||
227 | TraitAssocItem(Type, String), | ||
228 | /// A trait method with self parameter. | ||
229 | /// For 'test_enum.test_method()', `Type` is the `test_enum` expression type | ||
230 | /// and `String` is the `test_method` | ||
231 | TraitMethod(Type, String), | ||
232 | } | ||
233 | |||
234 | impl ImportCandidate { | ||
235 | fn for_method_call( | ||
236 | sema: &Semantics<RootDatabase>, | ||
237 | method_call: &ast::MethodCallExpr, | ||
238 | ) -> Option<Self> { | ||
239 | if sema.resolve_method_call(method_call).is_some() { | ||
240 | return None; | ||
241 | } | ||
242 | Some(Self::TraitMethod( | ||
243 | sema.type_of_expr(&method_call.expr()?)?, | ||
244 | method_call.name_ref()?.syntax().to_string(), | ||
245 | )) | ||
246 | } | ||
247 | |||
248 | fn for_regular_path( | ||
249 | sema: &Semantics<RootDatabase>, | ||
250 | path_under_caret: &ast::Path, | ||
251 | ) -> Option<Self> { | ||
252 | if sema.resolve_path(path_under_caret).is_some() { | ||
253 | return None; | ||
254 | } | ||
255 | |||
256 | let segment = path_under_caret.segment()?; | ||
257 | if let Some(qualifier) = path_under_caret.qualifier() { | ||
258 | let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?; | ||
259 | let qualifier_start_path = | ||
260 | qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?; | ||
261 | if let Some(qualifier_start_resolution) = sema.resolve_path(&qualifier_start_path) { | ||
262 | let qualifier_resolution = if qualifier_start_path == qualifier { | ||
263 | qualifier_start_resolution | ||
264 | } else { | ||
265 | sema.resolve_path(&qualifier)? | ||
266 | }; | ||
267 | if let PathResolution::Def(ModuleDef::Adt(assoc_item_path)) = qualifier_resolution { | ||
268 | Some(ImportCandidate::TraitAssocItem( | ||
269 | assoc_item_path.ty(sema.db), | ||
270 | segment.syntax().to_string(), | ||
271 | )) | ||
272 | } else { | ||
273 | None | ||
274 | } | ||
275 | } else { | ||
276 | Some(ImportCandidate::QualifierStart(qualifier_start.syntax().to_string())) | ||
277 | } | ||
278 | } else { | ||
279 | Some(ImportCandidate::UnqualifiedName( | ||
280 | segment.syntax().descendants().find_map(ast::NameRef::cast)?.syntax().to_string(), | ||
281 | )) | ||
282 | } | ||
283 | } | ||
284 | } | ||
285 | |||
286 | #[cfg(test)] | ||
287 | mod tests { | ||
288 | use super::*; | ||
289 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
290 | |||
291 | #[test] | ||
292 | fn applicable_when_found_an_import() { | ||
293 | check_assist( | ||
294 | auto_import, | ||
295 | r" | ||
296 | <|>PubStruct | ||
297 | |||
298 | pub mod PubMod { | ||
299 | pub struct PubStruct; | ||
300 | } | ||
301 | ", | ||
302 | r" | ||
303 | use PubMod::PubStruct; | ||
304 | |||
305 | PubStruct | ||
306 | |||
307 | pub mod PubMod { | ||
308 | pub struct PubStruct; | ||
309 | } | ||
310 | ", | ||
311 | ); | ||
312 | } | ||
313 | |||
314 | #[test] | ||
315 | fn applicable_when_found_an_import_in_macros() { | ||
316 | check_assist( | ||
317 | auto_import, | ||
318 | r" | ||
319 | macro_rules! foo { | ||
320 | ($i:ident) => { fn foo(a: $i) {} } | ||
321 | } | ||
322 | foo!(Pub<|>Struct); | ||
323 | |||
324 | pub mod PubMod { | ||
325 | pub struct PubStruct; | ||
326 | } | ||
327 | ", | ||
328 | r" | ||
329 | use PubMod::PubStruct; | ||
330 | |||
331 | macro_rules! foo { | ||
332 | ($i:ident) => { fn foo(a: $i) {} } | ||
333 | } | ||
334 | foo!(PubStruct); | ||
335 | |||
336 | pub mod PubMod { | ||
337 | pub struct PubStruct; | ||
338 | } | ||
339 | ", | ||
340 | ); | ||
341 | } | ||
342 | |||
343 | #[test] | ||
344 | fn auto_imports_are_merged() { | ||
345 | check_assist( | ||
346 | auto_import, | ||
347 | r" | ||
348 | use PubMod::PubStruct1; | ||
349 | |||
350 | struct Test { | ||
351 | test: Pub<|>Struct2<u8>, | ||
352 | } | ||
353 | |||
354 | pub mod PubMod { | ||
355 | pub struct PubStruct1; | ||
356 | pub struct PubStruct2<T> { | ||
357 | _t: T, | ||
358 | } | ||
359 | } | ||
360 | ", | ||
361 | r" | ||
362 | use PubMod::{PubStruct2, PubStruct1}; | ||
363 | |||
364 | struct Test { | ||
365 | test: PubStruct2<u8>, | ||
366 | } | ||
367 | |||
368 | pub mod PubMod { | ||
369 | pub struct PubStruct1; | ||
370 | pub struct PubStruct2<T> { | ||
371 | _t: T, | ||
372 | } | ||
373 | } | ||
374 | ", | ||
375 | ); | ||
376 | } | ||
377 | |||
378 | #[test] | ||
379 | fn applicable_when_found_multiple_imports() { | ||
380 | check_assist( | ||
381 | auto_import, | ||
382 | r" | ||
383 | PubSt<|>ruct | ||
384 | |||
385 | pub mod PubMod1 { | ||
386 | pub struct PubStruct; | ||
387 | } | ||
388 | pub mod PubMod2 { | ||
389 | pub struct PubStruct; | ||
390 | } | ||
391 | pub mod PubMod3 { | ||
392 | pub struct PubStruct; | ||
393 | } | ||
394 | ", | ||
395 | r" | ||
396 | use PubMod3::PubStruct; | ||
397 | |||
398 | PubStruct | ||
399 | |||
400 | pub mod PubMod1 { | ||
401 | pub struct PubStruct; | ||
402 | } | ||
403 | pub mod PubMod2 { | ||
404 | pub struct PubStruct; | ||
405 | } | ||
406 | pub mod PubMod3 { | ||
407 | pub struct PubStruct; | ||
408 | } | ||
409 | ", | ||
410 | ); | ||
411 | } | ||
412 | |||
413 | #[test] | ||
414 | fn not_applicable_for_already_imported_types() { | ||
415 | check_assist_not_applicable( | ||
416 | auto_import, | ||
417 | r" | ||
418 | use PubMod::PubStruct; | ||
419 | |||
420 | PubStruct<|> | ||
421 | |||
422 | pub mod PubMod { | ||
423 | pub struct PubStruct; | ||
424 | } | ||
425 | ", | ||
426 | ); | ||
427 | } | ||
428 | |||
429 | #[test] | ||
430 | fn not_applicable_for_types_with_private_paths() { | ||
431 | check_assist_not_applicable( | ||
432 | auto_import, | ||
433 | r" | ||
434 | PrivateStruct<|> | ||
435 | |||
436 | pub mod PubMod { | ||
437 | struct PrivateStruct; | ||
438 | } | ||
439 | ", | ||
440 | ); | ||
441 | } | ||
442 | |||
443 | #[test] | ||
444 | fn not_applicable_when_no_imports_found() { | ||
445 | check_assist_not_applicable( | ||
446 | auto_import, | ||
447 | " | ||
448 | PubStruct<|>", | ||
449 | ); | ||
450 | } | ||
451 | |||
452 | #[test] | ||
453 | fn not_applicable_in_import_statements() { | ||
454 | check_assist_not_applicable( | ||
455 | auto_import, | ||
456 | r" | ||
457 | use PubStruct<|>; | ||
458 | |||
459 | pub mod PubMod { | ||
460 | pub struct PubStruct; | ||
461 | }", | ||
462 | ); | ||
463 | } | ||
464 | |||
465 | #[test] | ||
466 | fn function_import() { | ||
467 | check_assist( | ||
468 | auto_import, | ||
469 | r" | ||
470 | test_function<|> | ||
471 | |||
472 | pub mod PubMod { | ||
473 | pub fn test_function() {}; | ||
474 | } | ||
475 | ", | ||
476 | r" | ||
477 | use PubMod::test_function; | ||
478 | |||
479 | test_function | ||
480 | |||
481 | pub mod PubMod { | ||
482 | pub fn test_function() {}; | ||
483 | } | ||
484 | ", | ||
485 | ); | ||
486 | } | ||
487 | |||
488 | #[test] | ||
489 | fn macro_import() { | ||
490 | check_assist( | ||
491 | auto_import, | ||
492 | r" | ||
493 | //- /lib.rs crate:crate_with_macro | ||
494 | #[macro_export] | ||
495 | macro_rules! foo { | ||
496 | () => () | ||
497 | } | ||
498 | |||
499 | //- /main.rs crate:main deps:crate_with_macro | ||
500 | fn main() { | ||
501 | foo<|> | ||
502 | } | ||
503 | ", | ||
504 | r"use crate_with_macro::foo; | ||
505 | |||
506 | fn main() { | ||
507 | foo | ||
508 | } | ||
509 | ", | ||
510 | ); | ||
511 | } | ||
512 | |||
513 | #[test] | ||
514 | fn auto_import_target() { | ||
515 | check_assist_target( | ||
516 | auto_import, | ||
517 | r" | ||
518 | struct AssistInfo { | ||
519 | group_label: Option<<|>GroupLabel>, | ||
520 | } | ||
521 | |||
522 | mod m { pub struct GroupLabel; } | ||
523 | ", | ||
524 | "GroupLabel", | ||
525 | ) | ||
526 | } | ||
527 | |||
528 | #[test] | ||
529 | fn not_applicable_when_path_start_is_imported() { | ||
530 | check_assist_not_applicable( | ||
531 | auto_import, | ||
532 | r" | ||
533 | pub mod mod1 { | ||
534 | pub mod mod2 { | ||
535 | pub mod mod3 { | ||
536 | pub struct TestStruct; | ||
537 | } | ||
538 | } | ||
539 | } | ||
540 | |||
541 | use mod1::mod2; | ||
542 | fn main() { | ||
543 | mod2::mod3::TestStruct<|> | ||
544 | } | ||
545 | ", | ||
546 | ); | ||
547 | } | ||
548 | |||
549 | #[test] | ||
550 | fn not_applicable_for_imported_function() { | ||
551 | check_assist_not_applicable( | ||
552 | auto_import, | ||
553 | r" | ||
554 | pub mod test_mod { | ||
555 | pub fn test_function() {} | ||
556 | } | ||
557 | |||
558 | use test_mod::test_function; | ||
559 | fn main() { | ||
560 | test_function<|> | ||
561 | } | ||
562 | ", | ||
563 | ); | ||
564 | } | ||
565 | |||
566 | #[test] | ||
567 | fn associated_struct_function() { | ||
568 | check_assist( | ||
569 | auto_import, | ||
570 | r" | ||
571 | mod test_mod { | ||
572 | pub struct TestStruct {} | ||
573 | impl TestStruct { | ||
574 | pub fn test_function() {} | ||
575 | } | ||
576 | } | ||
577 | |||
578 | fn main() { | ||
579 | TestStruct::test_function<|> | ||
580 | } | ||
581 | ", | ||
582 | r" | ||
583 | use test_mod::TestStruct; | ||
584 | |||
585 | mod test_mod { | ||
586 | pub struct TestStruct {} | ||
587 | impl TestStruct { | ||
588 | pub fn test_function() {} | ||
589 | } | ||
590 | } | ||
591 | |||
592 | fn main() { | ||
593 | TestStruct::test_function | ||
594 | } | ||
595 | ", | ||
596 | ); | ||
597 | } | ||
598 | |||
599 | #[test] | ||
600 | fn associated_struct_const() { | ||
601 | check_assist( | ||
602 | auto_import, | ||
603 | r" | ||
604 | mod test_mod { | ||
605 | pub struct TestStruct {} | ||
606 | impl TestStruct { | ||
607 | const TEST_CONST: u8 = 42; | ||
608 | } | ||
609 | } | ||
610 | |||
611 | fn main() { | ||
612 | TestStruct::TEST_CONST<|> | ||
613 | } | ||
614 | ", | ||
615 | r" | ||
616 | use test_mod::TestStruct; | ||
617 | |||
618 | mod test_mod { | ||
619 | pub struct TestStruct {} | ||
620 | impl TestStruct { | ||
621 | const TEST_CONST: u8 = 42; | ||
622 | } | ||
623 | } | ||
624 | |||
625 | fn main() { | ||
626 | TestStruct::TEST_CONST | ||
627 | } | ||
628 | ", | ||
629 | ); | ||
630 | } | ||
631 | |||
632 | #[test] | ||
633 | fn associated_trait_function() { | ||
634 | check_assist( | ||
635 | auto_import, | ||
636 | r" | ||
637 | mod test_mod { | ||
638 | pub trait TestTrait { | ||
639 | fn test_function(); | ||
640 | } | ||
641 | pub struct TestStruct {} | ||
642 | impl TestTrait for TestStruct { | ||
643 | fn test_function() {} | ||
644 | } | ||
645 | } | ||
646 | |||
647 | fn main() { | ||
648 | test_mod::TestStruct::test_function<|> | ||
649 | } | ||
650 | ", | ||
651 | r" | ||
652 | use test_mod::TestTrait; | ||
653 | |||
654 | mod test_mod { | ||
655 | pub trait TestTrait { | ||
656 | fn test_function(); | ||
657 | } | ||
658 | pub struct TestStruct {} | ||
659 | impl TestTrait for TestStruct { | ||
660 | fn test_function() {} | ||
661 | } | ||
662 | } | ||
663 | |||
664 | fn main() { | ||
665 | test_mod::TestStruct::test_function | ||
666 | } | ||
667 | ", | ||
668 | ); | ||
669 | } | ||
670 | |||
671 | #[test] | ||
672 | fn not_applicable_for_imported_trait_for_function() { | ||
673 | check_assist_not_applicable( | ||
674 | auto_import, | ||
675 | r" | ||
676 | mod test_mod { | ||
677 | pub trait TestTrait { | ||
678 | fn test_function(); | ||
679 | } | ||
680 | pub trait TestTrait2 { | ||
681 | fn test_function(); | ||
682 | } | ||
683 | pub enum TestEnum { | ||
684 | One, | ||
685 | Two, | ||
686 | } | ||
687 | impl TestTrait2 for TestEnum { | ||
688 | fn test_function() {} | ||
689 | } | ||
690 | impl TestTrait for TestEnum { | ||
691 | fn test_function() {} | ||
692 | } | ||
693 | } | ||
694 | |||
695 | use test_mod::TestTrait2; | ||
696 | fn main() { | ||
697 | test_mod::TestEnum::test_function<|>; | ||
698 | } | ||
699 | ", | ||
700 | ) | ||
701 | } | ||
702 | |||
703 | #[test] | ||
704 | fn associated_trait_const() { | ||
705 | check_assist( | ||
706 | auto_import, | ||
707 | r" | ||
708 | mod test_mod { | ||
709 | pub trait TestTrait { | ||
710 | const TEST_CONST: u8; | ||
711 | } | ||
712 | pub struct TestStruct {} | ||
713 | impl TestTrait for TestStruct { | ||
714 | const TEST_CONST: u8 = 42; | ||
715 | } | ||
716 | } | ||
717 | |||
718 | fn main() { | ||
719 | test_mod::TestStruct::TEST_CONST<|> | ||
720 | } | ||
721 | ", | ||
722 | r" | ||
723 | use test_mod::TestTrait; | ||
724 | |||
725 | mod test_mod { | ||
726 | pub trait TestTrait { | ||
727 | const TEST_CONST: u8; | ||
728 | } | ||
729 | pub struct TestStruct {} | ||
730 | impl TestTrait for TestStruct { | ||
731 | const TEST_CONST: u8 = 42; | ||
732 | } | ||
733 | } | ||
734 | |||
735 | fn main() { | ||
736 | test_mod::TestStruct::TEST_CONST | ||
737 | } | ||
738 | ", | ||
739 | ); | ||
740 | } | ||
741 | |||
742 | #[test] | ||
743 | fn not_applicable_for_imported_trait_for_const() { | ||
744 | check_assist_not_applicable( | ||
745 | auto_import, | ||
746 | r" | ||
747 | mod test_mod { | ||
748 | pub trait TestTrait { | ||
749 | const TEST_CONST: u8; | ||
750 | } | ||
751 | pub trait TestTrait2 { | ||
752 | const TEST_CONST: f64; | ||
753 | } | ||
754 | pub enum TestEnum { | ||
755 | One, | ||
756 | Two, | ||
757 | } | ||
758 | impl TestTrait2 for TestEnum { | ||
759 | const TEST_CONST: f64 = 42.0; | ||
760 | } | ||
761 | impl TestTrait for TestEnum { | ||
762 | const TEST_CONST: u8 = 42; | ||
763 | } | ||
764 | } | ||
765 | |||
766 | use test_mod::TestTrait2; | ||
767 | fn main() { | ||
768 | test_mod::TestEnum::TEST_CONST<|>; | ||
769 | } | ||
770 | ", | ||
771 | ) | ||
772 | } | ||
773 | |||
774 | #[test] | ||
775 | fn trait_method() { | ||
776 | check_assist( | ||
777 | auto_import, | ||
778 | r" | ||
779 | mod test_mod { | ||
780 | pub trait TestTrait { | ||
781 | fn test_method(&self); | ||
782 | } | ||
783 | pub struct TestStruct {} | ||
784 | impl TestTrait for TestStruct { | ||
785 | fn test_method(&self) {} | ||
786 | } | ||
787 | } | ||
788 | |||
789 | fn main() { | ||
790 | let test_struct = test_mod::TestStruct {}; | ||
791 | test_struct.test_meth<|>od() | ||
792 | } | ||
793 | ", | ||
794 | r" | ||
795 | use test_mod::TestTrait; | ||
796 | |||
797 | mod test_mod { | ||
798 | pub trait TestTrait { | ||
799 | fn test_method(&self); | ||
800 | } | ||
801 | pub struct TestStruct {} | ||
802 | impl TestTrait for TestStruct { | ||
803 | fn test_method(&self) {} | ||
804 | } | ||
805 | } | ||
806 | |||
807 | fn main() { | ||
808 | let test_struct = test_mod::TestStruct {}; | ||
809 | test_struct.test_method() | ||
810 | } | ||
811 | ", | ||
812 | ); | ||
813 | } | ||
814 | |||
815 | #[test] | ||
816 | fn trait_method_cross_crate() { | ||
817 | check_assist( | ||
818 | auto_import, | ||
819 | r" | ||
820 | //- /main.rs crate:main deps:dep | ||
821 | fn main() { | ||
822 | let test_struct = dep::test_mod::TestStruct {}; | ||
823 | test_struct.test_meth<|>od() | ||
824 | } | ||
825 | //- /dep.rs crate:dep | ||
826 | pub mod test_mod { | ||
827 | pub trait TestTrait { | ||
828 | fn test_method(&self); | ||
829 | } | ||
830 | pub struct TestStruct {} | ||
831 | impl TestTrait for TestStruct { | ||
832 | fn test_method(&self) {} | ||
833 | } | ||
834 | } | ||
835 | ", | ||
836 | r" | ||
837 | use dep::test_mod::TestTrait; | ||
838 | |||
839 | fn main() { | ||
840 | let test_struct = dep::test_mod::TestStruct {}; | ||
841 | test_struct.test_method() | ||
842 | } | ||
843 | ", | ||
844 | ); | ||
845 | } | ||
846 | |||
847 | #[test] | ||
848 | fn assoc_fn_cross_crate() { | ||
849 | check_assist( | ||
850 | auto_import, | ||
851 | r" | ||
852 | //- /main.rs crate:main deps:dep | ||
853 | fn main() { | ||
854 | dep::test_mod::TestStruct::test_func<|>tion | ||
855 | } | ||
856 | //- /dep.rs crate:dep | ||
857 | pub mod test_mod { | ||
858 | pub trait TestTrait { | ||
859 | fn test_function(); | ||
860 | } | ||
861 | pub struct TestStruct {} | ||
862 | impl TestTrait for TestStruct { | ||
863 | fn test_function() {} | ||
864 | } | ||
865 | } | ||
866 | ", | ||
867 | r" | ||
868 | use dep::test_mod::TestTrait; | ||
869 | |||
870 | fn main() { | ||
871 | dep::test_mod::TestStruct::test_function | ||
872 | } | ||
873 | ", | ||
874 | ); | ||
875 | } | ||
876 | |||
877 | #[test] | ||
878 | fn assoc_const_cross_crate() { | ||
879 | check_assist( | ||
880 | auto_import, | ||
881 | r" | ||
882 | //- /main.rs crate:main deps:dep | ||
883 | fn main() { | ||
884 | dep::test_mod::TestStruct::CONST<|> | ||
885 | } | ||
886 | //- /dep.rs crate:dep | ||
887 | pub mod test_mod { | ||
888 | pub trait TestTrait { | ||
889 | const CONST: bool; | ||
890 | } | ||
891 | pub struct TestStruct {} | ||
892 | impl TestTrait for TestStruct { | ||
893 | const CONST: bool = true; | ||
894 | } | ||
895 | } | ||
896 | ", | ||
897 | r" | ||
898 | use dep::test_mod::TestTrait; | ||
899 | |||
900 | fn main() { | ||
901 | dep::test_mod::TestStruct::CONST | ||
902 | } | ||
903 | ", | ||
904 | ); | ||
905 | } | ||
906 | |||
907 | #[test] | ||
908 | fn assoc_fn_as_method_cross_crate() { | ||
909 | check_assist_not_applicable( | ||
910 | auto_import, | ||
911 | r" | ||
912 | //- /main.rs crate:main deps:dep | ||
913 | fn main() { | ||
914 | let test_struct = dep::test_mod::TestStruct {}; | ||
915 | test_struct.test_func<|>tion() | ||
916 | } | ||
917 | //- /dep.rs crate:dep | ||
918 | pub mod test_mod { | ||
919 | pub trait TestTrait { | ||
920 | fn test_function(); | ||
921 | } | ||
922 | pub struct TestStruct {} | ||
923 | impl TestTrait for TestStruct { | ||
924 | fn test_function() {} | ||
925 | } | ||
926 | } | ||
927 | ", | ||
928 | ); | ||
929 | } | ||
930 | |||
931 | #[test] | ||
932 | fn private_trait_cross_crate() { | ||
933 | check_assist_not_applicable( | ||
934 | auto_import, | ||
935 | r" | ||
936 | //- /main.rs crate:main deps:dep | ||
937 | fn main() { | ||
938 | let test_struct = dep::test_mod::TestStruct {}; | ||
939 | test_struct.test_meth<|>od() | ||
940 | } | ||
941 | //- /dep.rs crate:dep | ||
942 | pub mod test_mod { | ||
943 | trait TestTrait { | ||
944 | fn test_method(&self); | ||
945 | } | ||
946 | pub struct TestStruct {} | ||
947 | impl TestTrait for TestStruct { | ||
948 | fn test_method(&self) {} | ||
949 | } | ||
950 | } | ||
951 | ", | ||
952 | ); | ||
953 | } | ||
954 | |||
955 | #[test] | ||
956 | fn not_applicable_for_imported_trait_for_method() { | ||
957 | check_assist_not_applicable( | ||
958 | auto_import, | ||
959 | r" | ||
960 | mod test_mod { | ||
961 | pub trait TestTrait { | ||
962 | fn test_method(&self); | ||
963 | } | ||
964 | pub trait TestTrait2 { | ||
965 | fn test_method(&self); | ||
966 | } | ||
967 | pub enum TestEnum { | ||
968 | One, | ||
969 | Two, | ||
970 | } | ||
971 | impl TestTrait2 for TestEnum { | ||
972 | fn test_method(&self) {} | ||
973 | } | ||
974 | impl TestTrait for TestEnum { | ||
975 | fn test_method(&self) {} | ||
976 | } | ||
977 | } | ||
978 | |||
979 | use test_mod::TestTrait2; | ||
980 | fn main() { | ||
981 | let one = test_mod::TestEnum::One; | ||
982 | one.test<|>_method(); | ||
983 | } | ||
984 | ", | ||
985 | ) | ||
986 | } | ||
987 | |||
988 | #[test] | ||
989 | fn dep_import() { | ||
990 | check_assist( | ||
991 | auto_import, | ||
992 | r" | ||
993 | //- /lib.rs crate:dep | ||
994 | pub struct Struct; | ||
995 | |||
996 | //- /main.rs crate:main deps:dep | ||
997 | fn main() { | ||
998 | Struct<|> | ||
999 | } | ||
1000 | ", | ||
1001 | r"use dep::Struct; | ||
1002 | |||
1003 | fn main() { | ||
1004 | Struct | ||
1005 | } | ||
1006 | ", | ||
1007 | ); | ||
1008 | } | ||
1009 | |||
1010 | #[test] | ||
1011 | fn whole_segment() { | ||
1012 | // Tests that only imports whose last segment matches the identifier get suggested. | ||
1013 | check_assist( | ||
1014 | auto_import, | ||
1015 | r" | ||
1016 | //- /lib.rs crate:dep | ||
1017 | pub mod fmt { | ||
1018 | pub trait Display {} | ||
1019 | } | ||
1020 | |||
1021 | pub fn panic_fmt() {} | ||
1022 | |||
1023 | //- /main.rs crate:main deps:dep | ||
1024 | struct S; | ||
1025 | |||
1026 | impl f<|>mt::Display for S {} | ||
1027 | ", | ||
1028 | r"use dep::fmt; | ||
1029 | |||
1030 | struct S; | ||
1031 | |||
1032 | impl fmt::Display for S {} | ||
1033 | ", | ||
1034 | ); | ||
1035 | } | ||
1036 | |||
1037 | #[test] | ||
1038 | fn macro_generated() { | ||
1039 | // Tests that macro-generated items are suggested from external crates. | ||
1040 | check_assist( | ||
1041 | auto_import, | ||
1042 | r" | ||
1043 | //- /lib.rs crate:dep | ||
1044 | macro_rules! mac { | ||
1045 | () => { | ||
1046 | pub struct Cheese; | ||
1047 | }; | ||
1048 | } | ||
1049 | |||
1050 | mac!(); | ||
1051 | |||
1052 | //- /main.rs crate:main deps:dep | ||
1053 | fn main() { | ||
1054 | Cheese<|>; | ||
1055 | } | ||
1056 | ", | ||
1057 | r"use dep::Cheese; | ||
1058 | |||
1059 | fn main() { | ||
1060 | Cheese; | ||
1061 | } | ||
1062 | ", | ||
1063 | ); | ||
1064 | } | ||
1065 | |||
1066 | #[test] | ||
1067 | fn casing() { | ||
1068 | // Tests that differently cased names don't interfere and we only suggest the matching one. | ||
1069 | check_assist( | ||
1070 | auto_import, | ||
1071 | r" | ||
1072 | //- /lib.rs crate:dep | ||
1073 | pub struct FMT; | ||
1074 | pub struct fmt; | ||
1075 | |||
1076 | //- /main.rs crate:main deps:dep | ||
1077 | fn main() { | ||
1078 | FMT<|>; | ||
1079 | } | ||
1080 | ", | ||
1081 | r"use dep::FMT; | ||
1082 | |||
1083 | fn main() { | ||
1084 | FMT; | ||
1085 | } | ||
1086 | ", | ||
1087 | ); | ||
1088 | } | ||
1089 | } | ||
diff --git a/crates/ra_assists/src/handlers/change_return_type_to_result.rs b/crates/ra_assists/src/handlers/change_return_type_to_result.rs deleted file mode 100644 index b83c94404..000000000 --- a/crates/ra_assists/src/handlers/change_return_type_to_result.rs +++ /dev/null | |||
@@ -1,991 +0,0 @@ | |||
1 | use ra_syntax::{ | ||
2 | ast::{self, BlockExpr, Expr, LoopBodyOwner}, | ||
3 | AstNode, SyntaxNode, | ||
4 | }; | ||
5 | |||
6 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
7 | use test_utils::mark; | ||
8 | |||
9 | // Assist: change_return_type_to_result | ||
10 | // | ||
11 | // Change the function's return type to Result. | ||
12 | // | ||
13 | // ``` | ||
14 | // fn foo() -> i32<|> { 42i32 } | ||
15 | // ``` | ||
16 | // -> | ||
17 | // ``` | ||
18 | // fn foo() -> Result<i32, ${0:_}> { Ok(42i32) } | ||
19 | // ``` | ||
20 | pub(crate) fn change_return_type_to_result(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
21 | let ret_type = ctx.find_node_at_offset::<ast::RetType>()?; | ||
22 | // FIXME: extend to lambdas as well | ||
23 | let fn_def = ret_type.syntax().parent().and_then(ast::Fn::cast)?; | ||
24 | |||
25 | let type_ref = &ret_type.ty()?; | ||
26 | let ret_type_str = type_ref.syntax().text().to_string(); | ||
27 | let first_part_ret_type = ret_type_str.splitn(2, '<').next(); | ||
28 | if let Some(ret_type_first_part) = first_part_ret_type { | ||
29 | if ret_type_first_part.ends_with("Result") { | ||
30 | mark::hit!(change_return_type_to_result_simple_return_type_already_result); | ||
31 | return None; | ||
32 | } | ||
33 | } | ||
34 | |||
35 | let block_expr = &fn_def.body()?; | ||
36 | |||
37 | acc.add( | ||
38 | AssistId("change_return_type_to_result", AssistKind::RefactorRewrite), | ||
39 | "Wrap return type in Result", | ||
40 | type_ref.syntax().text_range(), | ||
41 | |builder| { | ||
42 | let mut tail_return_expr_collector = TailReturnCollector::new(); | ||
43 | tail_return_expr_collector.collect_jump_exprs(block_expr, false); | ||
44 | tail_return_expr_collector.collect_tail_exprs(block_expr); | ||
45 | |||
46 | for ret_expr_arg in tail_return_expr_collector.exprs_to_wrap { | ||
47 | builder.replace_node_and_indent(&ret_expr_arg, format!("Ok({})", ret_expr_arg)); | ||
48 | } | ||
49 | |||
50 | match ctx.config.snippet_cap { | ||
51 | Some(cap) => { | ||
52 | let snippet = format!("Result<{}, ${{0:_}}>", type_ref); | ||
53 | builder.replace_snippet(cap, type_ref.syntax().text_range(), snippet) | ||
54 | } | ||
55 | None => builder | ||
56 | .replace(type_ref.syntax().text_range(), format!("Result<{}, _>", type_ref)), | ||
57 | } | ||
58 | }, | ||
59 | ) | ||
60 | } | ||
61 | |||
62 | struct TailReturnCollector { | ||
63 | exprs_to_wrap: Vec<SyntaxNode>, | ||
64 | } | ||
65 | |||
66 | impl TailReturnCollector { | ||
67 | fn new() -> Self { | ||
68 | Self { exprs_to_wrap: vec![] } | ||
69 | } | ||
70 | /// Collect all`return` expression | ||
71 | fn collect_jump_exprs(&mut self, block_expr: &BlockExpr, collect_break: bool) { | ||
72 | let statements = block_expr.statements(); | ||
73 | for stmt in statements { | ||
74 | let expr = match &stmt { | ||
75 | ast::Stmt::ExprStmt(stmt) => stmt.expr(), | ||
76 | ast::Stmt::LetStmt(stmt) => stmt.initializer(), | ||
77 | ast::Stmt::Item(_) => continue, | ||
78 | }; | ||
79 | if let Some(expr) = &expr { | ||
80 | self.handle_exprs(expr, collect_break); | ||
81 | } | ||
82 | } | ||
83 | |||
84 | // Browse tail expressions for each block | ||
85 | if let Some(expr) = block_expr.expr() { | ||
86 | if let Some(last_exprs) = get_tail_expr_from_block(&expr) { | ||
87 | for last_expr in last_exprs { | ||
88 | let last_expr = match last_expr { | ||
89 | NodeType::Node(expr) | NodeType::Leaf(expr) => expr, | ||
90 | }; | ||
91 | |||
92 | if let Some(last_expr) = Expr::cast(last_expr.clone()) { | ||
93 | self.handle_exprs(&last_expr, collect_break); | ||
94 | } else if let Some(expr_stmt) = ast::Stmt::cast(last_expr) { | ||
95 | let expr_stmt = match &expr_stmt { | ||
96 | ast::Stmt::ExprStmt(stmt) => stmt.expr(), | ||
97 | ast::Stmt::LetStmt(stmt) => stmt.initializer(), | ||
98 | ast::Stmt::Item(_) => None, | ||
99 | }; | ||
100 | if let Some(expr) = &expr_stmt { | ||
101 | self.handle_exprs(expr, collect_break); | ||
102 | } | ||
103 | } | ||
104 | } | ||
105 | } | ||
106 | } | ||
107 | } | ||
108 | |||
109 | fn handle_exprs(&mut self, expr: &Expr, collect_break: bool) { | ||
110 | match expr { | ||
111 | Expr::BlockExpr(block_expr) => { | ||
112 | self.collect_jump_exprs(&block_expr, collect_break); | ||
113 | } | ||
114 | Expr::ReturnExpr(ret_expr) => { | ||
115 | if let Some(ret_expr_arg) = &ret_expr.expr() { | ||
116 | self.exprs_to_wrap.push(ret_expr_arg.syntax().clone()); | ||
117 | } | ||
118 | } | ||
119 | Expr::BreakExpr(break_expr) if collect_break => { | ||
120 | if let Some(break_expr_arg) = &break_expr.expr() { | ||
121 | self.exprs_to_wrap.push(break_expr_arg.syntax().clone()); | ||
122 | } | ||
123 | } | ||
124 | Expr::IfExpr(if_expr) => { | ||
125 | for block in if_expr.blocks() { | ||
126 | self.collect_jump_exprs(&block, collect_break); | ||
127 | } | ||
128 | } | ||
129 | Expr::LoopExpr(loop_expr) => { | ||
130 | if let Some(block_expr) = loop_expr.loop_body() { | ||
131 | self.collect_jump_exprs(&block_expr, collect_break); | ||
132 | } | ||
133 | } | ||
134 | Expr::ForExpr(for_expr) => { | ||
135 | if let Some(block_expr) = for_expr.loop_body() { | ||
136 | self.collect_jump_exprs(&block_expr, collect_break); | ||
137 | } | ||
138 | } | ||
139 | Expr::WhileExpr(while_expr) => { | ||
140 | if let Some(block_expr) = while_expr.loop_body() { | ||
141 | self.collect_jump_exprs(&block_expr, collect_break); | ||
142 | } | ||
143 | } | ||
144 | Expr::MatchExpr(match_expr) => { | ||
145 | if let Some(arm_list) = match_expr.match_arm_list() { | ||
146 | arm_list.arms().filter_map(|match_arm| match_arm.expr()).for_each(|expr| { | ||
147 | self.handle_exprs(&expr, collect_break); | ||
148 | }); | ||
149 | } | ||
150 | } | ||
151 | _ => {} | ||
152 | } | ||
153 | } | ||
154 | |||
155 | fn collect_tail_exprs(&mut self, block: &BlockExpr) { | ||
156 | if let Some(expr) = block.expr() { | ||
157 | self.handle_exprs(&expr, true); | ||
158 | self.fetch_tail_exprs(&expr); | ||
159 | } | ||
160 | } | ||
161 | |||
162 | fn fetch_tail_exprs(&mut self, expr: &Expr) { | ||
163 | if let Some(exprs) = get_tail_expr_from_block(expr) { | ||
164 | for node_type in &exprs { | ||
165 | match node_type { | ||
166 | NodeType::Leaf(expr) => { | ||
167 | self.exprs_to_wrap.push(expr.clone()); | ||
168 | } | ||
169 | NodeType::Node(expr) => match &Expr::cast(expr.clone()) { | ||
170 | Some(last_expr) => { | ||
171 | self.fetch_tail_exprs(last_expr); | ||
172 | } | ||
173 | None => { | ||
174 | self.exprs_to_wrap.push(expr.clone()); | ||
175 | } | ||
176 | }, | ||
177 | } | ||
178 | } | ||
179 | } | ||
180 | } | ||
181 | } | ||
182 | |||
183 | #[derive(Debug)] | ||
184 | enum NodeType { | ||
185 | Leaf(SyntaxNode), | ||
186 | Node(SyntaxNode), | ||
187 | } | ||
188 | |||
189 | /// Get a tail expression inside a block | ||
190 | fn get_tail_expr_from_block(expr: &Expr) -> Option<Vec<NodeType>> { | ||
191 | match expr { | ||
192 | Expr::IfExpr(if_expr) => { | ||
193 | let mut nodes = vec![]; | ||
194 | for block in if_expr.blocks() { | ||
195 | if let Some(block_expr) = block.expr() { | ||
196 | if let Some(tail_exprs) = get_tail_expr_from_block(&block_expr) { | ||
197 | nodes.extend(tail_exprs); | ||
198 | } | ||
199 | } else if let Some(last_expr) = block.syntax().last_child() { | ||
200 | nodes.push(NodeType::Node(last_expr)); | ||
201 | } else { | ||
202 | nodes.push(NodeType::Node(block.syntax().clone())); | ||
203 | } | ||
204 | } | ||
205 | Some(nodes) | ||
206 | } | ||
207 | Expr::LoopExpr(loop_expr) => { | ||
208 | loop_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) | ||
209 | } | ||
210 | Expr::ForExpr(for_expr) => { | ||
211 | for_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) | ||
212 | } | ||
213 | Expr::WhileExpr(while_expr) => { | ||
214 | while_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) | ||
215 | } | ||
216 | Expr::BlockExpr(block_expr) => { | ||
217 | block_expr.expr().map(|lc| vec![NodeType::Node(lc.syntax().clone())]) | ||
218 | } | ||
219 | Expr::MatchExpr(match_expr) => { | ||
220 | let arm_list = match_expr.match_arm_list()?; | ||
221 | let arms: Vec<NodeType> = arm_list | ||
222 | .arms() | ||
223 | .filter_map(|match_arm| match_arm.expr()) | ||
224 | .map(|expr| match expr { | ||
225 | Expr::ReturnExpr(ret_expr) => NodeType::Node(ret_expr.syntax().clone()), | ||
226 | Expr::BreakExpr(break_expr) => NodeType::Node(break_expr.syntax().clone()), | ||
227 | _ => match expr.syntax().last_child() { | ||
228 | Some(last_expr) => NodeType::Node(last_expr), | ||
229 | None => NodeType::Node(expr.syntax().clone()), | ||
230 | }, | ||
231 | }) | ||
232 | .collect(); | ||
233 | |||
234 | Some(arms) | ||
235 | } | ||
236 | Expr::BreakExpr(expr) => expr.expr().map(|e| vec![NodeType::Leaf(e.syntax().clone())]), | ||
237 | Expr::ReturnExpr(ret_expr) => Some(vec![NodeType::Node(ret_expr.syntax().clone())]), | ||
238 | Expr::CallExpr(call_expr) => Some(vec![NodeType::Leaf(call_expr.syntax().clone())]), | ||
239 | Expr::Literal(lit_expr) => Some(vec![NodeType::Leaf(lit_expr.syntax().clone())]), | ||
240 | Expr::TupleExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
241 | Expr::ArrayExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
242 | Expr::ParenExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
243 | Expr::PathExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
244 | Expr::RecordExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
245 | Expr::IndexExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
246 | Expr::MethodCallExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
247 | Expr::AwaitExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
248 | Expr::CastExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
249 | Expr::RefExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
250 | Expr::PrefixExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
251 | Expr::RangeExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
252 | Expr::BinExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
253 | Expr::MacroCall(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
254 | Expr::BoxExpr(expr) => Some(vec![NodeType::Leaf(expr.syntax().clone())]), | ||
255 | _ => None, | ||
256 | } | ||
257 | } | ||
258 | |||
259 | #[cfg(test)] | ||
260 | mod tests { | ||
261 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
262 | |||
263 | use super::*; | ||
264 | |||
265 | #[test] | ||
266 | fn change_return_type_to_result_simple() { | ||
267 | check_assist( | ||
268 | change_return_type_to_result, | ||
269 | r#"fn foo() -> i3<|>2 { | ||
270 | let test = "test"; | ||
271 | return 42i32; | ||
272 | }"#, | ||
273 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
274 | let test = "test"; | ||
275 | return Ok(42i32); | ||
276 | }"#, | ||
277 | ); | ||
278 | } | ||
279 | |||
280 | #[test] | ||
281 | fn change_return_type_to_result_simple_return_type() { | ||
282 | check_assist( | ||
283 | change_return_type_to_result, | ||
284 | r#"fn foo() -> i32<|> { | ||
285 | let test = "test"; | ||
286 | return 42i32; | ||
287 | }"#, | ||
288 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
289 | let test = "test"; | ||
290 | return Ok(42i32); | ||
291 | }"#, | ||
292 | ); | ||
293 | } | ||
294 | |||
295 | #[test] | ||
296 | fn change_return_type_to_result_simple_return_type_bad_cursor() { | ||
297 | check_assist_not_applicable( | ||
298 | change_return_type_to_result, | ||
299 | r#"fn foo() -> i32 { | ||
300 | let test = "test";<|> | ||
301 | return 42i32; | ||
302 | }"#, | ||
303 | ); | ||
304 | } | ||
305 | |||
306 | #[test] | ||
307 | fn change_return_type_to_result_simple_return_type_already_result_std() { | ||
308 | check_assist_not_applicable( | ||
309 | change_return_type_to_result, | ||
310 | r#"fn foo() -> std::result::Result<i32<|>, String> { | ||
311 | let test = "test"; | ||
312 | return 42i32; | ||
313 | }"#, | ||
314 | ); | ||
315 | } | ||
316 | |||
317 | #[test] | ||
318 | fn change_return_type_to_result_simple_return_type_already_result() { | ||
319 | mark::check!(change_return_type_to_result_simple_return_type_already_result); | ||
320 | check_assist_not_applicable( | ||
321 | change_return_type_to_result, | ||
322 | r#"fn foo() -> Result<i32<|>, String> { | ||
323 | let test = "test"; | ||
324 | return 42i32; | ||
325 | }"#, | ||
326 | ); | ||
327 | } | ||
328 | |||
329 | #[test] | ||
330 | fn change_return_type_to_result_simple_with_cursor() { | ||
331 | check_assist( | ||
332 | change_return_type_to_result, | ||
333 | r#"fn foo() -> <|>i32 { | ||
334 | let test = "test"; | ||
335 | return 42i32; | ||
336 | }"#, | ||
337 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
338 | let test = "test"; | ||
339 | return Ok(42i32); | ||
340 | }"#, | ||
341 | ); | ||
342 | } | ||
343 | |||
344 | #[test] | ||
345 | fn change_return_type_to_result_simple_with_tail() { | ||
346 | check_assist( | ||
347 | change_return_type_to_result, | ||
348 | r#"fn foo() -><|> i32 { | ||
349 | let test = "test"; | ||
350 | 42i32 | ||
351 | }"#, | ||
352 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
353 | let test = "test"; | ||
354 | Ok(42i32) | ||
355 | }"#, | ||
356 | ); | ||
357 | } | ||
358 | |||
359 | #[test] | ||
360 | fn change_return_type_to_result_simple_with_tail_only() { | ||
361 | check_assist( | ||
362 | change_return_type_to_result, | ||
363 | r#"fn foo() -> i32<|> { | ||
364 | 42i32 | ||
365 | }"#, | ||
366 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
367 | Ok(42i32) | ||
368 | }"#, | ||
369 | ); | ||
370 | } | ||
371 | #[test] | ||
372 | fn change_return_type_to_result_simple_with_tail_block_like() { | ||
373 | check_assist( | ||
374 | change_return_type_to_result, | ||
375 | r#"fn foo() -> i32<|> { | ||
376 | if true { | ||
377 | 42i32 | ||
378 | } else { | ||
379 | 24i32 | ||
380 | } | ||
381 | }"#, | ||
382 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
383 | if true { | ||
384 | Ok(42i32) | ||
385 | } else { | ||
386 | Ok(24i32) | ||
387 | } | ||
388 | }"#, | ||
389 | ); | ||
390 | } | ||
391 | |||
392 | #[test] | ||
393 | fn change_return_type_to_result_simple_with_nested_if() { | ||
394 | check_assist( | ||
395 | change_return_type_to_result, | ||
396 | r#"fn foo() -> i32<|> { | ||
397 | if true { | ||
398 | if false { | ||
399 | 1 | ||
400 | } else { | ||
401 | 2 | ||
402 | } | ||
403 | } else { | ||
404 | 24i32 | ||
405 | } | ||
406 | }"#, | ||
407 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
408 | if true { | ||
409 | if false { | ||
410 | Ok(1) | ||
411 | } else { | ||
412 | Ok(2) | ||
413 | } | ||
414 | } else { | ||
415 | Ok(24i32) | ||
416 | } | ||
417 | }"#, | ||
418 | ); | ||
419 | } | ||
420 | |||
421 | #[test] | ||
422 | fn change_return_type_to_result_simple_with_await() { | ||
423 | check_assist( | ||
424 | change_return_type_to_result, | ||
425 | r#"async fn foo() -> i<|>32 { | ||
426 | if true { | ||
427 | if false { | ||
428 | 1.await | ||
429 | } else { | ||
430 | 2.await | ||
431 | } | ||
432 | } else { | ||
433 | 24i32.await | ||
434 | } | ||
435 | }"#, | ||
436 | r#"async fn foo() -> Result<i32, ${0:_}> { | ||
437 | if true { | ||
438 | if false { | ||
439 | Ok(1.await) | ||
440 | } else { | ||
441 | Ok(2.await) | ||
442 | } | ||
443 | } else { | ||
444 | Ok(24i32.await) | ||
445 | } | ||
446 | }"#, | ||
447 | ); | ||
448 | } | ||
449 | |||
450 | #[test] | ||
451 | fn change_return_type_to_result_simple_with_array() { | ||
452 | check_assist( | ||
453 | change_return_type_to_result, | ||
454 | r#"fn foo() -> [i32;<|> 3] { | ||
455 | [1, 2, 3] | ||
456 | }"#, | ||
457 | r#"fn foo() -> Result<[i32; 3], ${0:_}> { | ||
458 | Ok([1, 2, 3]) | ||
459 | }"#, | ||
460 | ); | ||
461 | } | ||
462 | |||
463 | #[test] | ||
464 | fn change_return_type_to_result_simple_with_cast() { | ||
465 | check_assist( | ||
466 | change_return_type_to_result, | ||
467 | r#"fn foo() -<|>> i32 { | ||
468 | if true { | ||
469 | if false { | ||
470 | 1 as i32 | ||
471 | } else { | ||
472 | 2 as i32 | ||
473 | } | ||
474 | } else { | ||
475 | 24 as i32 | ||
476 | } | ||
477 | }"#, | ||
478 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
479 | if true { | ||
480 | if false { | ||
481 | Ok(1 as i32) | ||
482 | } else { | ||
483 | Ok(2 as i32) | ||
484 | } | ||
485 | } else { | ||
486 | Ok(24 as i32) | ||
487 | } | ||
488 | }"#, | ||
489 | ); | ||
490 | } | ||
491 | |||
492 | #[test] | ||
493 | fn change_return_type_to_result_simple_with_tail_block_like_match() { | ||
494 | check_assist( | ||
495 | change_return_type_to_result, | ||
496 | r#"fn foo() -> i32<|> { | ||
497 | let my_var = 5; | ||
498 | match my_var { | ||
499 | 5 => 42i32, | ||
500 | _ => 24i32, | ||
501 | } | ||
502 | }"#, | ||
503 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
504 | let my_var = 5; | ||
505 | match my_var { | ||
506 | 5 => Ok(42i32), | ||
507 | _ => Ok(24i32), | ||
508 | } | ||
509 | }"#, | ||
510 | ); | ||
511 | } | ||
512 | |||
513 | #[test] | ||
514 | fn change_return_type_to_result_simple_with_loop_with_tail() { | ||
515 | check_assist( | ||
516 | change_return_type_to_result, | ||
517 | r#"fn foo() -> i32<|> { | ||
518 | let my_var = 5; | ||
519 | loop { | ||
520 | println!("test"); | ||
521 | 5 | ||
522 | } | ||
523 | |||
524 | my_var | ||
525 | }"#, | ||
526 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
527 | let my_var = 5; | ||
528 | loop { | ||
529 | println!("test"); | ||
530 | 5 | ||
531 | } | ||
532 | |||
533 | Ok(my_var) | ||
534 | }"#, | ||
535 | ); | ||
536 | } | ||
537 | |||
538 | #[test] | ||
539 | fn change_return_type_to_result_simple_with_loop_in_let_stmt() { | ||
540 | check_assist( | ||
541 | change_return_type_to_result, | ||
542 | r#"fn foo() -> i32<|> { | ||
543 | let my_var = let x = loop { | ||
544 | break 1; | ||
545 | }; | ||
546 | |||
547 | my_var | ||
548 | }"#, | ||
549 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
550 | let my_var = let x = loop { | ||
551 | break 1; | ||
552 | }; | ||
553 | |||
554 | Ok(my_var) | ||
555 | }"#, | ||
556 | ); | ||
557 | } | ||
558 | |||
559 | #[test] | ||
560 | fn change_return_type_to_result_simple_with_tail_block_like_match_return_expr() { | ||
561 | check_assist( | ||
562 | change_return_type_to_result, | ||
563 | r#"fn foo() -> i32<|> { | ||
564 | let my_var = 5; | ||
565 | let res = match my_var { | ||
566 | 5 => 42i32, | ||
567 | _ => return 24i32, | ||
568 | }; | ||
569 | |||
570 | res | ||
571 | }"#, | ||
572 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
573 | let my_var = 5; | ||
574 | let res = match my_var { | ||
575 | 5 => 42i32, | ||
576 | _ => return Ok(24i32), | ||
577 | }; | ||
578 | |||
579 | Ok(res) | ||
580 | }"#, | ||
581 | ); | ||
582 | |||
583 | check_assist( | ||
584 | change_return_type_to_result, | ||
585 | r#"fn foo() -> i32<|> { | ||
586 | let my_var = 5; | ||
587 | let res = if my_var == 5 { | ||
588 | 42i32 | ||
589 | } else { | ||
590 | return 24i32; | ||
591 | }; | ||
592 | |||
593 | res | ||
594 | }"#, | ||
595 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
596 | let my_var = 5; | ||
597 | let res = if my_var == 5 { | ||
598 | 42i32 | ||
599 | } else { | ||
600 | return Ok(24i32); | ||
601 | }; | ||
602 | |||
603 | Ok(res) | ||
604 | }"#, | ||
605 | ); | ||
606 | } | ||
607 | |||
608 | #[test] | ||
609 | fn change_return_type_to_result_simple_with_tail_block_like_match_deeper() { | ||
610 | check_assist( | ||
611 | change_return_type_to_result, | ||
612 | r#"fn foo() -> i32<|> { | ||
613 | let my_var = 5; | ||
614 | match my_var { | ||
615 | 5 => { | ||
616 | if true { | ||
617 | 42i32 | ||
618 | } else { | ||
619 | 25i32 | ||
620 | } | ||
621 | }, | ||
622 | _ => { | ||
623 | let test = "test"; | ||
624 | if test == "test" { | ||
625 | return bar(); | ||
626 | } | ||
627 | 53i32 | ||
628 | }, | ||
629 | } | ||
630 | }"#, | ||
631 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
632 | let my_var = 5; | ||
633 | match my_var { | ||
634 | 5 => { | ||
635 | if true { | ||
636 | Ok(42i32) | ||
637 | } else { | ||
638 | Ok(25i32) | ||
639 | } | ||
640 | }, | ||
641 | _ => { | ||
642 | let test = "test"; | ||
643 | if test == "test" { | ||
644 | return Ok(bar()); | ||
645 | } | ||
646 | Ok(53i32) | ||
647 | }, | ||
648 | } | ||
649 | }"#, | ||
650 | ); | ||
651 | } | ||
652 | |||
653 | #[test] | ||
654 | fn change_return_type_to_result_simple_with_tail_block_like_early_return() { | ||
655 | check_assist( | ||
656 | change_return_type_to_result, | ||
657 | r#"fn foo() -> i<|>32 { | ||
658 | let test = "test"; | ||
659 | if test == "test" { | ||
660 | return 24i32; | ||
661 | } | ||
662 | 53i32 | ||
663 | }"#, | ||
664 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
665 | let test = "test"; | ||
666 | if test == "test" { | ||
667 | return Ok(24i32); | ||
668 | } | ||
669 | Ok(53i32) | ||
670 | }"#, | ||
671 | ); | ||
672 | } | ||
673 | |||
674 | #[test] | ||
675 | fn change_return_type_to_result_simple_with_closure() { | ||
676 | check_assist( | ||
677 | change_return_type_to_result, | ||
678 | r#"fn foo(the_field: u32) -><|> u32 { | ||
679 | let true_closure = || { | ||
680 | return true; | ||
681 | }; | ||
682 | if the_field < 5 { | ||
683 | let mut i = 0; | ||
684 | |||
685 | |||
686 | if true_closure() { | ||
687 | return 99; | ||
688 | } else { | ||
689 | return 0; | ||
690 | } | ||
691 | } | ||
692 | |||
693 | the_field | ||
694 | }"#, | ||
695 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
696 | let true_closure = || { | ||
697 | return true; | ||
698 | }; | ||
699 | if the_field < 5 { | ||
700 | let mut i = 0; | ||
701 | |||
702 | |||
703 | if true_closure() { | ||
704 | return Ok(99); | ||
705 | } else { | ||
706 | return Ok(0); | ||
707 | } | ||
708 | } | ||
709 | |||
710 | Ok(the_field) | ||
711 | }"#, | ||
712 | ); | ||
713 | |||
714 | check_assist( | ||
715 | change_return_type_to_result, | ||
716 | r#"fn foo(the_field: u32) -> u32<|> { | ||
717 | let true_closure = || { | ||
718 | return true; | ||
719 | }; | ||
720 | if the_field < 5 { | ||
721 | let mut i = 0; | ||
722 | |||
723 | |||
724 | if true_closure() { | ||
725 | return 99; | ||
726 | } else { | ||
727 | return 0; | ||
728 | } | ||
729 | } | ||
730 | let t = None; | ||
731 | |||
732 | t.unwrap_or_else(|| the_field) | ||
733 | }"#, | ||
734 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
735 | let true_closure = || { | ||
736 | return true; | ||
737 | }; | ||
738 | if the_field < 5 { | ||
739 | let mut i = 0; | ||
740 | |||
741 | |||
742 | if true_closure() { | ||
743 | return Ok(99); | ||
744 | } else { | ||
745 | return Ok(0); | ||
746 | } | ||
747 | } | ||
748 | let t = None; | ||
749 | |||
750 | Ok(t.unwrap_or_else(|| the_field)) | ||
751 | }"#, | ||
752 | ); | ||
753 | } | ||
754 | |||
755 | #[test] | ||
756 | fn change_return_type_to_result_simple_with_weird_forms() { | ||
757 | check_assist( | ||
758 | change_return_type_to_result, | ||
759 | r#"fn foo() -> i32<|> { | ||
760 | let test = "test"; | ||
761 | if test == "test" { | ||
762 | return 24i32; | ||
763 | } | ||
764 | let mut i = 0; | ||
765 | loop { | ||
766 | if i == 1 { | ||
767 | break 55; | ||
768 | } | ||
769 | i += 1; | ||
770 | } | ||
771 | }"#, | ||
772 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
773 | let test = "test"; | ||
774 | if test == "test" { | ||
775 | return Ok(24i32); | ||
776 | } | ||
777 | let mut i = 0; | ||
778 | loop { | ||
779 | if i == 1 { | ||
780 | break Ok(55); | ||
781 | } | ||
782 | i += 1; | ||
783 | } | ||
784 | }"#, | ||
785 | ); | ||
786 | |||
787 | check_assist( | ||
788 | change_return_type_to_result, | ||
789 | r#"fn foo() -> i32<|> { | ||
790 | let test = "test"; | ||
791 | if test == "test" { | ||
792 | return 24i32; | ||
793 | } | ||
794 | let mut i = 0; | ||
795 | loop { | ||
796 | loop { | ||
797 | if i == 1 { | ||
798 | break 55; | ||
799 | } | ||
800 | i += 1; | ||
801 | } | ||
802 | } | ||
803 | }"#, | ||
804 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
805 | let test = "test"; | ||
806 | if test == "test" { | ||
807 | return Ok(24i32); | ||
808 | } | ||
809 | let mut i = 0; | ||
810 | loop { | ||
811 | loop { | ||
812 | if i == 1 { | ||
813 | break Ok(55); | ||
814 | } | ||
815 | i += 1; | ||
816 | } | ||
817 | } | ||
818 | }"#, | ||
819 | ); | ||
820 | |||
821 | check_assist( | ||
822 | change_return_type_to_result, | ||
823 | r#"fn foo() -> i3<|>2 { | ||
824 | let test = "test"; | ||
825 | let other = 5; | ||
826 | if test == "test" { | ||
827 | let res = match other { | ||
828 | 5 => 43, | ||
829 | _ => return 56, | ||
830 | }; | ||
831 | } | ||
832 | let mut i = 0; | ||
833 | loop { | ||
834 | loop { | ||
835 | if i == 1 { | ||
836 | break 55; | ||
837 | } | ||
838 | i += 1; | ||
839 | } | ||
840 | } | ||
841 | }"#, | ||
842 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
843 | let test = "test"; | ||
844 | let other = 5; | ||
845 | if test == "test" { | ||
846 | let res = match other { | ||
847 | 5 => 43, | ||
848 | _ => return Ok(56), | ||
849 | }; | ||
850 | } | ||
851 | let mut i = 0; | ||
852 | loop { | ||
853 | loop { | ||
854 | if i == 1 { | ||
855 | break Ok(55); | ||
856 | } | ||
857 | i += 1; | ||
858 | } | ||
859 | } | ||
860 | }"#, | ||
861 | ); | ||
862 | |||
863 | check_assist( | ||
864 | change_return_type_to_result, | ||
865 | r#"fn foo(the_field: u32) -> u32<|> { | ||
866 | if the_field < 5 { | ||
867 | let mut i = 0; | ||
868 | loop { | ||
869 | if i > 5 { | ||
870 | return 55u32; | ||
871 | } | ||
872 | i += 3; | ||
873 | } | ||
874 | |||
875 | match i { | ||
876 | 5 => return 99, | ||
877 | _ => return 0, | ||
878 | }; | ||
879 | } | ||
880 | |||
881 | the_field | ||
882 | }"#, | ||
883 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
884 | if the_field < 5 { | ||
885 | let mut i = 0; | ||
886 | loop { | ||
887 | if i > 5 { | ||
888 | return Ok(55u32); | ||
889 | } | ||
890 | i += 3; | ||
891 | } | ||
892 | |||
893 | match i { | ||
894 | 5 => return Ok(99), | ||
895 | _ => return Ok(0), | ||
896 | }; | ||
897 | } | ||
898 | |||
899 | Ok(the_field) | ||
900 | }"#, | ||
901 | ); | ||
902 | |||
903 | check_assist( | ||
904 | change_return_type_to_result, | ||
905 | r#"fn foo(the_field: u32) -> u3<|>2 { | ||
906 | if the_field < 5 { | ||
907 | let mut i = 0; | ||
908 | |||
909 | match i { | ||
910 | 5 => return 99, | ||
911 | _ => return 0, | ||
912 | } | ||
913 | } | ||
914 | |||
915 | the_field | ||
916 | }"#, | ||
917 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
918 | if the_field < 5 { | ||
919 | let mut i = 0; | ||
920 | |||
921 | match i { | ||
922 | 5 => return Ok(99), | ||
923 | _ => return Ok(0), | ||
924 | } | ||
925 | } | ||
926 | |||
927 | Ok(the_field) | ||
928 | }"#, | ||
929 | ); | ||
930 | |||
931 | check_assist( | ||
932 | change_return_type_to_result, | ||
933 | r#"fn foo(the_field: u32) -> u32<|> { | ||
934 | if the_field < 5 { | ||
935 | let mut i = 0; | ||
936 | |||
937 | if i == 5 { | ||
938 | return 99 | ||
939 | } else { | ||
940 | return 0 | ||
941 | } | ||
942 | } | ||
943 | |||
944 | the_field | ||
945 | }"#, | ||
946 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
947 | if the_field < 5 { | ||
948 | let mut i = 0; | ||
949 | |||
950 | if i == 5 { | ||
951 | return Ok(99) | ||
952 | } else { | ||
953 | return Ok(0) | ||
954 | } | ||
955 | } | ||
956 | |||
957 | Ok(the_field) | ||
958 | }"#, | ||
959 | ); | ||
960 | |||
961 | check_assist( | ||
962 | change_return_type_to_result, | ||
963 | r#"fn foo(the_field: u32) -> <|>u32 { | ||
964 | if the_field < 5 { | ||
965 | let mut i = 0; | ||
966 | |||
967 | if i == 5 { | ||
968 | return 99; | ||
969 | } else { | ||
970 | return 0; | ||
971 | } | ||
972 | } | ||
973 | |||
974 | the_field | ||
975 | }"#, | ||
976 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
977 | if the_field < 5 { | ||
978 | let mut i = 0; | ||
979 | |||
980 | if i == 5 { | ||
981 | return Ok(99); | ||
982 | } else { | ||
983 | return Ok(0); | ||
984 | } | ||
985 | } | ||
986 | |||
987 | Ok(the_field) | ||
988 | }"#, | ||
989 | ); | ||
990 | } | ||
991 | } | ||
diff --git a/crates/ra_assists/src/handlers/change_visibility.rs b/crates/ra_assists/src/handlers/change_visibility.rs deleted file mode 100644 index 724daa93f..000000000 --- a/crates/ra_assists/src/handlers/change_visibility.rs +++ /dev/null | |||
@@ -1,200 +0,0 @@ | |||
1 | use ra_syntax::{ | ||
2 | ast::{self, NameOwner, VisibilityOwner}, | ||
3 | AstNode, | ||
4 | SyntaxKind::{CONST, ENUM, FN, MODULE, STATIC, STRUCT, TRAIT, VISIBILITY}, | ||
5 | T, | ||
6 | }; | ||
7 | use test_utils::mark; | ||
8 | |||
9 | use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists}; | ||
10 | |||
11 | // Assist: change_visibility | ||
12 | // | ||
13 | // Adds or changes existing visibility specifier. | ||
14 | // | ||
15 | // ``` | ||
16 | // <|>fn frobnicate() {} | ||
17 | // ``` | ||
18 | // -> | ||
19 | // ``` | ||
20 | // pub(crate) fn frobnicate() {} | ||
21 | // ``` | ||
22 | pub(crate) fn change_visibility(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
23 | if let Some(vis) = ctx.find_node_at_offset::<ast::Visibility>() { | ||
24 | return change_vis(acc, vis); | ||
25 | } | ||
26 | add_vis(acc, ctx) | ||
27 | } | ||
28 | |||
29 | fn add_vis(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
30 | let item_keyword = ctx.token_at_offset().find(|leaf| { | ||
31 | matches!( | ||
32 | leaf.kind(), | ||
33 | T![const] | T![static] | T![fn] | T![mod] | T![struct] | T![enum] | T![trait] | ||
34 | ) | ||
35 | }); | ||
36 | |||
37 | let (offset, target) = if let Some(keyword) = item_keyword { | ||
38 | let parent = keyword.parent(); | ||
39 | let def_kws = vec![CONST, STATIC, FN, MODULE, STRUCT, ENUM, TRAIT]; | ||
40 | // Parent is not a definition, can't add visibility | ||
41 | if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) { | ||
42 | return None; | ||
43 | } | ||
44 | // Already have visibility, do nothing | ||
45 | if parent.children().any(|child| child.kind() == VISIBILITY) { | ||
46 | return None; | ||
47 | } | ||
48 | (vis_offset(&parent), keyword.text_range()) | ||
49 | } else if let Some(field_name) = ctx.find_node_at_offset::<ast::Name>() { | ||
50 | let field = field_name.syntax().ancestors().find_map(ast::RecordField::cast)?; | ||
51 | if field.name()? != field_name { | ||
52 | mark::hit!(change_visibility_field_false_positive); | ||
53 | return None; | ||
54 | } | ||
55 | if field.visibility().is_some() { | ||
56 | return None; | ||
57 | } | ||
58 | (vis_offset(field.syntax()), field_name.syntax().text_range()) | ||
59 | } else if let Some(field) = ctx.find_node_at_offset::<ast::TupleField>() { | ||
60 | if field.visibility().is_some() { | ||
61 | return None; | ||
62 | } | ||
63 | (vis_offset(field.syntax()), field.syntax().text_range()) | ||
64 | } else { | ||
65 | return None; | ||
66 | }; | ||
67 | |||
68 | acc.add( | ||
69 | AssistId("change_visibility", AssistKind::RefactorRewrite), | ||
70 | "Change visibility to pub(crate)", | ||
71 | target, | ||
72 | |edit| { | ||
73 | edit.insert(offset, "pub(crate) "); | ||
74 | }, | ||
75 | ) | ||
76 | } | ||
77 | |||
78 | fn change_vis(acc: &mut Assists, vis: ast::Visibility) -> Option<()> { | ||
79 | if vis.syntax().text() == "pub" { | ||
80 | let target = vis.syntax().text_range(); | ||
81 | return acc.add( | ||
82 | AssistId("change_visibility", AssistKind::RefactorRewrite), | ||
83 | "Change Visibility to pub(crate)", | ||
84 | target, | ||
85 | |edit| { | ||
86 | edit.replace(vis.syntax().text_range(), "pub(crate)"); | ||
87 | }, | ||
88 | ); | ||
89 | } | ||
90 | if vis.syntax().text() == "pub(crate)" { | ||
91 | let target = vis.syntax().text_range(); | ||
92 | return acc.add( | ||
93 | AssistId("change_visibility", AssistKind::RefactorRewrite), | ||
94 | "Change visibility to pub", | ||
95 | target, | ||
96 | |edit| { | ||
97 | edit.replace(vis.syntax().text_range(), "pub"); | ||
98 | }, | ||
99 | ); | ||
100 | } | ||
101 | None | ||
102 | } | ||
103 | |||
104 | #[cfg(test)] | ||
105 | mod tests { | ||
106 | use test_utils::mark; | ||
107 | |||
108 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
109 | |||
110 | use super::*; | ||
111 | |||
112 | #[test] | ||
113 | fn change_visibility_adds_pub_crate_to_items() { | ||
114 | check_assist(change_visibility, "<|>fn foo() {}", "pub(crate) fn foo() {}"); | ||
115 | check_assist(change_visibility, "f<|>n foo() {}", "pub(crate) fn foo() {}"); | ||
116 | check_assist(change_visibility, "<|>struct Foo {}", "pub(crate) struct Foo {}"); | ||
117 | check_assist(change_visibility, "<|>mod foo {}", "pub(crate) mod foo {}"); | ||
118 | check_assist(change_visibility, "<|>trait Foo {}", "pub(crate) trait Foo {}"); | ||
119 | check_assist(change_visibility, "m<|>od {}", "pub(crate) mod {}"); | ||
120 | check_assist(change_visibility, "unsafe f<|>n foo() {}", "pub(crate) unsafe fn foo() {}"); | ||
121 | } | ||
122 | |||
123 | #[test] | ||
124 | fn change_visibility_works_with_struct_fields() { | ||
125 | check_assist( | ||
126 | change_visibility, | ||
127 | r"struct S { <|>field: u32 }", | ||
128 | r"struct S { pub(crate) field: u32 }", | ||
129 | ); | ||
130 | check_assist(change_visibility, r"struct S ( <|>u32 )", r"struct S ( pub(crate) u32 )"); | ||
131 | } | ||
132 | |||
133 | #[test] | ||
134 | fn change_visibility_field_false_positive() { | ||
135 | mark::check!(change_visibility_field_false_positive); | ||
136 | check_assist_not_applicable( | ||
137 | change_visibility, | ||
138 | r"struct S { field: [(); { let <|>x = ();}] }", | ||
139 | ) | ||
140 | } | ||
141 | |||
142 | #[test] | ||
143 | fn change_visibility_pub_to_pub_crate() { | ||
144 | check_assist(change_visibility, "<|>pub fn foo() {}", "pub(crate) fn foo() {}") | ||
145 | } | ||
146 | |||
147 | #[test] | ||
148 | fn change_visibility_pub_crate_to_pub() { | ||
149 | check_assist(change_visibility, "<|>pub(crate) fn foo() {}", "pub fn foo() {}") | ||
150 | } | ||
151 | |||
152 | #[test] | ||
153 | fn change_visibility_const() { | ||
154 | check_assist(change_visibility, "<|>const FOO = 3u8;", "pub(crate) const FOO = 3u8;"); | ||
155 | } | ||
156 | |||
157 | #[test] | ||
158 | fn change_visibility_static() { | ||
159 | check_assist(change_visibility, "<|>static FOO = 3u8;", "pub(crate) static FOO = 3u8;"); | ||
160 | } | ||
161 | |||
162 | #[test] | ||
163 | fn change_visibility_handles_comment_attrs() { | ||
164 | check_assist( | ||
165 | change_visibility, | ||
166 | r" | ||
167 | /// docs | ||
168 | |||
169 | // comments | ||
170 | |||
171 | #[derive(Debug)] | ||
172 | <|>struct Foo; | ||
173 | ", | ||
174 | r" | ||
175 | /// docs | ||
176 | |||
177 | // comments | ||
178 | |||
179 | #[derive(Debug)] | ||
180 | pub(crate) struct Foo; | ||
181 | ", | ||
182 | ) | ||
183 | } | ||
184 | |||
185 | #[test] | ||
186 | fn not_applicable_for_enum_variants() { | ||
187 | check_assist_not_applicable( | ||
188 | change_visibility, | ||
189 | r"mod foo { pub enum Foo {Foo1} } | ||
190 | fn main() { foo::Foo::Foo1<|> } ", | ||
191 | ); | ||
192 | } | ||
193 | |||
194 | #[test] | ||
195 | fn change_visibility_target() { | ||
196 | check_assist_target(change_visibility, "<|>fn foo() {}", "fn"); | ||
197 | check_assist_target(change_visibility, "pub(crate)<|> fn foo() {}", "pub(crate)"); | ||
198 | check_assist_target(change_visibility, "struct S { <|>field: u32 }", "field"); | ||
199 | } | ||
200 | } | ||
diff --git a/crates/ra_assists/src/handlers/early_return.rs b/crates/ra_assists/src/handlers/early_return.rs deleted file mode 100644 index 6816a2709..000000000 --- a/crates/ra_assists/src/handlers/early_return.rs +++ /dev/null | |||
@@ -1,515 +0,0 @@ | |||
1 | use std::{iter::once, ops::RangeInclusive}; | ||
2 | |||
3 | use ra_syntax::{ | ||
4 | algo::replace_children, | ||
5 | ast::{ | ||
6 | self, | ||
7 | edit::{AstNodeEdit, IndentLevel}, | ||
8 | make, | ||
9 | }, | ||
10 | AstNode, | ||
11 | SyntaxKind::{FN, LOOP_EXPR, L_CURLY, R_CURLY, WHILE_EXPR, WHITESPACE}, | ||
12 | SyntaxNode, | ||
13 | }; | ||
14 | |||
15 | use crate::{ | ||
16 | assist_context::{AssistContext, Assists}, | ||
17 | utils::invert_boolean_expression, | ||
18 | AssistId, AssistKind, | ||
19 | }; | ||
20 | |||
21 | // Assist: convert_to_guarded_return | ||
22 | // | ||
23 | // Replace a large conditional with a guarded return. | ||
24 | // | ||
25 | // ``` | ||
26 | // fn main() { | ||
27 | // <|>if cond { | ||
28 | // foo(); | ||
29 | // bar(); | ||
30 | // } | ||
31 | // } | ||
32 | // ``` | ||
33 | // -> | ||
34 | // ``` | ||
35 | // fn main() { | ||
36 | // if !cond { | ||
37 | // return; | ||
38 | // } | ||
39 | // foo(); | ||
40 | // bar(); | ||
41 | // } | ||
42 | // ``` | ||
43 | pub(crate) fn convert_to_guarded_return(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
44 | let if_expr: ast::IfExpr = ctx.find_node_at_offset()?; | ||
45 | if if_expr.else_branch().is_some() { | ||
46 | return None; | ||
47 | } | ||
48 | |||
49 | let cond = if_expr.condition()?; | ||
50 | |||
51 | // Check if there is an IfLet that we can handle. | ||
52 | let if_let_pat = match cond.pat() { | ||
53 | None => None, // No IfLet, supported. | ||
54 | Some(ast::Pat::TupleStructPat(pat)) if pat.fields().count() == 1 => { | ||
55 | let path = pat.path()?; | ||
56 | match path.qualifier() { | ||
57 | None => { | ||
58 | let bound_ident = pat.fields().next().unwrap(); | ||
59 | Some((path, bound_ident)) | ||
60 | } | ||
61 | Some(_) => return None, | ||
62 | } | ||
63 | } | ||
64 | Some(_) => return None, // Unsupported IfLet. | ||
65 | }; | ||
66 | |||
67 | let cond_expr = cond.expr()?; | ||
68 | let then_block = if_expr.then_branch()?; | ||
69 | |||
70 | let parent_block = if_expr.syntax().parent()?.ancestors().find_map(ast::BlockExpr::cast)?; | ||
71 | |||
72 | if parent_block.expr()? != if_expr.clone().into() { | ||
73 | return None; | ||
74 | } | ||
75 | |||
76 | // check for early return and continue | ||
77 | let first_in_then_block = then_block.syntax().first_child()?; | ||
78 | if ast::ReturnExpr::can_cast(first_in_then_block.kind()) | ||
79 | || ast::ContinueExpr::can_cast(first_in_then_block.kind()) | ||
80 | || first_in_then_block | ||
81 | .children() | ||
82 | .any(|x| ast::ReturnExpr::can_cast(x.kind()) || ast::ContinueExpr::can_cast(x.kind())) | ||
83 | { | ||
84 | return None; | ||
85 | } | ||
86 | |||
87 | let parent_container = parent_block.syntax().parent()?; | ||
88 | |||
89 | let early_expression: ast::Expr = match parent_container.kind() { | ||
90 | WHILE_EXPR | LOOP_EXPR => make::expr_continue(), | ||
91 | FN => make::expr_return(), | ||
92 | _ => return None, | ||
93 | }; | ||
94 | |||
95 | if then_block.syntax().first_child_or_token().map(|t| t.kind() == L_CURLY).is_none() { | ||
96 | return None; | ||
97 | } | ||
98 | |||
99 | then_block.syntax().last_child_or_token().filter(|t| t.kind() == R_CURLY)?; | ||
100 | |||
101 | let target = if_expr.syntax().text_range(); | ||
102 | acc.add( | ||
103 | AssistId("convert_to_guarded_return", AssistKind::RefactorRewrite), | ||
104 | "Convert to guarded return", | ||
105 | target, | ||
106 | |edit| { | ||
107 | let if_indent_level = IndentLevel::from_node(&if_expr.syntax()); | ||
108 | let new_block = match if_let_pat { | ||
109 | None => { | ||
110 | // If. | ||
111 | let new_expr = { | ||
112 | let then_branch = | ||
113 | make::block_expr(once(make::expr_stmt(early_expression).into()), None); | ||
114 | let cond = invert_boolean_expression(cond_expr); | ||
115 | make::expr_if(make::condition(cond, None), then_branch) | ||
116 | .indent(if_indent_level) | ||
117 | }; | ||
118 | replace(new_expr.syntax(), &then_block, &parent_block, &if_expr) | ||
119 | } | ||
120 | Some((path, bound_ident)) => { | ||
121 | // If-let. | ||
122 | let match_expr = { | ||
123 | let happy_arm = { | ||
124 | let pat = make::tuple_struct_pat( | ||
125 | path, | ||
126 | once(make::ident_pat(make::name("it")).into()), | ||
127 | ); | ||
128 | let expr = { | ||
129 | let name_ref = make::name_ref("it"); | ||
130 | let segment = make::path_segment(name_ref); | ||
131 | let path = make::path_unqualified(segment); | ||
132 | make::expr_path(path) | ||
133 | }; | ||
134 | make::match_arm(once(pat.into()), expr) | ||
135 | }; | ||
136 | |||
137 | let sad_arm = make::match_arm( | ||
138 | // FIXME: would be cool to use `None` or `Err(_)` if appropriate | ||
139 | once(make::wildcard_pat().into()), | ||
140 | early_expression, | ||
141 | ); | ||
142 | |||
143 | make::expr_match(cond_expr, make::match_arm_list(vec![happy_arm, sad_arm])) | ||
144 | }; | ||
145 | |||
146 | let let_stmt = make::let_stmt( | ||
147 | make::ident_pat(make::name(&bound_ident.syntax().to_string())).into(), | ||
148 | Some(match_expr), | ||
149 | ); | ||
150 | let let_stmt = let_stmt.indent(if_indent_level); | ||
151 | replace(let_stmt.syntax(), &then_block, &parent_block, &if_expr) | ||
152 | } | ||
153 | }; | ||
154 | edit.replace_ast(parent_block, ast::BlockExpr::cast(new_block).unwrap()); | ||
155 | |||
156 | fn replace( | ||
157 | new_expr: &SyntaxNode, | ||
158 | then_block: &ast::BlockExpr, | ||
159 | parent_block: &ast::BlockExpr, | ||
160 | if_expr: &ast::IfExpr, | ||
161 | ) -> SyntaxNode { | ||
162 | let then_block_items = then_block.dedent(IndentLevel(1)); | ||
163 | let end_of_then = then_block_items.syntax().last_child_or_token().unwrap(); | ||
164 | let end_of_then = | ||
165 | if end_of_then.prev_sibling_or_token().map(|n| n.kind()) == Some(WHITESPACE) { | ||
166 | end_of_then.prev_sibling_or_token().unwrap() | ||
167 | } else { | ||
168 | end_of_then | ||
169 | }; | ||
170 | let mut then_statements = new_expr.children_with_tokens().chain( | ||
171 | then_block_items | ||
172 | .syntax() | ||
173 | .children_with_tokens() | ||
174 | .skip(1) | ||
175 | .take_while(|i| *i != end_of_then), | ||
176 | ); | ||
177 | replace_children( | ||
178 | &parent_block.syntax(), | ||
179 | RangeInclusive::new( | ||
180 | if_expr.clone().syntax().clone().into(), | ||
181 | if_expr.syntax().clone().into(), | ||
182 | ), | ||
183 | &mut then_statements, | ||
184 | ) | ||
185 | } | ||
186 | }, | ||
187 | ) | ||
188 | } | ||
189 | |||
190 | #[cfg(test)] | ||
191 | mod tests { | ||
192 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
193 | |||
194 | use super::*; | ||
195 | |||
196 | #[test] | ||
197 | fn convert_inside_fn() { | ||
198 | check_assist( | ||
199 | convert_to_guarded_return, | ||
200 | r#" | ||
201 | fn main() { | ||
202 | bar(); | ||
203 | if<|> true { | ||
204 | foo(); | ||
205 | |||
206 | //comment | ||
207 | bar(); | ||
208 | } | ||
209 | } | ||
210 | "#, | ||
211 | r#" | ||
212 | fn main() { | ||
213 | bar(); | ||
214 | if !true { | ||
215 | return; | ||
216 | } | ||
217 | foo(); | ||
218 | |||
219 | //comment | ||
220 | bar(); | ||
221 | } | ||
222 | "#, | ||
223 | ); | ||
224 | } | ||
225 | |||
226 | #[test] | ||
227 | fn convert_let_inside_fn() { | ||
228 | check_assist( | ||
229 | convert_to_guarded_return, | ||
230 | r#" | ||
231 | fn main(n: Option<String>) { | ||
232 | bar(); | ||
233 | if<|> let Some(n) = n { | ||
234 | foo(n); | ||
235 | |||
236 | //comment | ||
237 | bar(); | ||
238 | } | ||
239 | } | ||
240 | "#, | ||
241 | r#" | ||
242 | fn main(n: Option<String>) { | ||
243 | bar(); | ||
244 | let n = match n { | ||
245 | Some(it) => it, | ||
246 | _ => return, | ||
247 | }; | ||
248 | foo(n); | ||
249 | |||
250 | //comment | ||
251 | bar(); | ||
252 | } | ||
253 | "#, | ||
254 | ); | ||
255 | } | ||
256 | |||
257 | #[test] | ||
258 | fn convert_if_let_result() { | ||
259 | check_assist( | ||
260 | convert_to_guarded_return, | ||
261 | r#" | ||
262 | fn main() { | ||
263 | if<|> let Ok(x) = Err(92) { | ||
264 | foo(x); | ||
265 | } | ||
266 | } | ||
267 | "#, | ||
268 | r#" | ||
269 | fn main() { | ||
270 | let x = match Err(92) { | ||
271 | Ok(it) => it, | ||
272 | _ => return, | ||
273 | }; | ||
274 | foo(x); | ||
275 | } | ||
276 | "#, | ||
277 | ); | ||
278 | } | ||
279 | |||
280 | #[test] | ||
281 | fn convert_let_ok_inside_fn() { | ||
282 | check_assist( | ||
283 | convert_to_guarded_return, | ||
284 | r#" | ||
285 | fn main(n: Option<String>) { | ||
286 | bar(); | ||
287 | if<|> let Ok(n) = n { | ||
288 | foo(n); | ||
289 | |||
290 | //comment | ||
291 | bar(); | ||
292 | } | ||
293 | } | ||
294 | "#, | ||
295 | r#" | ||
296 | fn main(n: Option<String>) { | ||
297 | bar(); | ||
298 | let n = match n { | ||
299 | Ok(it) => it, | ||
300 | _ => return, | ||
301 | }; | ||
302 | foo(n); | ||
303 | |||
304 | //comment | ||
305 | bar(); | ||
306 | } | ||
307 | "#, | ||
308 | ); | ||
309 | } | ||
310 | |||
311 | #[test] | ||
312 | fn convert_inside_while() { | ||
313 | check_assist( | ||
314 | convert_to_guarded_return, | ||
315 | r#" | ||
316 | fn main() { | ||
317 | while true { | ||
318 | if<|> true { | ||
319 | foo(); | ||
320 | bar(); | ||
321 | } | ||
322 | } | ||
323 | } | ||
324 | "#, | ||
325 | r#" | ||
326 | fn main() { | ||
327 | while true { | ||
328 | if !true { | ||
329 | continue; | ||
330 | } | ||
331 | foo(); | ||
332 | bar(); | ||
333 | } | ||
334 | } | ||
335 | "#, | ||
336 | ); | ||
337 | } | ||
338 | |||
339 | #[test] | ||
340 | fn convert_let_inside_while() { | ||
341 | check_assist( | ||
342 | convert_to_guarded_return, | ||
343 | r#" | ||
344 | fn main() { | ||
345 | while true { | ||
346 | if<|> let Some(n) = n { | ||
347 | foo(n); | ||
348 | bar(); | ||
349 | } | ||
350 | } | ||
351 | } | ||
352 | "#, | ||
353 | r#" | ||
354 | fn main() { | ||
355 | while true { | ||
356 | let n = match n { | ||
357 | Some(it) => it, | ||
358 | _ => continue, | ||
359 | }; | ||
360 | foo(n); | ||
361 | bar(); | ||
362 | } | ||
363 | } | ||
364 | "#, | ||
365 | ); | ||
366 | } | ||
367 | |||
368 | #[test] | ||
369 | fn convert_inside_loop() { | ||
370 | check_assist( | ||
371 | convert_to_guarded_return, | ||
372 | r#" | ||
373 | fn main() { | ||
374 | loop { | ||
375 | if<|> true { | ||
376 | foo(); | ||
377 | bar(); | ||
378 | } | ||
379 | } | ||
380 | } | ||
381 | "#, | ||
382 | r#" | ||
383 | fn main() { | ||
384 | loop { | ||
385 | if !true { | ||
386 | continue; | ||
387 | } | ||
388 | foo(); | ||
389 | bar(); | ||
390 | } | ||
391 | } | ||
392 | "#, | ||
393 | ); | ||
394 | } | ||
395 | |||
396 | #[test] | ||
397 | fn convert_let_inside_loop() { | ||
398 | check_assist( | ||
399 | convert_to_guarded_return, | ||
400 | r#" | ||
401 | fn main() { | ||
402 | loop { | ||
403 | if<|> let Some(n) = n { | ||
404 | foo(n); | ||
405 | bar(); | ||
406 | } | ||
407 | } | ||
408 | } | ||
409 | "#, | ||
410 | r#" | ||
411 | fn main() { | ||
412 | loop { | ||
413 | let n = match n { | ||
414 | Some(it) => it, | ||
415 | _ => continue, | ||
416 | }; | ||
417 | foo(n); | ||
418 | bar(); | ||
419 | } | ||
420 | } | ||
421 | "#, | ||
422 | ); | ||
423 | } | ||
424 | |||
425 | #[test] | ||
426 | fn ignore_already_converted_if() { | ||
427 | check_assist_not_applicable( | ||
428 | convert_to_guarded_return, | ||
429 | r#" | ||
430 | fn main() { | ||
431 | if<|> true { | ||
432 | return; | ||
433 | } | ||
434 | } | ||
435 | "#, | ||
436 | ); | ||
437 | } | ||
438 | |||
439 | #[test] | ||
440 | fn ignore_already_converted_loop() { | ||
441 | check_assist_not_applicable( | ||
442 | convert_to_guarded_return, | ||
443 | r#" | ||
444 | fn main() { | ||
445 | loop { | ||
446 | if<|> true { | ||
447 | continue; | ||
448 | } | ||
449 | } | ||
450 | } | ||
451 | "#, | ||
452 | ); | ||
453 | } | ||
454 | |||
455 | #[test] | ||
456 | fn ignore_return() { | ||
457 | check_assist_not_applicable( | ||
458 | convert_to_guarded_return, | ||
459 | r#" | ||
460 | fn main() { | ||
461 | if<|> true { | ||
462 | return | ||
463 | } | ||
464 | } | ||
465 | "#, | ||
466 | ); | ||
467 | } | ||
468 | |||
469 | #[test] | ||
470 | fn ignore_else_branch() { | ||
471 | check_assist_not_applicable( | ||
472 | convert_to_guarded_return, | ||
473 | r#" | ||
474 | fn main() { | ||
475 | if<|> true { | ||
476 | foo(); | ||
477 | } else { | ||
478 | bar() | ||
479 | } | ||
480 | } | ||
481 | "#, | ||
482 | ); | ||
483 | } | ||
484 | |||
485 | #[test] | ||
486 | fn ignore_statements_aftert_if() { | ||
487 | check_assist_not_applicable( | ||
488 | convert_to_guarded_return, | ||
489 | r#" | ||
490 | fn main() { | ||
491 | if<|> true { | ||
492 | foo(); | ||
493 | } | ||
494 | bar(); | ||
495 | } | ||
496 | "#, | ||
497 | ); | ||
498 | } | ||
499 | |||
500 | #[test] | ||
501 | fn ignore_statements_inside_if() { | ||
502 | check_assist_not_applicable( | ||
503 | convert_to_guarded_return, | ||
504 | r#" | ||
505 | fn main() { | ||
506 | if false { | ||
507 | if<|> true { | ||
508 | foo(); | ||
509 | } | ||
510 | } | ||
511 | } | ||
512 | "#, | ||
513 | ); | ||
514 | } | ||
515 | } | ||
diff --git a/crates/ra_assists/src/handlers/expand_glob_import.rs b/crates/ra_assists/src/handlers/expand_glob_import.rs deleted file mode 100644 index eb216a81a..000000000 --- a/crates/ra_assists/src/handlers/expand_glob_import.rs +++ /dev/null | |||
@@ -1,391 +0,0 @@ | |||
1 | use hir::{AssocItem, MacroDef, ModuleDef, Name, PathResolution, ScopeDef, SemanticsScope}; | ||
2 | use ra_ide_db::{ | ||
3 | defs::{classify_name_ref, Definition, NameRefClass}, | ||
4 | RootDatabase, | ||
5 | }; | ||
6 | use ra_syntax::{algo, ast, match_ast, AstNode, SyntaxNode, SyntaxToken, T}; | ||
7 | |||
8 | use crate::{ | ||
9 | assist_context::{AssistBuilder, AssistContext, Assists}, | ||
10 | AssistId, AssistKind, | ||
11 | }; | ||
12 | |||
13 | use either::Either; | ||
14 | |||
15 | // Assist: expand_glob_import | ||
16 | // | ||
17 | // Expands glob imports. | ||
18 | // | ||
19 | // ``` | ||
20 | // mod foo { | ||
21 | // pub struct Bar; | ||
22 | // pub struct Baz; | ||
23 | // } | ||
24 | // | ||
25 | // use foo::*<|>; | ||
26 | // | ||
27 | // fn qux(bar: Bar, baz: Baz) {} | ||
28 | // ``` | ||
29 | // -> | ||
30 | // ``` | ||
31 | // mod foo { | ||
32 | // pub struct Bar; | ||
33 | // pub struct Baz; | ||
34 | // } | ||
35 | // | ||
36 | // use foo::{Baz, Bar}; | ||
37 | // | ||
38 | // fn qux(bar: Bar, baz: Baz) {} | ||
39 | // ``` | ||
40 | pub(crate) fn expand_glob_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
41 | let star = ctx.find_token_at_offset(T![*])?; | ||
42 | let mod_path = find_mod_path(&star)?; | ||
43 | |||
44 | let source_file = ctx.source_file(); | ||
45 | let scope = ctx.sema.scope_at_offset(source_file.syntax(), ctx.offset()); | ||
46 | |||
47 | let defs_in_mod = find_defs_in_mod(ctx, scope, &mod_path)?; | ||
48 | let name_refs_in_source_file = | ||
49 | source_file.syntax().descendants().filter_map(ast::NameRef::cast).collect(); | ||
50 | let used_names = find_used_names(ctx, defs_in_mod, name_refs_in_source_file); | ||
51 | |||
52 | let parent = star.parent().parent()?; | ||
53 | acc.add( | ||
54 | AssistId("expand_glob_import", AssistKind::RefactorRewrite), | ||
55 | "Expand glob import", | ||
56 | parent.text_range(), | ||
57 | |builder| { | ||
58 | replace_ast(builder, &parent, mod_path, used_names); | ||
59 | }, | ||
60 | ) | ||
61 | } | ||
62 | |||
63 | fn find_mod_path(star: &SyntaxToken) -> Option<ast::Path> { | ||
64 | star.ancestors().find_map(|n| ast::UseTree::cast(n).and_then(|u| u.path())) | ||
65 | } | ||
66 | |||
67 | #[derive(PartialEq)] | ||
68 | enum Def { | ||
69 | ModuleDef(ModuleDef), | ||
70 | MacroDef(MacroDef), | ||
71 | } | ||
72 | |||
73 | impl Def { | ||
74 | fn name(&self, db: &RootDatabase) -> Option<Name> { | ||
75 | match self { | ||
76 | Def::ModuleDef(def) => def.name(db), | ||
77 | Def::MacroDef(def) => def.name(db), | ||
78 | } | ||
79 | } | ||
80 | } | ||
81 | |||
82 | fn find_defs_in_mod( | ||
83 | ctx: &AssistContext, | ||
84 | from: SemanticsScope<'_>, | ||
85 | path: &ast::Path, | ||
86 | ) -> Option<Vec<Def>> { | ||
87 | let hir_path = ctx.sema.lower_path(&path)?; | ||
88 | let module = if let Some(PathResolution::Def(ModuleDef::Module(module))) = | ||
89 | from.resolve_hir_path_qualifier(&hir_path) | ||
90 | { | ||
91 | module | ||
92 | } else { | ||
93 | return None; | ||
94 | }; | ||
95 | |||
96 | let module_scope = module.scope(ctx.db(), from.module()); | ||
97 | |||
98 | let mut defs = vec![]; | ||
99 | for (_, def) in module_scope { | ||
100 | match def { | ||
101 | ScopeDef::ModuleDef(def) => defs.push(Def::ModuleDef(def)), | ||
102 | ScopeDef::MacroDef(def) => defs.push(Def::MacroDef(def)), | ||
103 | _ => continue, | ||
104 | } | ||
105 | } | ||
106 | |||
107 | Some(defs) | ||
108 | } | ||
109 | |||
110 | fn find_used_names( | ||
111 | ctx: &AssistContext, | ||
112 | defs_in_mod: Vec<Def>, | ||
113 | name_refs_in_source_file: Vec<ast::NameRef>, | ||
114 | ) -> Vec<Name> { | ||
115 | let defs_in_source_file = name_refs_in_source_file | ||
116 | .iter() | ||
117 | .filter_map(|r| classify_name_ref(&ctx.sema, r)) | ||
118 | .filter_map(|rc| match rc { | ||
119 | NameRefClass::Definition(Definition::ModuleDef(def)) => Some(Def::ModuleDef(def)), | ||
120 | NameRefClass::Definition(Definition::Macro(def)) => Some(Def::MacroDef(def)), | ||
121 | _ => None, | ||
122 | }) | ||
123 | .collect::<Vec<Def>>(); | ||
124 | |||
125 | defs_in_mod | ||
126 | .iter() | ||
127 | .filter(|def| { | ||
128 | if let Def::ModuleDef(ModuleDef::Trait(tr)) = def { | ||
129 | for item in tr.items(ctx.db()) { | ||
130 | if let AssocItem::Function(f) = item { | ||
131 | if defs_in_source_file.contains(&Def::ModuleDef(ModuleDef::Function(f))) { | ||
132 | return true; | ||
133 | } | ||
134 | } | ||
135 | } | ||
136 | } | ||
137 | |||
138 | defs_in_source_file.contains(def) | ||
139 | }) | ||
140 | .filter_map(|d| d.name(ctx.db())) | ||
141 | .collect() | ||
142 | } | ||
143 | |||
144 | fn replace_ast( | ||
145 | builder: &mut AssistBuilder, | ||
146 | node: &SyntaxNode, | ||
147 | path: ast::Path, | ||
148 | used_names: Vec<Name>, | ||
149 | ) { | ||
150 | let replacement: Either<ast::UseTree, ast::UseTreeList> = match used_names.as_slice() { | ||
151 | [name] => Either::Left(ast::make::use_tree( | ||
152 | ast::make::path_from_text(&format!("{}::{}", path, name)), | ||
153 | None, | ||
154 | None, | ||
155 | false, | ||
156 | )), | ||
157 | names => Either::Right(ast::make::use_tree_list(names.iter().map(|n| { | ||
158 | ast::make::use_tree(ast::make::path_from_text(&n.to_string()), None, None, false) | ||
159 | }))), | ||
160 | }; | ||
161 | |||
162 | let mut replace_node = |replacement: Either<ast::UseTree, ast::UseTreeList>| { | ||
163 | algo::diff(node, &replacement.either(|u| u.syntax().clone(), |ut| ut.syntax().clone())) | ||
164 | .into_text_edit(builder.text_edit_builder()); | ||
165 | }; | ||
166 | |||
167 | match_ast! { | ||
168 | match node { | ||
169 | ast::UseTree(use_tree) => { | ||
170 | replace_node(replacement); | ||
171 | }, | ||
172 | ast::UseTreeList(use_tree_list) => { | ||
173 | replace_node(replacement); | ||
174 | }, | ||
175 | ast::Use(use_item) => { | ||
176 | builder.replace_ast(use_item, ast::make::use_(replacement.left_or_else(|ut| ast::make::use_tree(path, Some(ut), None, false)))); | ||
177 | }, | ||
178 | _ => {}, | ||
179 | } | ||
180 | } | ||
181 | } | ||
182 | |||
183 | #[cfg(test)] | ||
184 | mod tests { | ||
185 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
186 | |||
187 | use super::*; | ||
188 | |||
189 | #[test] | ||
190 | fn expanding_glob_import() { | ||
191 | check_assist( | ||
192 | expand_glob_import, | ||
193 | r" | ||
194 | mod foo { | ||
195 | pub struct Bar; | ||
196 | pub struct Baz; | ||
197 | pub struct Qux; | ||
198 | |||
199 | pub fn f() {} | ||
200 | } | ||
201 | |||
202 | use foo::*<|>; | ||
203 | |||
204 | fn qux(bar: Bar, baz: Baz) { | ||
205 | f(); | ||
206 | } | ||
207 | ", | ||
208 | r" | ||
209 | mod foo { | ||
210 | pub struct Bar; | ||
211 | pub struct Baz; | ||
212 | pub struct Qux; | ||
213 | |||
214 | pub fn f() {} | ||
215 | } | ||
216 | |||
217 | use foo::{Baz, Bar, f}; | ||
218 | |||
219 | fn qux(bar: Bar, baz: Baz) { | ||
220 | f(); | ||
221 | } | ||
222 | ", | ||
223 | ) | ||
224 | } | ||
225 | |||
226 | #[test] | ||
227 | fn expanding_glob_import_with_existing_explicit_names() { | ||
228 | check_assist( | ||
229 | expand_glob_import, | ||
230 | r" | ||
231 | mod foo { | ||
232 | pub struct Bar; | ||
233 | pub struct Baz; | ||
234 | pub struct Qux; | ||
235 | |||
236 | pub fn f() {} | ||
237 | } | ||
238 | |||
239 | use foo::{*<|>, f}; | ||
240 | |||
241 | fn qux(bar: Bar, baz: Baz) { | ||
242 | f(); | ||
243 | } | ||
244 | ", | ||
245 | r" | ||
246 | mod foo { | ||
247 | pub struct Bar; | ||
248 | pub struct Baz; | ||
249 | pub struct Qux; | ||
250 | |||
251 | pub fn f() {} | ||
252 | } | ||
253 | |||
254 | use foo::{Baz, Bar, f}; | ||
255 | |||
256 | fn qux(bar: Bar, baz: Baz) { | ||
257 | f(); | ||
258 | } | ||
259 | ", | ||
260 | ) | ||
261 | } | ||
262 | |||
263 | #[test] | ||
264 | fn expanding_nested_glob_import() { | ||
265 | check_assist( | ||
266 | expand_glob_import, | ||
267 | r" | ||
268 | mod foo { | ||
269 | mod bar { | ||
270 | pub struct Bar; | ||
271 | pub struct Baz; | ||
272 | pub struct Qux; | ||
273 | |||
274 | pub fn f() {} | ||
275 | } | ||
276 | |||
277 | mod baz { | ||
278 | pub fn g() {} | ||
279 | } | ||
280 | } | ||
281 | |||
282 | use foo::{bar::{*<|>, f}, baz::*}; | ||
283 | |||
284 | fn qux(bar: Bar, baz: Baz) { | ||
285 | f(); | ||
286 | g(); | ||
287 | } | ||
288 | ", | ||
289 | r" | ||
290 | mod foo { | ||
291 | mod bar { | ||
292 | pub struct Bar; | ||
293 | pub struct Baz; | ||
294 | pub struct Qux; | ||
295 | |||
296 | pub fn f() {} | ||
297 | } | ||
298 | |||
299 | mod baz { | ||
300 | pub fn g() {} | ||
301 | } | ||
302 | } | ||
303 | |||
304 | use foo::{bar::{Baz, Bar, f}, baz::*}; | ||
305 | |||
306 | fn qux(bar: Bar, baz: Baz) { | ||
307 | f(); | ||
308 | g(); | ||
309 | } | ||
310 | ", | ||
311 | ) | ||
312 | } | ||
313 | |||
314 | #[test] | ||
315 | fn expanding_glob_import_with_macro_defs() { | ||
316 | check_assist( | ||
317 | expand_glob_import, | ||
318 | r" | ||
319 | //- /lib.rs crate:foo | ||
320 | #[macro_export] | ||
321 | macro_rules! bar { | ||
322 | () => () | ||
323 | } | ||
324 | |||
325 | pub fn baz() {} | ||
326 | |||
327 | //- /main.rs crate:main deps:foo | ||
328 | use foo::*<|>; | ||
329 | |||
330 | fn main() { | ||
331 | bar!(); | ||
332 | baz(); | ||
333 | } | ||
334 | ", | ||
335 | r" | ||
336 | use foo::{bar, baz}; | ||
337 | |||
338 | fn main() { | ||
339 | bar!(); | ||
340 | baz(); | ||
341 | } | ||
342 | ", | ||
343 | ) | ||
344 | } | ||
345 | |||
346 | #[test] | ||
347 | fn expanding_glob_import_with_trait_method_uses() { | ||
348 | check_assist( | ||
349 | expand_glob_import, | ||
350 | r" | ||
351 | //- /lib.rs crate:foo | ||
352 | pub trait Tr { | ||
353 | fn method(&self) {} | ||
354 | } | ||
355 | impl Tr for () {} | ||
356 | |||
357 | //- /main.rs crate:main deps:foo | ||
358 | use foo::*<|>; | ||
359 | |||
360 | fn main() { | ||
361 | ().method(); | ||
362 | } | ||
363 | ", | ||
364 | r" | ||
365 | use foo::Tr; | ||
366 | |||
367 | fn main() { | ||
368 | ().method(); | ||
369 | } | ||
370 | ", | ||
371 | ) | ||
372 | } | ||
373 | |||
374 | #[test] | ||
375 | fn expanding_is_not_applicable_if_cursor_is_not_in_star_token() { | ||
376 | check_assist_not_applicable( | ||
377 | expand_glob_import, | ||
378 | r" | ||
379 | mod foo { | ||
380 | pub struct Bar; | ||
381 | pub struct Baz; | ||
382 | pub struct Qux; | ||
383 | } | ||
384 | |||
385 | use foo::Bar<|>; | ||
386 | |||
387 | fn qux(bar: Bar, baz: Baz) {} | ||
388 | ", | ||
389 | ) | ||
390 | } | ||
391 | } | ||
diff --git a/crates/ra_assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ra_assists/src/handlers/extract_struct_from_enum_variant.rs deleted file mode 100644 index ccec688ca..000000000 --- a/crates/ra_assists/src/handlers/extract_struct_from_enum_variant.rs +++ /dev/null | |||
@@ -1,321 +0,0 @@ | |||
1 | use hir::{EnumVariant, Module, ModuleDef, Name}; | ||
2 | use ra_db::FileId; | ||
3 | use ra_fmt::leading_indent; | ||
4 | use ra_ide_db::{defs::Definition, search::Reference, RootDatabase}; | ||
5 | use ra_syntax::{ | ||
6 | algo::find_node_at_offset, | ||
7 | ast::{self, ArgListOwner, AstNode, NameOwner, VisibilityOwner}, | ||
8 | SourceFile, SyntaxNode, TextRange, TextSize, | ||
9 | }; | ||
10 | use rustc_hash::FxHashSet; | ||
11 | |||
12 | use crate::{ | ||
13 | assist_context::AssistBuilder, utils::insert_use_statement, AssistContext, AssistId, | ||
14 | AssistKind, Assists, | ||
15 | }; | ||
16 | |||
17 | // Assist: extract_struct_from_enum_variant | ||
18 | // | ||
19 | // Extracts a struct from enum variant. | ||
20 | // | ||
21 | // ``` | ||
22 | // enum A { <|>One(u32, u32) } | ||
23 | // ``` | ||
24 | // -> | ||
25 | // ``` | ||
26 | // struct One(pub u32, pub u32); | ||
27 | // | ||
28 | // enum A { One(One) } | ||
29 | // ``` | ||
30 | pub(crate) fn extract_struct_from_enum_variant( | ||
31 | acc: &mut Assists, | ||
32 | ctx: &AssistContext, | ||
33 | ) -> Option<()> { | ||
34 | let variant = ctx.find_node_at_offset::<ast::Variant>()?; | ||
35 | let field_list = match variant.kind() { | ||
36 | ast::StructKind::Tuple(field_list) => field_list, | ||
37 | _ => return None, | ||
38 | }; | ||
39 | let variant_name = variant.name()?.to_string(); | ||
40 | let variant_hir = ctx.sema.to_def(&variant)?; | ||
41 | if existing_struct_def(ctx.db(), &variant_name, &variant_hir) { | ||
42 | return None; | ||
43 | } | ||
44 | let enum_ast = variant.parent_enum(); | ||
45 | let visibility = enum_ast.visibility(); | ||
46 | let enum_hir = ctx.sema.to_def(&enum_ast)?; | ||
47 | let variant_hir_name = variant_hir.name(ctx.db()); | ||
48 | let enum_module_def = ModuleDef::from(enum_hir); | ||
49 | let current_module = enum_hir.module(ctx.db()); | ||
50 | let target = variant.syntax().text_range(); | ||
51 | acc.add( | ||
52 | AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite), | ||
53 | "Extract struct from enum variant", | ||
54 | target, | ||
55 | |builder| { | ||
56 | let definition = Definition::ModuleDef(ModuleDef::EnumVariant(variant_hir)); | ||
57 | let res = definition.find_usages(&ctx.sema, None); | ||
58 | let start_offset = variant.parent_enum().syntax().text_range().start(); | ||
59 | let mut visited_modules_set = FxHashSet::default(); | ||
60 | visited_modules_set.insert(current_module); | ||
61 | for reference in res { | ||
62 | let source_file = ctx.sema.parse(reference.file_range.file_id); | ||
63 | update_reference( | ||
64 | ctx, | ||
65 | builder, | ||
66 | reference, | ||
67 | &source_file, | ||
68 | &enum_module_def, | ||
69 | &variant_hir_name, | ||
70 | &mut visited_modules_set, | ||
71 | ); | ||
72 | } | ||
73 | extract_struct_def( | ||
74 | builder, | ||
75 | enum_ast.syntax(), | ||
76 | &variant_name, | ||
77 | &field_list.to_string(), | ||
78 | start_offset, | ||
79 | ctx.frange.file_id, | ||
80 | &visibility, | ||
81 | ); | ||
82 | let list_range = field_list.syntax().text_range(); | ||
83 | update_variant(builder, &variant_name, ctx.frange.file_id, list_range); | ||
84 | }, | ||
85 | ) | ||
86 | } | ||
87 | |||
88 | fn existing_struct_def(db: &RootDatabase, variant_name: &str, variant: &EnumVariant) -> bool { | ||
89 | variant | ||
90 | .parent_enum(db) | ||
91 | .module(db) | ||
92 | .scope(db, None) | ||
93 | .into_iter() | ||
94 | .any(|(name, _)| name.to_string() == variant_name.to_string()) | ||
95 | } | ||
96 | |||
97 | fn insert_import( | ||
98 | ctx: &AssistContext, | ||
99 | builder: &mut AssistBuilder, | ||
100 | path: &ast::PathExpr, | ||
101 | module: &Module, | ||
102 | enum_module_def: &ModuleDef, | ||
103 | variant_hir_name: &Name, | ||
104 | ) -> Option<()> { | ||
105 | let db = ctx.db(); | ||
106 | let mod_path = module.find_use_path(db, enum_module_def.clone()); | ||
107 | if let Some(mut mod_path) = mod_path { | ||
108 | mod_path.segments.pop(); | ||
109 | mod_path.segments.push(variant_hir_name.clone()); | ||
110 | insert_use_statement(path.syntax(), &mod_path, ctx, builder.text_edit_builder()); | ||
111 | } | ||
112 | Some(()) | ||
113 | } | ||
114 | |||
115 | fn extract_struct_def( | ||
116 | builder: &mut AssistBuilder, | ||
117 | enum_ast: &SyntaxNode, | ||
118 | variant_name: &str, | ||
119 | variant_list: &str, | ||
120 | start_offset: TextSize, | ||
121 | file_id: FileId, | ||
122 | visibility: &Option<ast::Visibility>, | ||
123 | ) -> Option<()> { | ||
124 | let visibility_string = if let Some(visibility) = visibility { | ||
125 | format!("{} ", visibility.to_string()) | ||
126 | } else { | ||
127 | "".to_string() | ||
128 | }; | ||
129 | let indent = if let Some(indent) = leading_indent(enum_ast) { | ||
130 | indent.to_string() | ||
131 | } else { | ||
132 | "".to_string() | ||
133 | }; | ||
134 | let struct_def = format!( | ||
135 | r#"{}struct {}{}; | ||
136 | |||
137 | {}"#, | ||
138 | visibility_string, | ||
139 | variant_name, | ||
140 | list_with_visibility(variant_list), | ||
141 | indent | ||
142 | ); | ||
143 | builder.edit_file(file_id); | ||
144 | builder.insert(start_offset, struct_def); | ||
145 | Some(()) | ||
146 | } | ||
147 | |||
148 | fn update_variant( | ||
149 | builder: &mut AssistBuilder, | ||
150 | variant_name: &str, | ||
151 | file_id: FileId, | ||
152 | list_range: TextRange, | ||
153 | ) -> Option<()> { | ||
154 | let inside_variant_range = TextRange::new( | ||
155 | list_range.start().checked_add(TextSize::from(1))?, | ||
156 | list_range.end().checked_sub(TextSize::from(1))?, | ||
157 | ); | ||
158 | builder.edit_file(file_id); | ||
159 | builder.replace(inside_variant_range, variant_name); | ||
160 | Some(()) | ||
161 | } | ||
162 | |||
163 | fn update_reference( | ||
164 | ctx: &AssistContext, | ||
165 | builder: &mut AssistBuilder, | ||
166 | reference: Reference, | ||
167 | source_file: &SourceFile, | ||
168 | enum_module_def: &ModuleDef, | ||
169 | variant_hir_name: &Name, | ||
170 | visited_modules_set: &mut FxHashSet<Module>, | ||
171 | ) -> Option<()> { | ||
172 | let path_expr: ast::PathExpr = find_node_at_offset::<ast::PathExpr>( | ||
173 | source_file.syntax(), | ||
174 | reference.file_range.range.start(), | ||
175 | )?; | ||
176 | let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?; | ||
177 | let list = call.arg_list()?; | ||
178 | let segment = path_expr.path()?.segment()?; | ||
179 | let module = ctx.sema.scope(&path_expr.syntax()).module()?; | ||
180 | let list_range = list.syntax().text_range(); | ||
181 | let inside_list_range = TextRange::new( | ||
182 | list_range.start().checked_add(TextSize::from(1))?, | ||
183 | list_range.end().checked_sub(TextSize::from(1))?, | ||
184 | ); | ||
185 | builder.edit_file(reference.file_range.file_id); | ||
186 | if !visited_modules_set.contains(&module) { | ||
187 | if insert_import(ctx, builder, &path_expr, &module, enum_module_def, variant_hir_name) | ||
188 | .is_some() | ||
189 | { | ||
190 | visited_modules_set.insert(module); | ||
191 | } | ||
192 | } | ||
193 | builder.replace(inside_list_range, format!("{}{}", segment, list)); | ||
194 | Some(()) | ||
195 | } | ||
196 | |||
197 | fn list_with_visibility(list: &str) -> String { | ||
198 | list.split(',') | ||
199 | .map(|part| { | ||
200 | let index = if part.chars().next().unwrap() == '(' { 1usize } else { 0 }; | ||
201 | let mut mod_part = part.trim().to_string(); | ||
202 | mod_part.insert_str(index, "pub "); | ||
203 | mod_part | ||
204 | }) | ||
205 | .collect::<Vec<String>>() | ||
206 | .join(", ") | ||
207 | } | ||
208 | |||
209 | #[cfg(test)] | ||
210 | mod tests { | ||
211 | |||
212 | use crate::{ | ||
213 | tests::{check_assist, check_assist_not_applicable}, | ||
214 | utils::FamousDefs, | ||
215 | }; | ||
216 | |||
217 | use super::*; | ||
218 | |||
219 | #[test] | ||
220 | fn test_extract_struct_several_fields() { | ||
221 | check_assist( | ||
222 | extract_struct_from_enum_variant, | ||
223 | "enum A { <|>One(u32, u32) }", | ||
224 | r#"struct One(pub u32, pub u32); | ||
225 | |||
226 | enum A { One(One) }"#, | ||
227 | ); | ||
228 | } | ||
229 | |||
230 | #[test] | ||
231 | fn test_extract_struct_one_field() { | ||
232 | check_assist( | ||
233 | extract_struct_from_enum_variant, | ||
234 | "enum A { <|>One(u32) }", | ||
235 | r#"struct One(pub u32); | ||
236 | |||
237 | enum A { One(One) }"#, | ||
238 | ); | ||
239 | } | ||
240 | |||
241 | #[test] | ||
242 | fn test_extract_struct_pub_visibility() { | ||
243 | check_assist( | ||
244 | extract_struct_from_enum_variant, | ||
245 | "pub enum A { <|>One(u32, u32) }", | ||
246 | r#"pub struct One(pub u32, pub u32); | ||
247 | |||
248 | pub enum A { One(One) }"#, | ||
249 | ); | ||
250 | } | ||
251 | |||
252 | #[test] | ||
253 | fn test_extract_struct_with_complex_imports() { | ||
254 | check_assist( | ||
255 | extract_struct_from_enum_variant, | ||
256 | r#"mod my_mod { | ||
257 | fn another_fn() { | ||
258 | let m = my_other_mod::MyEnum::MyField(1, 1); | ||
259 | } | ||
260 | |||
261 | pub mod my_other_mod { | ||
262 | fn another_fn() { | ||
263 | let m = MyEnum::MyField(1, 1); | ||
264 | } | ||
265 | |||
266 | pub enum MyEnum { | ||
267 | <|>MyField(u8, u8), | ||
268 | } | ||
269 | } | ||
270 | } | ||
271 | |||
272 | fn another_fn() { | ||
273 | let m = my_mod::my_other_mod::MyEnum::MyField(1, 1); | ||
274 | }"#, | ||
275 | r#"use my_mod::my_other_mod::MyField; | ||
276 | |||
277 | mod my_mod { | ||
278 | use my_other_mod::MyField; | ||
279 | |||
280 | fn another_fn() { | ||
281 | let m = my_other_mod::MyEnum::MyField(MyField(1, 1)); | ||
282 | } | ||
283 | |||
284 | pub mod my_other_mod { | ||
285 | fn another_fn() { | ||
286 | let m = MyEnum::MyField(MyField(1, 1)); | ||
287 | } | ||
288 | |||
289 | pub struct MyField(pub u8, pub u8); | ||
290 | |||
291 | pub enum MyEnum { | ||
292 | MyField(MyField), | ||
293 | } | ||
294 | } | ||
295 | } | ||
296 | |||
297 | fn another_fn() { | ||
298 | let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1)); | ||
299 | }"#, | ||
300 | ); | ||
301 | } | ||
302 | |||
303 | fn check_not_applicable(ra_fixture: &str) { | ||
304 | let fixture = | ||
305 | format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE); | ||
306 | check_assist_not_applicable(extract_struct_from_enum_variant, &fixture) | ||
307 | } | ||
308 | |||
309 | #[test] | ||
310 | fn test_extract_enum_not_applicable_for_element_with_no_fields() { | ||
311 | check_not_applicable("enum A { <|>One }"); | ||
312 | } | ||
313 | |||
314 | #[test] | ||
315 | fn test_extract_enum_not_applicable_if_struct_exists() { | ||
316 | check_not_applicable( | ||
317 | r#"struct One; | ||
318 | enum A { <|>One(u8) }"#, | ||
319 | ); | ||
320 | } | ||
321 | } | ||
diff --git a/crates/ra_assists/src/handlers/extract_variable.rs b/crates/ra_assists/src/handlers/extract_variable.rs deleted file mode 100644 index cc62db0c4..000000000 --- a/crates/ra_assists/src/handlers/extract_variable.rs +++ /dev/null | |||
@@ -1,588 +0,0 @@ | |||
1 | use ra_syntax::{ | ||
2 | ast::{self, AstNode}, | ||
3 | SyntaxKind::{ | ||
4 | BLOCK_EXPR, BREAK_EXPR, CLOSURE_EXPR, COMMENT, LOOP_EXPR, MATCH_ARM, PATH_EXPR, RETURN_EXPR, | ||
5 | }, | ||
6 | SyntaxNode, | ||
7 | }; | ||
8 | use stdx::format_to; | ||
9 | use test_utils::mark; | ||
10 | |||
11 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
12 | |||
13 | // Assist: extract_variable | ||
14 | // | ||
15 | // Extracts subexpression into a variable. | ||
16 | // | ||
17 | // ``` | ||
18 | // fn main() { | ||
19 | // <|>(1 + 2)<|> * 4; | ||
20 | // } | ||
21 | // ``` | ||
22 | // -> | ||
23 | // ``` | ||
24 | // fn main() { | ||
25 | // let $0var_name = (1 + 2); | ||
26 | // var_name * 4; | ||
27 | // } | ||
28 | // ``` | ||
29 | pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
30 | if ctx.frange.range.is_empty() { | ||
31 | return None; | ||
32 | } | ||
33 | let node = ctx.covering_element(); | ||
34 | if node.kind() == COMMENT { | ||
35 | mark::hit!(extract_var_in_comment_is_not_applicable); | ||
36 | return None; | ||
37 | } | ||
38 | let to_extract = node.ancestors().find_map(valid_target_expr)?; | ||
39 | let anchor = Anchor::from(&to_extract)?; | ||
40 | let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone(); | ||
41 | let target = to_extract.syntax().text_range(); | ||
42 | acc.add( | ||
43 | AssistId("extract_variable", AssistKind::RefactorExtract), | ||
44 | "Extract into variable", | ||
45 | target, | ||
46 | move |edit| { | ||
47 | let field_shorthand = | ||
48 | match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) { | ||
49 | Some(field) => field.name_ref(), | ||
50 | None => None, | ||
51 | }; | ||
52 | |||
53 | let mut buf = String::new(); | ||
54 | |||
55 | let var_name = match &field_shorthand { | ||
56 | Some(it) => it.to_string(), | ||
57 | None => "var_name".to_string(), | ||
58 | }; | ||
59 | let expr_range = match &field_shorthand { | ||
60 | Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()), | ||
61 | None => to_extract.syntax().text_range(), | ||
62 | }; | ||
63 | |||
64 | if let Anchor::WrapInBlock(_) = anchor { | ||
65 | format_to!(buf, "{{ let {} = ", var_name); | ||
66 | } else { | ||
67 | format_to!(buf, "let {} = ", var_name); | ||
68 | }; | ||
69 | format_to!(buf, "{}", to_extract.syntax()); | ||
70 | |||
71 | if let Anchor::Replace(stmt) = anchor { | ||
72 | mark::hit!(test_extract_var_expr_stmt); | ||
73 | if stmt.semicolon_token().is_none() { | ||
74 | buf.push_str(";"); | ||
75 | } | ||
76 | match ctx.config.snippet_cap { | ||
77 | Some(cap) => { | ||
78 | let snip = buf | ||
79 | .replace(&format!("let {}", var_name), &format!("let $0{}", var_name)); | ||
80 | edit.replace_snippet(cap, expr_range, snip) | ||
81 | } | ||
82 | None => edit.replace(expr_range, buf), | ||
83 | } | ||
84 | return; | ||
85 | } | ||
86 | |||
87 | buf.push_str(";"); | ||
88 | |||
89 | // We want to maintain the indent level, | ||
90 | // but we do not want to duplicate possible | ||
91 | // extra newlines in the indent block | ||
92 | let text = indent.text(); | ||
93 | if text.starts_with('\n') { | ||
94 | buf.push_str("\n"); | ||
95 | buf.push_str(text.trim_start_matches('\n')); | ||
96 | } else { | ||
97 | buf.push_str(text); | ||
98 | } | ||
99 | |||
100 | edit.replace(expr_range, var_name.clone()); | ||
101 | let offset = anchor.syntax().text_range().start(); | ||
102 | match ctx.config.snippet_cap { | ||
103 | Some(cap) => { | ||
104 | let snip = | ||
105 | buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name)); | ||
106 | edit.insert_snippet(cap, offset, snip) | ||
107 | } | ||
108 | None => edit.insert(offset, buf), | ||
109 | } | ||
110 | |||
111 | if let Anchor::WrapInBlock(_) = anchor { | ||
112 | edit.insert(anchor.syntax().text_range().end(), " }"); | ||
113 | } | ||
114 | }, | ||
115 | ) | ||
116 | } | ||
117 | |||
118 | /// Check whether the node is a valid expression which can be extracted to a variable. | ||
119 | /// In general that's true for any expression, but in some cases that would produce invalid code. | ||
120 | fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> { | ||
121 | match node.kind() { | ||
122 | PATH_EXPR | LOOP_EXPR => None, | ||
123 | BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()), | ||
124 | RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()), | ||
125 | BLOCK_EXPR => { | ||
126 | ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from) | ||
127 | } | ||
128 | _ => ast::Expr::cast(node), | ||
129 | } | ||
130 | } | ||
131 | |||
132 | enum Anchor { | ||
133 | Before(SyntaxNode), | ||
134 | Replace(ast::ExprStmt), | ||
135 | WrapInBlock(SyntaxNode), | ||
136 | } | ||
137 | |||
138 | impl Anchor { | ||
139 | fn from(to_extract: &ast::Expr) -> Option<Anchor> { | ||
140 | to_extract.syntax().ancestors().find_map(|node| { | ||
141 | if let Some(expr) = | ||
142 | node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.expr()) | ||
143 | { | ||
144 | if expr.syntax() == &node { | ||
145 | mark::hit!(test_extract_var_last_expr); | ||
146 | return Some(Anchor::Before(node)); | ||
147 | } | ||
148 | } | ||
149 | |||
150 | if let Some(parent) = node.parent() { | ||
151 | if parent.kind() == MATCH_ARM || parent.kind() == CLOSURE_EXPR { | ||
152 | return Some(Anchor::WrapInBlock(node)); | ||
153 | } | ||
154 | } | ||
155 | |||
156 | if let Some(stmt) = ast::Stmt::cast(node.clone()) { | ||
157 | if let ast::Stmt::ExprStmt(stmt) = stmt { | ||
158 | if stmt.expr().as_ref() == Some(to_extract) { | ||
159 | return Some(Anchor::Replace(stmt)); | ||
160 | } | ||
161 | } | ||
162 | return Some(Anchor::Before(node)); | ||
163 | } | ||
164 | None | ||
165 | }) | ||
166 | } | ||
167 | |||
168 | fn syntax(&self) -> &SyntaxNode { | ||
169 | match self { | ||
170 | Anchor::Before(it) | Anchor::WrapInBlock(it) => it, | ||
171 | Anchor::Replace(stmt) => stmt.syntax(), | ||
172 | } | ||
173 | } | ||
174 | } | ||
175 | |||
176 | #[cfg(test)] | ||
177 | mod tests { | ||
178 | use test_utils::mark; | ||
179 | |||
180 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
181 | |||
182 | use super::*; | ||
183 | |||
184 | #[test] | ||
185 | fn test_extract_var_simple() { | ||
186 | check_assist( | ||
187 | extract_variable, | ||
188 | r#" | ||
189 | fn foo() { | ||
190 | foo(<|>1 + 1<|>); | ||
191 | }"#, | ||
192 | r#" | ||
193 | fn foo() { | ||
194 | let $0var_name = 1 + 1; | ||
195 | foo(var_name); | ||
196 | }"#, | ||
197 | ); | ||
198 | } | ||
199 | |||
200 | #[test] | ||
201 | fn extract_var_in_comment_is_not_applicable() { | ||
202 | mark::check!(extract_var_in_comment_is_not_applicable); | ||
203 | check_assist_not_applicable(extract_variable, "fn main() { 1 + /* <|>comment<|> */ 1; }"); | ||
204 | } | ||
205 | |||
206 | #[test] | ||
207 | fn test_extract_var_expr_stmt() { | ||
208 | mark::check!(test_extract_var_expr_stmt); | ||
209 | check_assist( | ||
210 | extract_variable, | ||
211 | r#" | ||
212 | fn foo() { | ||
213 | <|>1 + 1<|>; | ||
214 | }"#, | ||
215 | r#" | ||
216 | fn foo() { | ||
217 | let $0var_name = 1 + 1; | ||
218 | }"#, | ||
219 | ); | ||
220 | check_assist( | ||
221 | extract_variable, | ||
222 | " | ||
223 | fn foo() { | ||
224 | <|>{ let x = 0; x }<|> | ||
225 | something_else(); | ||
226 | }", | ||
227 | " | ||
228 | fn foo() { | ||
229 | let $0var_name = { let x = 0; x }; | ||
230 | something_else(); | ||
231 | }", | ||
232 | ); | ||
233 | } | ||
234 | |||
235 | #[test] | ||
236 | fn test_extract_var_part_of_expr_stmt() { | ||
237 | check_assist( | ||
238 | extract_variable, | ||
239 | " | ||
240 | fn foo() { | ||
241 | <|>1<|> + 1; | ||
242 | }", | ||
243 | " | ||
244 | fn foo() { | ||
245 | let $0var_name = 1; | ||
246 | var_name + 1; | ||
247 | }", | ||
248 | ); | ||
249 | } | ||
250 | |||
251 | #[test] | ||
252 | fn test_extract_var_last_expr() { | ||
253 | mark::check!(test_extract_var_last_expr); | ||
254 | check_assist( | ||
255 | extract_variable, | ||
256 | r#" | ||
257 | fn foo() { | ||
258 | bar(<|>1 + 1<|>) | ||
259 | } | ||
260 | "#, | ||
261 | r#" | ||
262 | fn foo() { | ||
263 | let $0var_name = 1 + 1; | ||
264 | bar(var_name) | ||
265 | } | ||
266 | "#, | ||
267 | ); | ||
268 | check_assist( | ||
269 | extract_variable, | ||
270 | r#" | ||
271 | fn foo() { | ||
272 | <|>bar(1 + 1)<|> | ||
273 | } | ||
274 | "#, | ||
275 | r#" | ||
276 | fn foo() { | ||
277 | let $0var_name = bar(1 + 1); | ||
278 | var_name | ||
279 | } | ||
280 | "#, | ||
281 | ) | ||
282 | } | ||
283 | |||
284 | #[test] | ||
285 | fn test_extract_var_in_match_arm_no_block() { | ||
286 | check_assist( | ||
287 | extract_variable, | ||
288 | " | ||
289 | fn main() { | ||
290 | let x = true; | ||
291 | let tuple = match x { | ||
292 | true => (<|>2 + 2<|>, true) | ||
293 | _ => (0, false) | ||
294 | }; | ||
295 | } | ||
296 | ", | ||
297 | " | ||
298 | fn main() { | ||
299 | let x = true; | ||
300 | let tuple = match x { | ||
301 | true => { let $0var_name = 2 + 2; (var_name, true) } | ||
302 | _ => (0, false) | ||
303 | }; | ||
304 | } | ||
305 | ", | ||
306 | ); | ||
307 | } | ||
308 | |||
309 | #[test] | ||
310 | fn test_extract_var_in_match_arm_with_block() { | ||
311 | check_assist( | ||
312 | extract_variable, | ||
313 | " | ||
314 | fn main() { | ||
315 | let x = true; | ||
316 | let tuple = match x { | ||
317 | true => { | ||
318 | let y = 1; | ||
319 | (<|>2 + y<|>, true) | ||
320 | } | ||
321 | _ => (0, false) | ||
322 | }; | ||
323 | } | ||
324 | ", | ||
325 | " | ||
326 | fn main() { | ||
327 | let x = true; | ||
328 | let tuple = match x { | ||
329 | true => { | ||
330 | let y = 1; | ||
331 | let $0var_name = 2 + y; | ||
332 | (var_name, true) | ||
333 | } | ||
334 | _ => (0, false) | ||
335 | }; | ||
336 | } | ||
337 | ", | ||
338 | ); | ||
339 | } | ||
340 | |||
341 | #[test] | ||
342 | fn test_extract_var_in_closure_no_block() { | ||
343 | check_assist( | ||
344 | extract_variable, | ||
345 | " | ||
346 | fn main() { | ||
347 | let lambda = |x: u32| <|>x * 2<|>; | ||
348 | } | ||
349 | ", | ||
350 | " | ||
351 | fn main() { | ||
352 | let lambda = |x: u32| { let $0var_name = x * 2; var_name }; | ||
353 | } | ||
354 | ", | ||
355 | ); | ||
356 | } | ||
357 | |||
358 | #[test] | ||
359 | fn test_extract_var_in_closure_with_block() { | ||
360 | check_assist( | ||
361 | extract_variable, | ||
362 | " | ||
363 | fn main() { | ||
364 | let lambda = |x: u32| { <|>x * 2<|> }; | ||
365 | } | ||
366 | ", | ||
367 | " | ||
368 | fn main() { | ||
369 | let lambda = |x: u32| { let $0var_name = x * 2; var_name }; | ||
370 | } | ||
371 | ", | ||
372 | ); | ||
373 | } | ||
374 | |||
375 | #[test] | ||
376 | fn test_extract_var_path_simple() { | ||
377 | check_assist( | ||
378 | extract_variable, | ||
379 | " | ||
380 | fn main() { | ||
381 | let o = <|>Some(true)<|>; | ||
382 | } | ||
383 | ", | ||
384 | " | ||
385 | fn main() { | ||
386 | let $0var_name = Some(true); | ||
387 | let o = var_name; | ||
388 | } | ||
389 | ", | ||
390 | ); | ||
391 | } | ||
392 | |||
393 | #[test] | ||
394 | fn test_extract_var_path_method() { | ||
395 | check_assist( | ||
396 | extract_variable, | ||
397 | " | ||
398 | fn main() { | ||
399 | let v = <|>bar.foo()<|>; | ||
400 | } | ||
401 | ", | ||
402 | " | ||
403 | fn main() { | ||
404 | let $0var_name = bar.foo(); | ||
405 | let v = var_name; | ||
406 | } | ||
407 | ", | ||
408 | ); | ||
409 | } | ||
410 | |||
411 | #[test] | ||
412 | fn test_extract_var_return() { | ||
413 | check_assist( | ||
414 | extract_variable, | ||
415 | " | ||
416 | fn foo() -> u32 { | ||
417 | <|>return 2 + 2<|>; | ||
418 | } | ||
419 | ", | ||
420 | " | ||
421 | fn foo() -> u32 { | ||
422 | let $0var_name = 2 + 2; | ||
423 | return var_name; | ||
424 | } | ||
425 | ", | ||
426 | ); | ||
427 | } | ||
428 | |||
429 | #[test] | ||
430 | fn test_extract_var_does_not_add_extra_whitespace() { | ||
431 | check_assist( | ||
432 | extract_variable, | ||
433 | " | ||
434 | fn foo() -> u32 { | ||
435 | |||
436 | |||
437 | <|>return 2 + 2<|>; | ||
438 | } | ||
439 | ", | ||
440 | " | ||
441 | fn foo() -> u32 { | ||
442 | |||
443 | |||
444 | let $0var_name = 2 + 2; | ||
445 | return var_name; | ||
446 | } | ||
447 | ", | ||
448 | ); | ||
449 | |||
450 | check_assist( | ||
451 | extract_variable, | ||
452 | " | ||
453 | fn foo() -> u32 { | ||
454 | |||
455 | <|>return 2 + 2<|>; | ||
456 | } | ||
457 | ", | ||
458 | " | ||
459 | fn foo() -> u32 { | ||
460 | |||
461 | let $0var_name = 2 + 2; | ||
462 | return var_name; | ||
463 | } | ||
464 | ", | ||
465 | ); | ||
466 | |||
467 | check_assist( | ||
468 | extract_variable, | ||
469 | " | ||
470 | fn foo() -> u32 { | ||
471 | let foo = 1; | ||
472 | |||
473 | // bar | ||
474 | |||
475 | |||
476 | <|>return 2 + 2<|>; | ||
477 | } | ||
478 | ", | ||
479 | " | ||
480 | fn foo() -> u32 { | ||
481 | let foo = 1; | ||
482 | |||
483 | // bar | ||
484 | |||
485 | |||
486 | let $0var_name = 2 + 2; | ||
487 | return var_name; | ||
488 | } | ||
489 | ", | ||
490 | ); | ||
491 | } | ||
492 | |||
493 | #[test] | ||
494 | fn test_extract_var_break() { | ||
495 | check_assist( | ||
496 | extract_variable, | ||
497 | " | ||
498 | fn main() { | ||
499 | let result = loop { | ||
500 | <|>break 2 + 2<|>; | ||
501 | }; | ||
502 | } | ||
503 | ", | ||
504 | " | ||
505 | fn main() { | ||
506 | let result = loop { | ||
507 | let $0var_name = 2 + 2; | ||
508 | break var_name; | ||
509 | }; | ||
510 | } | ||
511 | ", | ||
512 | ); | ||
513 | } | ||
514 | |||
515 | #[test] | ||
516 | fn test_extract_var_for_cast() { | ||
517 | check_assist( | ||
518 | extract_variable, | ||
519 | " | ||
520 | fn main() { | ||
521 | let v = <|>0f32 as u32<|>; | ||
522 | } | ||
523 | ", | ||
524 | " | ||
525 | fn main() { | ||
526 | let $0var_name = 0f32 as u32; | ||
527 | let v = var_name; | ||
528 | } | ||
529 | ", | ||
530 | ); | ||
531 | } | ||
532 | |||
533 | #[test] | ||
534 | fn extract_var_field_shorthand() { | ||
535 | check_assist( | ||
536 | extract_variable, | ||
537 | r#" | ||
538 | struct S { | ||
539 | foo: i32 | ||
540 | } | ||
541 | |||
542 | fn main() { | ||
543 | S { foo: <|>1 + 1<|> } | ||
544 | } | ||
545 | "#, | ||
546 | r#" | ||
547 | struct S { | ||
548 | foo: i32 | ||
549 | } | ||
550 | |||
551 | fn main() { | ||
552 | let $0foo = 1 + 1; | ||
553 | S { foo } | ||
554 | } | ||
555 | "#, | ||
556 | ) | ||
557 | } | ||
558 | |||
559 | #[test] | ||
560 | fn test_extract_var_for_return_not_applicable() { | ||
561 | check_assist_not_applicable(extract_variable, "fn foo() { <|>return<|>; } "); | ||
562 | } | ||
563 | |||
564 | #[test] | ||
565 | fn test_extract_var_for_break_not_applicable() { | ||
566 | check_assist_not_applicable(extract_variable, "fn main() { loop { <|>break<|>; }; }"); | ||
567 | } | ||
568 | |||
569 | // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic | ||
570 | #[test] | ||
571 | fn extract_var_target() { | ||
572 | check_assist_target(extract_variable, "fn foo() -> u32 { <|>return 2 + 2<|>; }", "2 + 2"); | ||
573 | |||
574 | check_assist_target( | ||
575 | extract_variable, | ||
576 | " | ||
577 | fn main() { | ||
578 | let x = true; | ||
579 | let tuple = match x { | ||
580 | true => (<|>2 + 2<|>, true) | ||
581 | _ => (0, false) | ||
582 | }; | ||
583 | } | ||
584 | ", | ||
585 | "2 + 2", | ||
586 | ); | ||
587 | } | ||
588 | } | ||
diff --git a/crates/ra_assists/src/handlers/fill_match_arms.rs b/crates/ra_assists/src/handlers/fill_match_arms.rs deleted file mode 100644 index 6698d1a27..000000000 --- a/crates/ra_assists/src/handlers/fill_match_arms.rs +++ /dev/null | |||
@@ -1,747 +0,0 @@ | |||
1 | use std::iter; | ||
2 | |||
3 | use hir::{Adt, HasSource, ModuleDef, Semantics}; | ||
4 | use itertools::Itertools; | ||
5 | use ra_ide_db::RootDatabase; | ||
6 | use ra_syntax::ast::{self, make, AstNode, MatchArm, NameOwner, Pat}; | ||
7 | use test_utils::mark; | ||
8 | |||
9 | use crate::{ | ||
10 | utils::{render_snippet, Cursor, FamousDefs}, | ||
11 | AssistContext, AssistId, AssistKind, Assists, | ||
12 | }; | ||
13 | |||
14 | // Assist: fill_match_arms | ||
15 | // | ||
16 | // Adds missing clauses to a `match` expression. | ||
17 | // | ||
18 | // ``` | ||
19 | // enum Action { Move { distance: u32 }, Stop } | ||
20 | // | ||
21 | // fn handle(action: Action) { | ||
22 | // match action { | ||
23 | // <|> | ||
24 | // } | ||
25 | // } | ||
26 | // ``` | ||
27 | // -> | ||
28 | // ``` | ||
29 | // enum Action { Move { distance: u32 }, Stop } | ||
30 | // | ||
31 | // fn handle(action: Action) { | ||
32 | // match action { | ||
33 | // $0Action::Move { distance } => {} | ||
34 | // Action::Stop => {} | ||
35 | // } | ||
36 | // } | ||
37 | // ``` | ||
38 | pub(crate) fn fill_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
39 | let match_expr = ctx.find_node_at_offset::<ast::MatchExpr>()?; | ||
40 | let match_arm_list = match_expr.match_arm_list()?; | ||
41 | |||
42 | let expr = match_expr.expr()?; | ||
43 | |||
44 | let mut arms: Vec<MatchArm> = match_arm_list.arms().collect(); | ||
45 | if arms.len() == 1 { | ||
46 | if let Some(Pat::WildcardPat(..)) = arms[0].pat() { | ||
47 | arms.clear(); | ||
48 | } | ||
49 | } | ||
50 | |||
51 | let module = ctx.sema.scope(expr.syntax()).module()?; | ||
52 | |||
53 | let missing_arms: Vec<MatchArm> = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) { | ||
54 | let variants = enum_def.variants(ctx.db()); | ||
55 | |||
56 | let mut variants = variants | ||
57 | .into_iter() | ||
58 | .filter_map(|variant| build_pat(ctx.db(), module, variant)) | ||
59 | .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat)) | ||
60 | .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block())) | ||
61 | .collect::<Vec<_>>(); | ||
62 | if Some(enum_def) == FamousDefs(&ctx.sema, module.krate()).core_option_Option() { | ||
63 | // Match `Some` variant first. | ||
64 | mark::hit!(option_order); | ||
65 | variants.reverse() | ||
66 | } | ||
67 | variants | ||
68 | } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) { | ||
69 | // Partial fill not currently supported for tuple of enums. | ||
70 | if !arms.is_empty() { | ||
71 | return None; | ||
72 | } | ||
73 | |||
74 | // We do not currently support filling match arms for a tuple | ||
75 | // containing a single enum. | ||
76 | if enum_defs.len() < 2 { | ||
77 | return None; | ||
78 | } | ||
79 | |||
80 | // When calculating the match arms for a tuple of enums, we want | ||
81 | // to create a match arm for each possible combination of enum | ||
82 | // values. The `multi_cartesian_product` method transforms | ||
83 | // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)> | ||
84 | // where each tuple represents a proposed match arm. | ||
85 | enum_defs | ||
86 | .into_iter() | ||
87 | .map(|enum_def| enum_def.variants(ctx.db())) | ||
88 | .multi_cartesian_product() | ||
89 | .map(|variants| { | ||
90 | let patterns = | ||
91 | variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant)); | ||
92 | ast::Pat::from(make::tuple_pat(patterns)) | ||
93 | }) | ||
94 | .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat)) | ||
95 | .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block())) | ||
96 | .collect() | ||
97 | } else { | ||
98 | return None; | ||
99 | }; | ||
100 | |||
101 | if missing_arms.is_empty() { | ||
102 | return None; | ||
103 | } | ||
104 | |||
105 | let target = match_expr.syntax().text_range(); | ||
106 | acc.add( | ||
107 | AssistId("fill_match_arms", AssistKind::QuickFix), | ||
108 | "Fill match arms", | ||
109 | target, | ||
110 | |builder| { | ||
111 | let new_arm_list = match_arm_list.remove_placeholder(); | ||
112 | let n_old_arms = new_arm_list.arms().count(); | ||
113 | let new_arm_list = new_arm_list.append_arms(missing_arms); | ||
114 | let first_new_arm = new_arm_list.arms().nth(n_old_arms); | ||
115 | let old_range = match_arm_list.syntax().text_range(); | ||
116 | match (first_new_arm, ctx.config.snippet_cap) { | ||
117 | (Some(first_new_arm), Some(cap)) => { | ||
118 | let extend_lifetime; | ||
119 | let cursor = | ||
120 | match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast) | ||
121 | { | ||
122 | Some(it) => { | ||
123 | extend_lifetime = it.syntax().clone(); | ||
124 | Cursor::Replace(&extend_lifetime) | ||
125 | } | ||
126 | None => Cursor::Before(first_new_arm.syntax()), | ||
127 | }; | ||
128 | let snippet = render_snippet(cap, new_arm_list.syntax(), cursor); | ||
129 | builder.replace_snippet(cap, old_range, snippet); | ||
130 | } | ||
131 | _ => builder.replace(old_range, new_arm_list.to_string()), | ||
132 | } | ||
133 | }, | ||
134 | ) | ||
135 | } | ||
136 | |||
137 | fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool { | ||
138 | existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| { | ||
139 | // Special casee OrPat as separate top-level pats | ||
140 | let top_level_pats: Vec<Pat> = match pat { | ||
141 | Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(), | ||
142 | _ => vec![pat], | ||
143 | }; | ||
144 | |||
145 | !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var)) | ||
146 | }) | ||
147 | } | ||
148 | |||
149 | fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool { | ||
150 | let first_node_text = |pat: &Pat| pat.syntax().first_child().map(|node| node.text()); | ||
151 | |||
152 | let pat_head = match pat { | ||
153 | Pat::IdentPat(bind_pat) => { | ||
154 | if let Some(p) = bind_pat.pat() { | ||
155 | first_node_text(&p) | ||
156 | } else { | ||
157 | return false; | ||
158 | } | ||
159 | } | ||
160 | pat => first_node_text(pat), | ||
161 | }; | ||
162 | |||
163 | let var_head = first_node_text(var); | ||
164 | |||
165 | pat_head == var_head | ||
166 | } | ||
167 | |||
168 | fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> { | ||
169 | sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() { | ||
170 | Some(Adt::Enum(e)) => Some(e), | ||
171 | _ => None, | ||
172 | }) | ||
173 | } | ||
174 | |||
175 | fn resolve_tuple_of_enum_def( | ||
176 | sema: &Semantics<RootDatabase>, | ||
177 | expr: &ast::Expr, | ||
178 | ) -> Option<Vec<hir::Enum>> { | ||
179 | sema.type_of_expr(&expr)? | ||
180 | .tuple_fields(sema.db) | ||
181 | .iter() | ||
182 | .map(|ty| { | ||
183 | ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() { | ||
184 | Some(Adt::Enum(e)) => Some(e), | ||
185 | // For now we only handle expansion for a tuple of enums. Here | ||
186 | // we map non-enum items to None and rely on `collect` to | ||
187 | // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>. | ||
188 | _ => None, | ||
189 | }) | ||
190 | }) | ||
191 | .collect() | ||
192 | } | ||
193 | |||
194 | fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> { | ||
195 | let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?); | ||
196 | |||
197 | // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though | ||
198 | let pat: ast::Pat = match var.source(db).value.kind() { | ||
199 | ast::StructKind::Tuple(field_list) => { | ||
200 | let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count()); | ||
201 | make::tuple_struct_pat(path, pats).into() | ||
202 | } | ||
203 | ast::StructKind::Record(field_list) => { | ||
204 | let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into()); | ||
205 | make::record_pat(path, pats).into() | ||
206 | } | ||
207 | ast::StructKind::Unit => make::path_pat(path), | ||
208 | }; | ||
209 | |||
210 | Some(pat) | ||
211 | } | ||
212 | |||
213 | #[cfg(test)] | ||
214 | mod tests { | ||
215 | use test_utils::mark; | ||
216 | |||
217 | use crate::{ | ||
218 | tests::{check_assist, check_assist_not_applicable, check_assist_target}, | ||
219 | utils::FamousDefs, | ||
220 | }; | ||
221 | |||
222 | use super::fill_match_arms; | ||
223 | |||
224 | #[test] | ||
225 | fn all_match_arms_provided() { | ||
226 | check_assist_not_applicable( | ||
227 | fill_match_arms, | ||
228 | r#" | ||
229 | enum A { | ||
230 | As, | ||
231 | Bs{x:i32, y:Option<i32>}, | ||
232 | Cs(i32, Option<i32>), | ||
233 | } | ||
234 | fn main() { | ||
235 | match A::As<|> { | ||
236 | A::As, | ||
237 | A::Bs{x,y:Some(_)} => {} | ||
238 | A::Cs(_, Some(_)) => {} | ||
239 | } | ||
240 | } | ||
241 | "#, | ||
242 | ); | ||
243 | } | ||
244 | |||
245 | #[test] | ||
246 | fn tuple_of_non_enum() { | ||
247 | // for now this case is not handled, although it potentially could be | ||
248 | // in the future | ||
249 | check_assist_not_applicable( | ||
250 | fill_match_arms, | ||
251 | r#" | ||
252 | fn main() { | ||
253 | match (0, false)<|> { | ||
254 | } | ||
255 | } | ||
256 | "#, | ||
257 | ); | ||
258 | } | ||
259 | |||
260 | #[test] | ||
261 | fn partial_fill_record_tuple() { | ||
262 | check_assist( | ||
263 | fill_match_arms, | ||
264 | r#" | ||
265 | enum A { | ||
266 | As, | ||
267 | Bs { x: i32, y: Option<i32> }, | ||
268 | Cs(i32, Option<i32>), | ||
269 | } | ||
270 | fn main() { | ||
271 | match A::As<|> { | ||
272 | A::Bs { x, y: Some(_) } => {} | ||
273 | A::Cs(_, Some(_)) => {} | ||
274 | } | ||
275 | } | ||
276 | "#, | ||
277 | r#" | ||
278 | enum A { | ||
279 | As, | ||
280 | Bs { x: i32, y: Option<i32> }, | ||
281 | Cs(i32, Option<i32>), | ||
282 | } | ||
283 | fn main() { | ||
284 | match A::As { | ||
285 | A::Bs { x, y: Some(_) } => {} | ||
286 | A::Cs(_, Some(_)) => {} | ||
287 | $0A::As => {} | ||
288 | } | ||
289 | } | ||
290 | "#, | ||
291 | ); | ||
292 | } | ||
293 | |||
294 | #[test] | ||
295 | fn partial_fill_or_pat() { | ||
296 | check_assist( | ||
297 | fill_match_arms, | ||
298 | r#" | ||
299 | enum A { As, Bs, Cs(Option<i32>) } | ||
300 | fn main() { | ||
301 | match A::As<|> { | ||
302 | A::Cs(_) | A::Bs => {} | ||
303 | } | ||
304 | } | ||
305 | "#, | ||
306 | r#" | ||
307 | enum A { As, Bs, Cs(Option<i32>) } | ||
308 | fn main() { | ||
309 | match A::As { | ||
310 | A::Cs(_) | A::Bs => {} | ||
311 | $0A::As => {} | ||
312 | } | ||
313 | } | ||
314 | "#, | ||
315 | ); | ||
316 | } | ||
317 | |||
318 | #[test] | ||
319 | fn partial_fill() { | ||
320 | check_assist( | ||
321 | fill_match_arms, | ||
322 | r#" | ||
323 | enum A { As, Bs, Cs, Ds(String), Es(B) } | ||
324 | enum B { Xs, Ys } | ||
325 | fn main() { | ||
326 | match A::As<|> { | ||
327 | A::Bs if 0 < 1 => {} | ||
328 | A::Ds(_value) => { let x = 1; } | ||
329 | A::Es(B::Xs) => (), | ||
330 | } | ||
331 | } | ||
332 | "#, | ||
333 | r#" | ||
334 | enum A { As, Bs, Cs, Ds(String), Es(B) } | ||
335 | enum B { Xs, Ys } | ||
336 | fn main() { | ||
337 | match A::As { | ||
338 | A::Bs if 0 < 1 => {} | ||
339 | A::Ds(_value) => { let x = 1; } | ||
340 | A::Es(B::Xs) => (), | ||
341 | $0A::As => {} | ||
342 | A::Cs => {} | ||
343 | } | ||
344 | } | ||
345 | "#, | ||
346 | ); | ||
347 | } | ||
348 | |||
349 | #[test] | ||
350 | fn partial_fill_bind_pat() { | ||
351 | check_assist( | ||
352 | fill_match_arms, | ||
353 | r#" | ||
354 | enum A { As, Bs, Cs(Option<i32>) } | ||
355 | fn main() { | ||
356 | match A::As<|> { | ||
357 | A::As(_) => {} | ||
358 | a @ A::Bs(_) => {} | ||
359 | } | ||
360 | } | ||
361 | "#, | ||
362 | r#" | ||
363 | enum A { As, Bs, Cs(Option<i32>) } | ||
364 | fn main() { | ||
365 | match A::As { | ||
366 | A::As(_) => {} | ||
367 | a @ A::Bs(_) => {} | ||
368 | A::Cs(${0:_}) => {} | ||
369 | } | ||
370 | } | ||
371 | "#, | ||
372 | ); | ||
373 | } | ||
374 | |||
375 | #[test] | ||
376 | fn fill_match_arms_empty_body() { | ||
377 | check_assist( | ||
378 | fill_match_arms, | ||
379 | r#" | ||
380 | enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } } | ||
381 | |||
382 | fn main() { | ||
383 | let a = A::As; | ||
384 | match a<|> {} | ||
385 | } | ||
386 | "#, | ||
387 | r#" | ||
388 | enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } } | ||
389 | |||
390 | fn main() { | ||
391 | let a = A::As; | ||
392 | match a { | ||
393 | $0A::As => {} | ||
394 | A::Bs => {} | ||
395 | A::Cs(_) => {} | ||
396 | A::Ds(_, _) => {} | ||
397 | A::Es { x, y } => {} | ||
398 | } | ||
399 | } | ||
400 | "#, | ||
401 | ); | ||
402 | } | ||
403 | |||
404 | #[test] | ||
405 | fn fill_match_arms_tuple_of_enum() { | ||
406 | check_assist( | ||
407 | fill_match_arms, | ||
408 | r#" | ||
409 | enum A { One, Two } | ||
410 | enum B { One, Two } | ||
411 | |||
412 | fn main() { | ||
413 | let a = A::One; | ||
414 | let b = B::One; | ||
415 | match (a<|>, b) {} | ||
416 | } | ||
417 | "#, | ||
418 | r#" | ||
419 | enum A { One, Two } | ||
420 | enum B { One, Two } | ||
421 | |||
422 | fn main() { | ||
423 | let a = A::One; | ||
424 | let b = B::One; | ||
425 | match (a, b) { | ||
426 | $0(A::One, B::One) => {} | ||
427 | (A::One, B::Two) => {} | ||
428 | (A::Two, B::One) => {} | ||
429 | (A::Two, B::Two) => {} | ||
430 | } | ||
431 | } | ||
432 | "#, | ||
433 | ); | ||
434 | } | ||
435 | |||
436 | #[test] | ||
437 | fn fill_match_arms_tuple_of_enum_ref() { | ||
438 | check_assist( | ||
439 | fill_match_arms, | ||
440 | r#" | ||
441 | enum A { One, Two } | ||
442 | enum B { One, Two } | ||
443 | |||
444 | fn main() { | ||
445 | let a = A::One; | ||
446 | let b = B::One; | ||
447 | match (&a<|>, &b) {} | ||
448 | } | ||
449 | "#, | ||
450 | r#" | ||
451 | enum A { One, Two } | ||
452 | enum B { One, Two } | ||
453 | |||
454 | fn main() { | ||
455 | let a = A::One; | ||
456 | let b = B::One; | ||
457 | match (&a, &b) { | ||
458 | $0(A::One, B::One) => {} | ||
459 | (A::One, B::Two) => {} | ||
460 | (A::Two, B::One) => {} | ||
461 | (A::Two, B::Two) => {} | ||
462 | } | ||
463 | } | ||
464 | "#, | ||
465 | ); | ||
466 | } | ||
467 | |||
468 | #[test] | ||
469 | fn fill_match_arms_tuple_of_enum_partial() { | ||
470 | check_assist_not_applicable( | ||
471 | fill_match_arms, | ||
472 | r#" | ||
473 | enum A { One, Two } | ||
474 | enum B { One, Two } | ||
475 | |||
476 | fn main() { | ||
477 | let a = A::One; | ||
478 | let b = B::One; | ||
479 | match (a<|>, b) { | ||
480 | (A::Two, B::One) => {} | ||
481 | } | ||
482 | } | ||
483 | "#, | ||
484 | ); | ||
485 | } | ||
486 | |||
487 | #[test] | ||
488 | fn fill_match_arms_tuple_of_enum_not_applicable() { | ||
489 | check_assist_not_applicable( | ||
490 | fill_match_arms, | ||
491 | r#" | ||
492 | enum A { One, Two } | ||
493 | enum B { One, Two } | ||
494 | |||
495 | fn main() { | ||
496 | let a = A::One; | ||
497 | let b = B::One; | ||
498 | match (a<|>, b) { | ||
499 | (A::Two, B::One) => {} | ||
500 | (A::One, B::One) => {} | ||
501 | (A::One, B::Two) => {} | ||
502 | (A::Two, B::Two) => {} | ||
503 | } | ||
504 | } | ||
505 | "#, | ||
506 | ); | ||
507 | } | ||
508 | |||
509 | #[test] | ||
510 | fn fill_match_arms_single_element_tuple_of_enum() { | ||
511 | // For now we don't hande the case of a single element tuple, but | ||
512 | // we could handle this in the future if `make::tuple_pat` allowed | ||
513 | // creating a tuple with a single pattern. | ||
514 | check_assist_not_applicable( | ||
515 | fill_match_arms, | ||
516 | r#" | ||
517 | enum A { One, Two } | ||
518 | |||
519 | fn main() { | ||
520 | let a = A::One; | ||
521 | match (a<|>, ) { | ||
522 | } | ||
523 | } | ||
524 | "#, | ||
525 | ); | ||
526 | } | ||
527 | |||
528 | #[test] | ||
529 | fn test_fill_match_arm_refs() { | ||
530 | check_assist( | ||
531 | fill_match_arms, | ||
532 | r#" | ||
533 | enum A { As } | ||
534 | |||
535 | fn foo(a: &A) { | ||
536 | match a<|> { | ||
537 | } | ||
538 | } | ||
539 | "#, | ||
540 | r#" | ||
541 | enum A { As } | ||
542 | |||
543 | fn foo(a: &A) { | ||
544 | match a { | ||
545 | $0A::As => {} | ||
546 | } | ||
547 | } | ||
548 | "#, | ||
549 | ); | ||
550 | |||
551 | check_assist( | ||
552 | fill_match_arms, | ||
553 | r#" | ||
554 | enum A { | ||
555 | Es { x: usize, y: usize } | ||
556 | } | ||
557 | |||
558 | fn foo(a: &mut A) { | ||
559 | match a<|> { | ||
560 | } | ||
561 | } | ||
562 | "#, | ||
563 | r#" | ||
564 | enum A { | ||
565 | Es { x: usize, y: usize } | ||
566 | } | ||
567 | |||
568 | fn foo(a: &mut A) { | ||
569 | match a { | ||
570 | $0A::Es { x, y } => {} | ||
571 | } | ||
572 | } | ||
573 | "#, | ||
574 | ); | ||
575 | } | ||
576 | |||
577 | #[test] | ||
578 | fn fill_match_arms_target() { | ||
579 | check_assist_target( | ||
580 | fill_match_arms, | ||
581 | r#" | ||
582 | enum E { X, Y } | ||
583 | |||
584 | fn main() { | ||
585 | match E::X<|> {} | ||
586 | } | ||
587 | "#, | ||
588 | "match E::X {}", | ||
589 | ); | ||
590 | } | ||
591 | |||
592 | #[test] | ||
593 | fn fill_match_arms_trivial_arm() { | ||
594 | check_assist( | ||
595 | fill_match_arms, | ||
596 | r#" | ||
597 | enum E { X, Y } | ||
598 | |||
599 | fn main() { | ||
600 | match E::X { | ||
601 | <|>_ => {} | ||
602 | } | ||
603 | } | ||
604 | "#, | ||
605 | r#" | ||
606 | enum E { X, Y } | ||
607 | |||
608 | fn main() { | ||
609 | match E::X { | ||
610 | $0E::X => {} | ||
611 | E::Y => {} | ||
612 | } | ||
613 | } | ||
614 | "#, | ||
615 | ); | ||
616 | } | ||
617 | |||
618 | #[test] | ||
619 | fn fill_match_arms_qualifies_path() { | ||
620 | check_assist( | ||
621 | fill_match_arms, | ||
622 | r#" | ||
623 | mod foo { pub enum E { X, Y } } | ||
624 | use foo::E::X; | ||
625 | |||
626 | fn main() { | ||
627 | match X { | ||
628 | <|> | ||
629 | } | ||
630 | } | ||
631 | "#, | ||
632 | r#" | ||
633 | mod foo { pub enum E { X, Y } } | ||
634 | use foo::E::X; | ||
635 | |||
636 | fn main() { | ||
637 | match X { | ||
638 | $0X => {} | ||
639 | foo::E::Y => {} | ||
640 | } | ||
641 | } | ||
642 | "#, | ||
643 | ); | ||
644 | } | ||
645 | |||
646 | #[test] | ||
647 | fn fill_match_arms_preserves_comments() { | ||
648 | check_assist( | ||
649 | fill_match_arms, | ||
650 | r#" | ||
651 | enum A { One, Two } | ||
652 | fn foo(a: A) { | ||
653 | match a { | ||
654 | // foo bar baz<|> | ||
655 | A::One => {} | ||
656 | // This is where the rest should be | ||
657 | } | ||
658 | } | ||
659 | "#, | ||
660 | r#" | ||
661 | enum A { One, Two } | ||
662 | fn foo(a: A) { | ||
663 | match a { | ||
664 | // foo bar baz | ||
665 | A::One => {} | ||
666 | // This is where the rest should be | ||
667 | $0A::Two => {} | ||
668 | } | ||
669 | } | ||
670 | "#, | ||
671 | ); | ||
672 | } | ||
673 | |||
674 | #[test] | ||
675 | fn fill_match_arms_preserves_comments_empty() { | ||
676 | check_assist( | ||
677 | fill_match_arms, | ||
678 | r#" | ||
679 | enum A { One, Two } | ||
680 | fn foo(a: A) { | ||
681 | match a { | ||
682 | // foo bar baz<|> | ||
683 | } | ||
684 | } | ||
685 | "#, | ||
686 | r#" | ||
687 | enum A { One, Two } | ||
688 | fn foo(a: A) { | ||
689 | match a { | ||
690 | // foo bar baz | ||
691 | $0A::One => {} | ||
692 | A::Two => {} | ||
693 | } | ||
694 | } | ||
695 | "#, | ||
696 | ); | ||
697 | } | ||
698 | |||
699 | #[test] | ||
700 | fn fill_match_arms_placeholder() { | ||
701 | check_assist( | ||
702 | fill_match_arms, | ||
703 | r#" | ||
704 | enum A { One, Two, } | ||
705 | fn foo(a: A) { | ||
706 | match a<|> { | ||
707 | _ => (), | ||
708 | } | ||
709 | } | ||
710 | "#, | ||
711 | r#" | ||
712 | enum A { One, Two, } | ||
713 | fn foo(a: A) { | ||
714 | match a { | ||
715 | $0A::One => {} | ||
716 | A::Two => {} | ||
717 | } | ||
718 | } | ||
719 | "#, | ||
720 | ); | ||
721 | } | ||
722 | |||
723 | #[test] | ||
724 | fn option_order() { | ||
725 | mark::check!(option_order); | ||
726 | let before = r#" | ||
727 | fn foo(opt: Option<i32>) { | ||
728 | match opt<|> { | ||
729 | } | ||
730 | } | ||
731 | "#; | ||
732 | let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE); | ||
733 | |||
734 | check_assist( | ||
735 | fill_match_arms, | ||
736 | before, | ||
737 | r#" | ||
738 | fn foo(opt: Option<i32>) { | ||
739 | match opt { | ||
740 | Some(${0:_}) => {} | ||
741 | None => {} | ||
742 | } | ||
743 | } | ||
744 | "#, | ||
745 | ); | ||
746 | } | ||
747 | } | ||
diff --git a/crates/ra_assists/src/handlers/fix_visibility.rs b/crates/ra_assists/src/handlers/fix_visibility.rs deleted file mode 100644 index 1aefa79cc..000000000 --- a/crates/ra_assists/src/handlers/fix_visibility.rs +++ /dev/null | |||
@@ -1,607 +0,0 @@ | |||
1 | use hir::{db::HirDatabase, HasSource, HasVisibility, PathResolution}; | ||
2 | use ra_db::FileId; | ||
3 | use ra_syntax::{ast, AstNode, TextRange, TextSize}; | ||
4 | |||
5 | use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists}; | ||
6 | use ast::VisibilityOwner; | ||
7 | |||
8 | // FIXME: this really should be a fix for diagnostic, rather than an assist. | ||
9 | |||
10 | // Assist: fix_visibility | ||
11 | // | ||
12 | // Makes inaccessible item public. | ||
13 | // | ||
14 | // ``` | ||
15 | // mod m { | ||
16 | // fn frobnicate() {} | ||
17 | // } | ||
18 | // fn main() { | ||
19 | // m::frobnicate<|>() {} | ||
20 | // } | ||
21 | // ``` | ||
22 | // -> | ||
23 | // ``` | ||
24 | // mod m { | ||
25 | // $0pub(crate) fn frobnicate() {} | ||
26 | // } | ||
27 | // fn main() { | ||
28 | // m::frobnicate() {} | ||
29 | // } | ||
30 | // ``` | ||
31 | pub(crate) fn fix_visibility(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
32 | add_vis_to_referenced_module_def(acc, ctx) | ||
33 | .or_else(|| add_vis_to_referenced_record_field(acc, ctx)) | ||
34 | } | ||
35 | |||
36 | fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
37 | let path: ast::Path = ctx.find_node_at_offset()?; | ||
38 | let path_res = ctx.sema.resolve_path(&path)?; | ||
39 | let def = match path_res { | ||
40 | PathResolution::Def(def) => def, | ||
41 | _ => return None, | ||
42 | }; | ||
43 | |||
44 | let current_module = ctx.sema.scope(&path.syntax()).module()?; | ||
45 | let target_module = def.module(ctx.db())?; | ||
46 | |||
47 | let vis = target_module.visibility_of(ctx.db(), &def)?; | ||
48 | if vis.is_visible_from(ctx.db(), current_module.into()) { | ||
49 | return None; | ||
50 | }; | ||
51 | |||
52 | let (offset, current_visibility, target, target_file, target_name) = | ||
53 | target_data_for_def(ctx.db(), def)?; | ||
54 | |||
55 | let missing_visibility = | ||
56 | if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" }; | ||
57 | |||
58 | let assist_label = match target_name { | ||
59 | None => format!("Change visibility to {}", missing_visibility), | ||
60 | Some(name) => format!("Change visibility of {} to {}", name, missing_visibility), | ||
61 | }; | ||
62 | |||
63 | acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| { | ||
64 | builder.edit_file(target_file); | ||
65 | match ctx.config.snippet_cap { | ||
66 | Some(cap) => match current_visibility { | ||
67 | Some(current_visibility) => builder.replace_snippet( | ||
68 | cap, | ||
69 | current_visibility.syntax().text_range(), | ||
70 | format!("$0{}", missing_visibility), | ||
71 | ), | ||
72 | None => builder.insert_snippet(cap, offset, format!("$0{} ", missing_visibility)), | ||
73 | }, | ||
74 | None => match current_visibility { | ||
75 | Some(current_visibility) => { | ||
76 | builder.replace(current_visibility.syntax().text_range(), missing_visibility) | ||
77 | } | ||
78 | None => builder.insert(offset, format!("{} ", missing_visibility)), | ||
79 | }, | ||
80 | } | ||
81 | }) | ||
82 | } | ||
83 | |||
84 | fn add_vis_to_referenced_record_field(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
85 | let record_field: ast::RecordExprField = ctx.find_node_at_offset()?; | ||
86 | let (record_field_def, _) = ctx.sema.resolve_record_field(&record_field)?; | ||
87 | |||
88 | let current_module = ctx.sema.scope(record_field.syntax()).module()?; | ||
89 | let visibility = record_field_def.visibility(ctx.db()); | ||
90 | if visibility.is_visible_from(ctx.db(), current_module.into()) { | ||
91 | return None; | ||
92 | } | ||
93 | |||
94 | let parent = record_field_def.parent_def(ctx.db()); | ||
95 | let parent_name = parent.name(ctx.db()); | ||
96 | let target_module = parent.module(ctx.db()); | ||
97 | |||
98 | let in_file_source = record_field_def.source(ctx.db()); | ||
99 | let (offset, current_visibility, target) = match in_file_source.value { | ||
100 | hir::FieldSource::Named(it) => { | ||
101 | let s = it.syntax(); | ||
102 | (vis_offset(s), it.visibility(), s.text_range()) | ||
103 | } | ||
104 | hir::FieldSource::Pos(it) => { | ||
105 | let s = it.syntax(); | ||
106 | (vis_offset(s), it.visibility(), s.text_range()) | ||
107 | } | ||
108 | }; | ||
109 | |||
110 | let missing_visibility = | ||
111 | if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" }; | ||
112 | let target_file = in_file_source.file_id.original_file(ctx.db()); | ||
113 | |||
114 | let target_name = record_field_def.name(ctx.db()); | ||
115 | let assist_label = | ||
116 | format!("Change visibility of {}.{} to {}", parent_name, target_name, missing_visibility); | ||
117 | |||
118 | acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| { | ||
119 | builder.edit_file(target_file); | ||
120 | match ctx.config.snippet_cap { | ||
121 | Some(cap) => match current_visibility { | ||
122 | Some(current_visibility) => builder.replace_snippet( | ||
123 | cap, | ||
124 | dbg!(current_visibility.syntax()).text_range(), | ||
125 | format!("$0{}", missing_visibility), | ||
126 | ), | ||
127 | None => builder.insert_snippet(cap, offset, format!("$0{} ", missing_visibility)), | ||
128 | }, | ||
129 | None => match current_visibility { | ||
130 | Some(current_visibility) => { | ||
131 | builder.replace(current_visibility.syntax().text_range(), missing_visibility) | ||
132 | } | ||
133 | None => builder.insert(offset, format!("{} ", missing_visibility)), | ||
134 | }, | ||
135 | } | ||
136 | }) | ||
137 | } | ||
138 | |||
139 | fn target_data_for_def( | ||
140 | db: &dyn HirDatabase, | ||
141 | def: hir::ModuleDef, | ||
142 | ) -> Option<(TextSize, Option<ast::Visibility>, TextRange, FileId, Option<hir::Name>)> { | ||
143 | fn offset_target_and_file_id<S, Ast>( | ||
144 | db: &dyn HirDatabase, | ||
145 | x: S, | ||
146 | ) -> (TextSize, Option<ast::Visibility>, TextRange, FileId) | ||
147 | where | ||
148 | S: HasSource<Ast = Ast>, | ||
149 | Ast: AstNode + ast::VisibilityOwner, | ||
150 | { | ||
151 | let source = x.source(db); | ||
152 | let in_file_syntax = source.syntax(); | ||
153 | let file_id = in_file_syntax.file_id; | ||
154 | let syntax = in_file_syntax.value; | ||
155 | let current_visibility = source.value.visibility(); | ||
156 | ( | ||
157 | vis_offset(syntax), | ||
158 | current_visibility, | ||
159 | syntax.text_range(), | ||
160 | file_id.original_file(db.upcast()), | ||
161 | ) | ||
162 | } | ||
163 | |||
164 | let target_name; | ||
165 | let (offset, current_visibility, target, target_file) = match def { | ||
166 | hir::ModuleDef::Function(f) => { | ||
167 | target_name = Some(f.name(db)); | ||
168 | offset_target_and_file_id(db, f) | ||
169 | } | ||
170 | hir::ModuleDef::Adt(adt) => { | ||
171 | target_name = Some(adt.name(db)); | ||
172 | match adt { | ||
173 | hir::Adt::Struct(s) => offset_target_and_file_id(db, s), | ||
174 | hir::Adt::Union(u) => offset_target_and_file_id(db, u), | ||
175 | hir::Adt::Enum(e) => offset_target_and_file_id(db, e), | ||
176 | } | ||
177 | } | ||
178 | hir::ModuleDef::Const(c) => { | ||
179 | target_name = c.name(db); | ||
180 | offset_target_and_file_id(db, c) | ||
181 | } | ||
182 | hir::ModuleDef::Static(s) => { | ||
183 | target_name = s.name(db); | ||
184 | offset_target_and_file_id(db, s) | ||
185 | } | ||
186 | hir::ModuleDef::Trait(t) => { | ||
187 | target_name = Some(t.name(db)); | ||
188 | offset_target_and_file_id(db, t) | ||
189 | } | ||
190 | hir::ModuleDef::TypeAlias(t) => { | ||
191 | target_name = Some(t.name(db)); | ||
192 | offset_target_and_file_id(db, t) | ||
193 | } | ||
194 | hir::ModuleDef::Module(m) => { | ||
195 | target_name = m.name(db); | ||
196 | let in_file_source = m.declaration_source(db)?; | ||
197 | let file_id = in_file_source.file_id.original_file(db.upcast()); | ||
198 | let syntax = in_file_source.value.syntax(); | ||
199 | (vis_offset(syntax), in_file_source.value.visibility(), syntax.text_range(), file_id) | ||
200 | } | ||
201 | // Enum variants can't be private, we can't modify builtin types | ||
202 | hir::ModuleDef::EnumVariant(_) | hir::ModuleDef::BuiltinType(_) => return None, | ||
203 | }; | ||
204 | |||
205 | Some((offset, current_visibility, target, target_file, target_name)) | ||
206 | } | ||
207 | |||
208 | #[cfg(test)] | ||
209 | mod tests { | ||
210 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
211 | |||
212 | use super::*; | ||
213 | |||
214 | #[test] | ||
215 | fn fix_visibility_of_fn() { | ||
216 | check_assist( | ||
217 | fix_visibility, | ||
218 | r"mod foo { fn foo() {} } | ||
219 | fn main() { foo::foo<|>() } ", | ||
220 | r"mod foo { $0pub(crate) fn foo() {} } | ||
221 | fn main() { foo::foo() } ", | ||
222 | ); | ||
223 | check_assist_not_applicable( | ||
224 | fix_visibility, | ||
225 | r"mod foo { pub fn foo() {} } | ||
226 | fn main() { foo::foo<|>() } ", | ||
227 | ) | ||
228 | } | ||
229 | |||
230 | #[test] | ||
231 | fn fix_visibility_of_adt_in_submodule() { | ||
232 | check_assist( | ||
233 | fix_visibility, | ||
234 | r"mod foo { struct Foo; } | ||
235 | fn main() { foo::Foo<|> } ", | ||
236 | r"mod foo { $0pub(crate) struct Foo; } | ||
237 | fn main() { foo::Foo } ", | ||
238 | ); | ||
239 | check_assist_not_applicable( | ||
240 | fix_visibility, | ||
241 | r"mod foo { pub struct Foo; } | ||
242 | fn main() { foo::Foo<|> } ", | ||
243 | ); | ||
244 | check_assist( | ||
245 | fix_visibility, | ||
246 | r"mod foo { enum Foo; } | ||
247 | fn main() { foo::Foo<|> } ", | ||
248 | r"mod foo { $0pub(crate) enum Foo; } | ||
249 | fn main() { foo::Foo } ", | ||
250 | ); | ||
251 | check_assist_not_applicable( | ||
252 | fix_visibility, | ||
253 | r"mod foo { pub enum Foo; } | ||
254 | fn main() { foo::Foo<|> } ", | ||
255 | ); | ||
256 | check_assist( | ||
257 | fix_visibility, | ||
258 | r"mod foo { union Foo; } | ||
259 | fn main() { foo::Foo<|> } ", | ||
260 | r"mod foo { $0pub(crate) union Foo; } | ||
261 | fn main() { foo::Foo } ", | ||
262 | ); | ||
263 | check_assist_not_applicable( | ||
264 | fix_visibility, | ||
265 | r"mod foo { pub union Foo; } | ||
266 | fn main() { foo::Foo<|> } ", | ||
267 | ); | ||
268 | } | ||
269 | |||
270 | #[test] | ||
271 | fn fix_visibility_of_adt_in_other_file() { | ||
272 | check_assist( | ||
273 | fix_visibility, | ||
274 | r" | ||
275 | //- /main.rs | ||
276 | mod foo; | ||
277 | fn main() { foo::Foo<|> } | ||
278 | |||
279 | //- /foo.rs | ||
280 | struct Foo; | ||
281 | ", | ||
282 | r"$0pub(crate) struct Foo; | ||
283 | ", | ||
284 | ); | ||
285 | } | ||
286 | |||
287 | #[test] | ||
288 | fn fix_visibility_of_struct_field() { | ||
289 | check_assist( | ||
290 | fix_visibility, | ||
291 | r"mod foo { pub struct Foo { bar: (), } } | ||
292 | fn main() { foo::Foo { <|>bar: () }; } ", | ||
293 | r"mod foo { pub struct Foo { $0pub(crate) bar: (), } } | ||
294 | fn main() { foo::Foo { bar: () }; } ", | ||
295 | ); | ||
296 | check_assist( | ||
297 | fix_visibility, | ||
298 | r" | ||
299 | //- /lib.rs | ||
300 | mod foo; | ||
301 | fn main() { foo::Foo { <|>bar: () }; } | ||
302 | //- /foo.rs | ||
303 | pub struct Foo { bar: () } | ||
304 | ", | ||
305 | r"pub struct Foo { $0pub(crate) bar: () } | ||
306 | ", | ||
307 | ); | ||
308 | check_assist_not_applicable( | ||
309 | fix_visibility, | ||
310 | r"mod foo { pub struct Foo { pub bar: (), } } | ||
311 | fn main() { foo::Foo { <|>bar: () }; } ", | ||
312 | ); | ||
313 | check_assist_not_applicable( | ||
314 | fix_visibility, | ||
315 | r" | ||
316 | //- /lib.rs | ||
317 | mod foo; | ||
318 | fn main() { foo::Foo { <|>bar: () }; } | ||
319 | //- /foo.rs | ||
320 | pub struct Foo { pub bar: () } | ||
321 | ", | ||
322 | ); | ||
323 | } | ||
324 | |||
325 | #[test] | ||
326 | fn fix_visibility_of_enum_variant_field() { | ||
327 | check_assist( | ||
328 | fix_visibility, | ||
329 | r"mod foo { pub enum Foo { Bar { bar: () } } } | ||
330 | fn main() { foo::Foo::Bar { <|>bar: () }; } ", | ||
331 | r"mod foo { pub enum Foo { Bar { $0pub(crate) bar: () } } } | ||
332 | fn main() { foo::Foo::Bar { bar: () }; } ", | ||
333 | ); | ||
334 | check_assist( | ||
335 | fix_visibility, | ||
336 | r" | ||
337 | //- /lib.rs | ||
338 | mod foo; | ||
339 | fn main() { foo::Foo::Bar { <|>bar: () }; } | ||
340 | //- /foo.rs | ||
341 | pub enum Foo { Bar { bar: () } } | ||
342 | ", | ||
343 | r"pub enum Foo { Bar { $0pub(crate) bar: () } } | ||
344 | ", | ||
345 | ); | ||
346 | check_assist_not_applicable( | ||
347 | fix_visibility, | ||
348 | r"mod foo { pub struct Foo { pub bar: (), } } | ||
349 | fn main() { foo::Foo { <|>bar: () }; } ", | ||
350 | ); | ||
351 | check_assist_not_applicable( | ||
352 | fix_visibility, | ||
353 | r" | ||
354 | //- /lib.rs | ||
355 | mod foo; | ||
356 | fn main() { foo::Foo { <|>bar: () }; } | ||
357 | //- /foo.rs | ||
358 | pub struct Foo { pub bar: () } | ||
359 | ", | ||
360 | ); | ||
361 | } | ||
362 | |||
363 | #[test] | ||
364 | #[ignore] | ||
365 | // FIXME reenable this test when `Semantics::resolve_record_field` works with union fields | ||
366 | fn fix_visibility_of_union_field() { | ||
367 | check_assist( | ||
368 | fix_visibility, | ||
369 | r"mod foo { pub union Foo { bar: (), } } | ||
370 | fn main() { foo::Foo { <|>bar: () }; } ", | ||
371 | r"mod foo { pub union Foo { $0pub(crate) bar: (), } } | ||
372 | fn main() { foo::Foo { bar: () }; } ", | ||
373 | ); | ||
374 | check_assist( | ||
375 | fix_visibility, | ||
376 | r" | ||
377 | //- /lib.rs | ||
378 | mod foo; | ||
379 | fn main() { foo::Foo { <|>bar: () }; } | ||
380 | //- /foo.rs | ||
381 | pub union Foo { bar: () } | ||
382 | ", | ||
383 | r"pub union Foo { $0pub(crate) bar: () } | ||
384 | ", | ||
385 | ); | ||
386 | check_assist_not_applicable( | ||
387 | fix_visibility, | ||
388 | r"mod foo { pub union Foo { pub bar: (), } } | ||
389 | fn main() { foo::Foo { <|>bar: () }; } ", | ||
390 | ); | ||
391 | check_assist_not_applicable( | ||
392 | fix_visibility, | ||
393 | r" | ||
394 | //- /lib.rs | ||
395 | mod foo; | ||
396 | fn main() { foo::Foo { <|>bar: () }; } | ||
397 | //- /foo.rs | ||
398 | pub union Foo { pub bar: () } | ||
399 | ", | ||
400 | ); | ||
401 | } | ||
402 | |||
403 | #[test] | ||
404 | fn fix_visibility_of_const() { | ||
405 | check_assist( | ||
406 | fix_visibility, | ||
407 | r"mod foo { const FOO: () = (); } | ||
408 | fn main() { foo::FOO<|> } ", | ||
409 | r"mod foo { $0pub(crate) const FOO: () = (); } | ||
410 | fn main() { foo::FOO } ", | ||
411 | ); | ||
412 | check_assist_not_applicable( | ||
413 | fix_visibility, | ||
414 | r"mod foo { pub const FOO: () = (); } | ||
415 | fn main() { foo::FOO<|> } ", | ||
416 | ); | ||
417 | } | ||
418 | |||
419 | #[test] | ||
420 | fn fix_visibility_of_static() { | ||
421 | check_assist( | ||
422 | fix_visibility, | ||
423 | r"mod foo { static FOO: () = (); } | ||
424 | fn main() { foo::FOO<|> } ", | ||
425 | r"mod foo { $0pub(crate) static FOO: () = (); } | ||
426 | fn main() { foo::FOO } ", | ||
427 | ); | ||
428 | check_assist_not_applicable( | ||
429 | fix_visibility, | ||
430 | r"mod foo { pub static FOO: () = (); } | ||
431 | fn main() { foo::FOO<|> } ", | ||
432 | ); | ||
433 | } | ||
434 | |||
435 | #[test] | ||
436 | fn fix_visibility_of_trait() { | ||
437 | check_assist( | ||
438 | fix_visibility, | ||
439 | r"mod foo { trait Foo { fn foo(&self) {} } } | ||
440 | fn main() { let x: &dyn foo::<|>Foo; } ", | ||
441 | r"mod foo { $0pub(crate) trait Foo { fn foo(&self) {} } } | ||
442 | fn main() { let x: &dyn foo::Foo; } ", | ||
443 | ); | ||
444 | check_assist_not_applicable( | ||
445 | fix_visibility, | ||
446 | r"mod foo { pub trait Foo { fn foo(&self) {} } } | ||
447 | fn main() { let x: &dyn foo::Foo<|>; } ", | ||
448 | ); | ||
449 | } | ||
450 | |||
451 | #[test] | ||
452 | fn fix_visibility_of_type_alias() { | ||
453 | check_assist( | ||
454 | fix_visibility, | ||
455 | r"mod foo { type Foo = (); } | ||
456 | fn main() { let x: foo::Foo<|>; } ", | ||
457 | r"mod foo { $0pub(crate) type Foo = (); } | ||
458 | fn main() { let x: foo::Foo; } ", | ||
459 | ); | ||
460 | check_assist_not_applicable( | ||
461 | fix_visibility, | ||
462 | r"mod foo { pub type Foo = (); } | ||
463 | fn main() { let x: foo::Foo<|>; } ", | ||
464 | ); | ||
465 | } | ||
466 | |||
467 | #[test] | ||
468 | fn fix_visibility_of_module() { | ||
469 | check_assist( | ||
470 | fix_visibility, | ||
471 | r"mod foo { mod bar { fn bar() {} } } | ||
472 | fn main() { foo::bar<|>::bar(); } ", | ||
473 | r"mod foo { $0pub(crate) mod bar { fn bar() {} } } | ||
474 | fn main() { foo::bar::bar(); } ", | ||
475 | ); | ||
476 | |||
477 | check_assist( | ||
478 | fix_visibility, | ||
479 | r" | ||
480 | //- /main.rs | ||
481 | mod foo; | ||
482 | fn main() { foo::bar<|>::baz(); } | ||
483 | |||
484 | //- /foo.rs | ||
485 | mod bar { | ||
486 | pub fn baz() {} | ||
487 | } | ||
488 | ", | ||
489 | r"$0pub(crate) mod bar { | ||
490 | pub fn baz() {} | ||
491 | } | ||
492 | ", | ||
493 | ); | ||
494 | |||
495 | check_assist_not_applicable( | ||
496 | fix_visibility, | ||
497 | r"mod foo { pub mod bar { pub fn bar() {} } } | ||
498 | fn main() { foo::bar<|>::bar(); } ", | ||
499 | ); | ||
500 | } | ||
501 | |||
502 | #[test] | ||
503 | fn fix_visibility_of_inline_module_in_other_file() { | ||
504 | check_assist( | ||
505 | fix_visibility, | ||
506 | r" | ||
507 | //- /main.rs | ||
508 | mod foo; | ||
509 | fn main() { foo::bar<|>::baz(); } | ||
510 | |||
511 | //- /foo.rs | ||
512 | mod bar; | ||
513 | //- /foo/bar.rs | ||
514 | pub fn baz() {} | ||
515 | ", | ||
516 | r"$0pub(crate) mod bar; | ||
517 | ", | ||
518 | ); | ||
519 | } | ||
520 | |||
521 | #[test] | ||
522 | fn fix_visibility_of_module_declaration_in_other_file() { | ||
523 | check_assist( | ||
524 | fix_visibility, | ||
525 | r" | ||
526 | //- /main.rs | ||
527 | mod foo; | ||
528 | fn main() { foo::bar<|>>::baz(); } | ||
529 | |||
530 | //- /foo.rs | ||
531 | mod bar { | ||
532 | pub fn baz() {} | ||
533 | } | ||
534 | ", | ||
535 | r"$0pub(crate) mod bar { | ||
536 | pub fn baz() {} | ||
537 | } | ||
538 | ", | ||
539 | ); | ||
540 | } | ||
541 | |||
542 | #[test] | ||
543 | fn adds_pub_when_target_is_in_another_crate() { | ||
544 | check_assist( | ||
545 | fix_visibility, | ||
546 | r" | ||
547 | //- /main.rs crate:a deps:foo | ||
548 | foo::Bar<|> | ||
549 | //- /lib.rs crate:foo | ||
550 | struct Bar; | ||
551 | ", | ||
552 | r"$0pub struct Bar; | ||
553 | ", | ||
554 | ) | ||
555 | } | ||
556 | |||
557 | #[test] | ||
558 | fn replaces_pub_crate_with_pub() { | ||
559 | check_assist( | ||
560 | fix_visibility, | ||
561 | r" | ||
562 | //- /main.rs crate:a deps:foo | ||
563 | foo::Bar<|> | ||
564 | //- /lib.rs crate:foo | ||
565 | pub(crate) struct Bar; | ||
566 | ", | ||
567 | r"$0pub struct Bar; | ||
568 | ", | ||
569 | ); | ||
570 | check_assist( | ||
571 | fix_visibility, | ||
572 | r" | ||
573 | //- /main.rs crate:a deps:foo | ||
574 | fn main() { | ||
575 | foo::Foo { <|>bar: () }; | ||
576 | } | ||
577 | //- /lib.rs crate:foo | ||
578 | pub struct Foo { pub(crate) bar: () } | ||
579 | ", | ||
580 | r"pub struct Foo { $0pub bar: () } | ||
581 | ", | ||
582 | ); | ||
583 | } | ||
584 | |||
585 | #[test] | ||
586 | #[ignore] | ||
587 | // FIXME handle reexports properly | ||
588 | fn fix_visibility_of_reexport() { | ||
589 | check_assist( | ||
590 | fix_visibility, | ||
591 | r" | ||
592 | mod foo { | ||
593 | use bar::Baz; | ||
594 | mod bar { pub(super) struct Baz; } | ||
595 | } | ||
596 | foo::Baz<|> | ||
597 | ", | ||
598 | r" | ||
599 | mod foo { | ||
600 | $0pub(crate) use bar::Baz; | ||
601 | mod bar { pub(super) struct Baz; } | ||
602 | } | ||
603 | foo::Baz | ||
604 | ", | ||
605 | ) | ||
606 | } | ||
607 | } | ||
diff --git a/crates/ra_assists/src/handlers/flip_binexpr.rs b/crates/ra_assists/src/handlers/flip_binexpr.rs deleted file mode 100644 index 3cd532650..000000000 --- a/crates/ra_assists/src/handlers/flip_binexpr.rs +++ /dev/null | |||
@@ -1,142 +0,0 @@ | |||
1 | use ra_syntax::ast::{AstNode, BinExpr, BinOp}; | ||
2 | |||
3 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
4 | |||
5 | // Assist: flip_binexpr | ||
6 | // | ||
7 | // Flips operands of a binary expression. | ||
8 | // | ||
9 | // ``` | ||
10 | // fn main() { | ||
11 | // let _ = 90 +<|> 2; | ||
12 | // } | ||
13 | // ``` | ||
14 | // -> | ||
15 | // ``` | ||
16 | // fn main() { | ||
17 | // let _ = 2 + 90; | ||
18 | // } | ||
19 | // ``` | ||
20 | pub(crate) fn flip_binexpr(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
21 | let expr = ctx.find_node_at_offset::<BinExpr>()?; | ||
22 | let lhs = expr.lhs()?.syntax().clone(); | ||
23 | let rhs = expr.rhs()?.syntax().clone(); | ||
24 | let op_range = expr.op_token()?.text_range(); | ||
25 | // The assist should be applied only if the cursor is on the operator | ||
26 | let cursor_in_range = op_range.contains_range(ctx.frange.range); | ||
27 | if !cursor_in_range { | ||
28 | return None; | ||
29 | } | ||
30 | let action: FlipAction = expr.op_kind()?.into(); | ||
31 | // The assist should not be applied for certain operators | ||
32 | if let FlipAction::DontFlip = action { | ||
33 | return None; | ||
34 | } | ||
35 | |||
36 | acc.add( | ||
37 | AssistId("flip_binexpr", AssistKind::RefactorRewrite), | ||
38 | "Flip binary expression", | ||
39 | op_range, | ||
40 | |edit| { | ||
41 | if let FlipAction::FlipAndReplaceOp(new_op) = action { | ||
42 | edit.replace(op_range, new_op); | ||
43 | } | ||
44 | edit.replace(lhs.text_range(), rhs.text()); | ||
45 | edit.replace(rhs.text_range(), lhs.text()); | ||
46 | }, | ||
47 | ) | ||
48 | } | ||
49 | |||
50 | enum FlipAction { | ||
51 | // Flip the expression | ||
52 | Flip, | ||
53 | // Flip the expression and replace the operator with this string | ||
54 | FlipAndReplaceOp(&'static str), | ||
55 | // Do not flip the expression | ||
56 | DontFlip, | ||
57 | } | ||
58 | |||
59 | impl From<BinOp> for FlipAction { | ||
60 | fn from(op_kind: BinOp) -> Self { | ||
61 | match op_kind { | ||
62 | kind if kind.is_assignment() => FlipAction::DontFlip, | ||
63 | BinOp::GreaterTest => FlipAction::FlipAndReplaceOp("<"), | ||
64 | BinOp::GreaterEqualTest => FlipAction::FlipAndReplaceOp("<="), | ||
65 | BinOp::LesserTest => FlipAction::FlipAndReplaceOp(">"), | ||
66 | BinOp::LesserEqualTest => FlipAction::FlipAndReplaceOp(">="), | ||
67 | _ => FlipAction::Flip, | ||
68 | } | ||
69 | } | ||
70 | } | ||
71 | |||
72 | #[cfg(test)] | ||
73 | mod tests { | ||
74 | use super::*; | ||
75 | |||
76 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
77 | |||
78 | #[test] | ||
79 | fn flip_binexpr_target_is_the_op() { | ||
80 | check_assist_target(flip_binexpr, "fn f() { let res = 1 ==<|> 2; }", "==") | ||
81 | } | ||
82 | |||
83 | #[test] | ||
84 | fn flip_binexpr_not_applicable_for_assignment() { | ||
85 | check_assist_not_applicable(flip_binexpr, "fn f() { let mut _x = 1; _x +=<|> 2 }") | ||
86 | } | ||
87 | |||
88 | #[test] | ||
89 | fn flip_binexpr_works_for_eq() { | ||
90 | check_assist( | ||
91 | flip_binexpr, | ||
92 | "fn f() { let res = 1 ==<|> 2; }", | ||
93 | "fn f() { let res = 2 == 1; }", | ||
94 | ) | ||
95 | } | ||
96 | |||
97 | #[test] | ||
98 | fn flip_binexpr_works_for_gt() { | ||
99 | check_assist(flip_binexpr, "fn f() { let res = 1 ><|> 2; }", "fn f() { let res = 2 < 1; }") | ||
100 | } | ||
101 | |||
102 | #[test] | ||
103 | fn flip_binexpr_works_for_lteq() { | ||
104 | check_assist( | ||
105 | flip_binexpr, | ||
106 | "fn f() { let res = 1 <=<|> 2; }", | ||
107 | "fn f() { let res = 2 >= 1; }", | ||
108 | ) | ||
109 | } | ||
110 | |||
111 | #[test] | ||
112 | fn flip_binexpr_works_for_complex_expr() { | ||
113 | check_assist( | ||
114 | flip_binexpr, | ||
115 | "fn f() { let res = (1 + 1) ==<|> (2 + 2); }", | ||
116 | "fn f() { let res = (2 + 2) == (1 + 1); }", | ||
117 | ) | ||
118 | } | ||
119 | |||
120 | #[test] | ||
121 | fn flip_binexpr_works_inside_match() { | ||
122 | check_assist( | ||
123 | flip_binexpr, | ||
124 | r#" | ||
125 | fn dyn_eq(&self, other: &dyn Diagnostic) -> bool { | ||
126 | match other.downcast_ref::<Self>() { | ||
127 | None => false, | ||
128 | Some(it) => it ==<|> self, | ||
129 | } | ||
130 | } | ||
131 | "#, | ||
132 | r#" | ||
133 | fn dyn_eq(&self, other: &dyn Diagnostic) -> bool { | ||
134 | match other.downcast_ref::<Self>() { | ||
135 | None => false, | ||
136 | Some(it) => self == it, | ||
137 | } | ||
138 | } | ||
139 | "#, | ||
140 | ) | ||
141 | } | ||
142 | } | ||
diff --git a/crates/ra_assists/src/handlers/flip_comma.rs b/crates/ra_assists/src/handlers/flip_comma.rs deleted file mode 100644 index 55a971dc7..000000000 --- a/crates/ra_assists/src/handlers/flip_comma.rs +++ /dev/null | |||
@@ -1,84 +0,0 @@ | |||
1 | use ra_syntax::{algo::non_trivia_sibling, Direction, T}; | ||
2 | |||
3 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
4 | |||
5 | // Assist: flip_comma | ||
6 | // | ||
7 | // Flips two comma-separated items. | ||
8 | // | ||
9 | // ``` | ||
10 | // fn main() { | ||
11 | // ((1, 2),<|> (3, 4)); | ||
12 | // } | ||
13 | // ``` | ||
14 | // -> | ||
15 | // ``` | ||
16 | // fn main() { | ||
17 | // ((3, 4), (1, 2)); | ||
18 | // } | ||
19 | // ``` | ||
20 | pub(crate) fn flip_comma(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
21 | let comma = ctx.find_token_at_offset(T![,])?; | ||
22 | let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?; | ||
23 | let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?; | ||
24 | |||
25 | // Don't apply a "flip" in case of a last comma | ||
26 | // that typically comes before punctuation | ||
27 | if next.kind().is_punct() { | ||
28 | return None; | ||
29 | } | ||
30 | |||
31 | acc.add( | ||
32 | AssistId("flip_comma", AssistKind::RefactorRewrite), | ||
33 | "Flip comma", | ||
34 | comma.text_range(), | ||
35 | |edit| { | ||
36 | edit.replace(prev.text_range(), next.to_string()); | ||
37 | edit.replace(next.text_range(), prev.to_string()); | ||
38 | }, | ||
39 | ) | ||
40 | } | ||
41 | |||
42 | #[cfg(test)] | ||
43 | mod tests { | ||
44 | use super::*; | ||
45 | |||
46 | use crate::tests::{check_assist, check_assist_target}; | ||
47 | |||
48 | #[test] | ||
49 | fn flip_comma_works_for_function_parameters() { | ||
50 | check_assist( | ||
51 | flip_comma, | ||
52 | "fn foo(x: i32,<|> y: Result<(), ()>) {}", | ||
53 | "fn foo(y: Result<(), ()>, x: i32) {}", | ||
54 | ) | ||
55 | } | ||
56 | |||
57 | #[test] | ||
58 | fn flip_comma_target() { | ||
59 | check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",") | ||
60 | } | ||
61 | |||
62 | #[test] | ||
63 | #[should_panic] | ||
64 | fn flip_comma_before_punct() { | ||
65 | // See https://github.com/rust-analyzer/rust-analyzer/issues/1619 | ||
66 | // "Flip comma" assist shouldn't be applicable to the last comma in enum or struct | ||
67 | // declaration body. | ||
68 | check_assist_target( | ||
69 | flip_comma, | ||
70 | "pub enum Test { \ | ||
71 | A,<|> \ | ||
72 | }", | ||
73 | ",", | ||
74 | ); | ||
75 | |||
76 | check_assist_target( | ||
77 | flip_comma, | ||
78 | "pub struct Test { \ | ||
79 | foo: usize,<|> \ | ||
80 | }", | ||
81 | ",", | ||
82 | ); | ||
83 | } | ||
84 | } | ||
diff --git a/crates/ra_assists/src/handlers/flip_trait_bound.rs b/crates/ra_assists/src/handlers/flip_trait_bound.rs deleted file mode 100644 index 1234f4d29..000000000 --- a/crates/ra_assists/src/handlers/flip_trait_bound.rs +++ /dev/null | |||
@@ -1,121 +0,0 @@ | |||
1 | use ra_syntax::{ | ||
2 | algo::non_trivia_sibling, | ||
3 | ast::{self, AstNode}, | ||
4 | Direction, T, | ||
5 | }; | ||
6 | |||
7 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
8 | |||
9 | // Assist: flip_trait_bound | ||
10 | // | ||
11 | // Flips two trait bounds. | ||
12 | // | ||
13 | // ``` | ||
14 | // fn foo<T: Clone +<|> Copy>() { } | ||
15 | // ``` | ||
16 | // -> | ||
17 | // ``` | ||
18 | // fn foo<T: Copy + Clone>() { } | ||
19 | // ``` | ||
20 | pub(crate) fn flip_trait_bound(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
21 | // We want to replicate the behavior of `flip_binexpr` by only suggesting | ||
22 | // the assist when the cursor is on a `+` | ||
23 | let plus = ctx.find_token_at_offset(T![+])?; | ||
24 | |||
25 | // Make sure we're in a `TypeBoundList` | ||
26 | if ast::TypeBoundList::cast(plus.parent()).is_none() { | ||
27 | return None; | ||
28 | } | ||
29 | |||
30 | let (before, after) = ( | ||
31 | non_trivia_sibling(plus.clone().into(), Direction::Prev)?, | ||
32 | non_trivia_sibling(plus.clone().into(), Direction::Next)?, | ||
33 | ); | ||
34 | |||
35 | let target = plus.text_range(); | ||
36 | acc.add( | ||
37 | AssistId("flip_trait_bound", AssistKind::RefactorRewrite), | ||
38 | "Flip trait bounds", | ||
39 | target, | ||
40 | |edit| { | ||
41 | edit.replace(before.text_range(), after.to_string()); | ||
42 | edit.replace(after.text_range(), before.to_string()); | ||
43 | }, | ||
44 | ) | ||
45 | } | ||
46 | |||
47 | #[cfg(test)] | ||
48 | mod tests { | ||
49 | use super::*; | ||
50 | |||
51 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
52 | |||
53 | #[test] | ||
54 | fn flip_trait_bound_assist_available() { | ||
55 | check_assist_target(flip_trait_bound, "struct S<T> where T: A <|>+ B + C { }", "+") | ||
56 | } | ||
57 | |||
58 | #[test] | ||
59 | fn flip_trait_bound_not_applicable_for_single_trait_bound() { | ||
60 | check_assist_not_applicable(flip_trait_bound, "struct S<T> where T: <|>A { }") | ||
61 | } | ||
62 | |||
63 | #[test] | ||
64 | fn flip_trait_bound_works_for_struct() { | ||
65 | check_assist( | ||
66 | flip_trait_bound, | ||
67 | "struct S<T> where T: A <|>+ B { }", | ||
68 | "struct S<T> where T: B + A { }", | ||
69 | ) | ||
70 | } | ||
71 | |||
72 | #[test] | ||
73 | fn flip_trait_bound_works_for_trait_impl() { | ||
74 | check_assist( | ||
75 | flip_trait_bound, | ||
76 | "impl X for S<T> where T: A +<|> B { }", | ||
77 | "impl X for S<T> where T: B + A { }", | ||
78 | ) | ||
79 | } | ||
80 | |||
81 | #[test] | ||
82 | fn flip_trait_bound_works_for_fn() { | ||
83 | check_assist(flip_trait_bound, "fn f<T: A <|>+ B>(t: T) { }", "fn f<T: B + A>(t: T) { }") | ||
84 | } | ||
85 | |||
86 | #[test] | ||
87 | fn flip_trait_bound_works_for_fn_where_clause() { | ||
88 | check_assist( | ||
89 | flip_trait_bound, | ||
90 | "fn f<T>(t: T) where T: A +<|> B { }", | ||
91 | "fn f<T>(t: T) where T: B + A { }", | ||
92 | ) | ||
93 | } | ||
94 | |||
95 | #[test] | ||
96 | fn flip_trait_bound_works_for_lifetime() { | ||
97 | check_assist( | ||
98 | flip_trait_bound, | ||
99 | "fn f<T>(t: T) where T: A <|>+ 'static { }", | ||
100 | "fn f<T>(t: T) where T: 'static + A { }", | ||
101 | ) | ||
102 | } | ||
103 | |||
104 | #[test] | ||
105 | fn flip_trait_bound_works_for_complex_bounds() { | ||
106 | check_assist( | ||
107 | flip_trait_bound, | ||
108 | "struct S<T> where T: A<T> <|>+ b_mod::B<T> + C<T> { }", | ||
109 | "struct S<T> where T: b_mod::B<T> + A<T> + C<T> { }", | ||
110 | ) | ||
111 | } | ||
112 | |||
113 | #[test] | ||
114 | fn flip_trait_bound_works_for_long_bounds() { | ||
115 | check_assist( | ||
116 | flip_trait_bound, | ||
117 | "struct S<T> where T: A + B + C + D + E + F +<|> G + H + I + J { }", | ||
118 | "struct S<T> where T: A + B + C + D + E + G + F + H + I + J { }", | ||
119 | ) | ||
120 | } | ||
121 | } | ||
diff --git a/crates/ra_assists/src/handlers/generate_derive.rs b/crates/ra_assists/src/handlers/generate_derive.rs deleted file mode 100644 index 90ece9fab..000000000 --- a/crates/ra_assists/src/handlers/generate_derive.rs +++ /dev/null | |||
@@ -1,132 +0,0 @@ | |||
1 | use ra_syntax::{ | ||
2 | ast::{self, AstNode, AttrsOwner}, | ||
3 | SyntaxKind::{COMMENT, WHITESPACE}, | ||
4 | TextSize, | ||
5 | }; | ||
6 | |||
7 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
8 | |||
9 | // Assist: generate_derive | ||
10 | // | ||
11 | // Adds a new `#[derive()]` clause to a struct or enum. | ||
12 | // | ||
13 | // ``` | ||
14 | // struct Point { | ||
15 | // x: u32, | ||
16 | // y: u32,<|> | ||
17 | // } | ||
18 | // ``` | ||
19 | // -> | ||
20 | // ``` | ||
21 | // #[derive($0)] | ||
22 | // struct Point { | ||
23 | // x: u32, | ||
24 | // y: u32, | ||
25 | // } | ||
26 | // ``` | ||
27 | pub(crate) fn generate_derive(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
28 | let cap = ctx.config.snippet_cap?; | ||
29 | let nominal = ctx.find_node_at_offset::<ast::AdtDef>()?; | ||
30 | let node_start = derive_insertion_offset(&nominal)?; | ||
31 | let target = nominal.syntax().text_range(); | ||
32 | acc.add( | ||
33 | AssistId("generate_derive", AssistKind::Generate), | ||
34 | "Add `#[derive]`", | ||
35 | target, | ||
36 | |builder| { | ||
37 | let derive_attr = nominal | ||
38 | .attrs() | ||
39 | .filter_map(|x| x.as_simple_call()) | ||
40 | .filter(|(name, _arg)| name == "derive") | ||
41 | .map(|(_name, arg)| arg) | ||
42 | .next(); | ||
43 | match derive_attr { | ||
44 | None => { | ||
45 | builder.insert_snippet(cap, node_start, "#[derive($0)]\n"); | ||
46 | } | ||
47 | Some(tt) => { | ||
48 | // Just move the cursor. | ||
49 | builder.insert_snippet( | ||
50 | cap, | ||
51 | tt.syntax().text_range().end() - TextSize::of(')'), | ||
52 | "$0", | ||
53 | ) | ||
54 | } | ||
55 | }; | ||
56 | }, | ||
57 | ) | ||
58 | } | ||
59 | |||
60 | // Insert `derive` after doc comments. | ||
61 | fn derive_insertion_offset(nominal: &ast::AdtDef) -> Option<TextSize> { | ||
62 | let non_ws_child = nominal | ||
63 | .syntax() | ||
64 | .children_with_tokens() | ||
65 | .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?; | ||
66 | Some(non_ws_child.text_range().start()) | ||
67 | } | ||
68 | |||
69 | #[cfg(test)] | ||
70 | mod tests { | ||
71 | use crate::tests::{check_assist, check_assist_target}; | ||
72 | |||
73 | use super::*; | ||
74 | |||
75 | #[test] | ||
76 | fn add_derive_new() { | ||
77 | check_assist( | ||
78 | generate_derive, | ||
79 | "struct Foo { a: i32, <|>}", | ||
80 | "#[derive($0)]\nstruct Foo { a: i32, }", | ||
81 | ); | ||
82 | check_assist( | ||
83 | generate_derive, | ||
84 | "struct Foo { <|> a: i32, }", | ||
85 | "#[derive($0)]\nstruct Foo { a: i32, }", | ||
86 | ); | ||
87 | } | ||
88 | |||
89 | #[test] | ||
90 | fn add_derive_existing() { | ||
91 | check_assist( | ||
92 | generate_derive, | ||
93 | "#[derive(Clone)]\nstruct Foo { a: i32<|>, }", | ||
94 | "#[derive(Clone$0)]\nstruct Foo { a: i32, }", | ||
95 | ); | ||
96 | } | ||
97 | |||
98 | #[test] | ||
99 | fn add_derive_new_with_doc_comment() { | ||
100 | check_assist( | ||
101 | generate_derive, | ||
102 | " | ||
103 | /// `Foo` is a pretty important struct. | ||
104 | /// It does stuff. | ||
105 | struct Foo { a: i32<|>, } | ||
106 | ", | ||
107 | " | ||
108 | /// `Foo` is a pretty important struct. | ||
109 | /// It does stuff. | ||
110 | #[derive($0)] | ||
111 | struct Foo { a: i32, } | ||
112 | ", | ||
113 | ); | ||
114 | } | ||
115 | |||
116 | #[test] | ||
117 | fn add_derive_target() { | ||
118 | check_assist_target( | ||
119 | generate_derive, | ||
120 | " | ||
121 | struct SomeThingIrrelevant; | ||
122 | /// `Foo` is a pretty important struct. | ||
123 | /// It does stuff. | ||
124 | struct Foo { a: i32<|>, } | ||
125 | struct EvenMoreIrrelevant; | ||
126 | ", | ||
127 | "/// `Foo` is a pretty important struct. | ||
128 | /// It does stuff. | ||
129 | struct Foo { a: i32, }", | ||
130 | ); | ||
131 | } | ||
132 | } | ||
diff --git a/crates/ra_assists/src/handlers/generate_from_impl_for_enum.rs b/crates/ra_assists/src/handlers/generate_from_impl_for_enum.rs deleted file mode 100644 index 4c1aef8a2..000000000 --- a/crates/ra_assists/src/handlers/generate_from_impl_for_enum.rs +++ /dev/null | |||
@@ -1,200 +0,0 @@ | |||
1 | use ra_ide_db::RootDatabase; | ||
2 | use ra_syntax::ast::{self, AstNode, NameOwner}; | ||
3 | use test_utils::mark; | ||
4 | |||
5 | use crate::{utils::FamousDefs, AssistContext, AssistId, AssistKind, Assists}; | ||
6 | |||
7 | // Assist: generate_from_impl_for_enum | ||
8 | // | ||
9 | // Adds a From impl for an enum variant with one tuple field. | ||
10 | // | ||
11 | // ``` | ||
12 | // enum A { <|>One(u32) } | ||
13 | // ``` | ||
14 | // -> | ||
15 | // ``` | ||
16 | // enum A { One(u32) } | ||
17 | // | ||
18 | // impl From<u32> for A { | ||
19 | // fn from(v: u32) -> Self { | ||
20 | // A::One(v) | ||
21 | // } | ||
22 | // } | ||
23 | // ``` | ||
24 | pub(crate) fn generate_from_impl_for_enum(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
25 | let variant = ctx.find_node_at_offset::<ast::Variant>()?; | ||
26 | let variant_name = variant.name()?; | ||
27 | let enum_name = variant.parent_enum().name()?; | ||
28 | let field_list = match variant.kind() { | ||
29 | ast::StructKind::Tuple(field_list) => field_list, | ||
30 | _ => return None, | ||
31 | }; | ||
32 | if field_list.fields().count() != 1 { | ||
33 | return None; | ||
34 | } | ||
35 | let field_type = field_list.fields().next()?.ty()?; | ||
36 | let path = match field_type { | ||
37 | ast::Type::PathType(it) => it, | ||
38 | _ => return None, | ||
39 | }; | ||
40 | |||
41 | if existing_from_impl(&ctx.sema, &variant).is_some() { | ||
42 | mark::hit!(test_add_from_impl_already_exists); | ||
43 | return None; | ||
44 | } | ||
45 | |||
46 | let target = variant.syntax().text_range(); | ||
47 | acc.add( | ||
48 | AssistId("generate_from_impl_for_enum", AssistKind::Generate), | ||
49 | "Generate `From` impl for this enum variant", | ||
50 | target, | ||
51 | |edit| { | ||
52 | let start_offset = variant.parent_enum().syntax().text_range().end(); | ||
53 | let buf = format!( | ||
54 | r#" | ||
55 | |||
56 | impl From<{0}> for {1} {{ | ||
57 | fn from(v: {0}) -> Self {{ | ||
58 | {1}::{2}(v) | ||
59 | }} | ||
60 | }}"#, | ||
61 | path.syntax(), | ||
62 | enum_name, | ||
63 | variant_name | ||
64 | ); | ||
65 | edit.insert(start_offset, buf); | ||
66 | }, | ||
67 | ) | ||
68 | } | ||
69 | |||
70 | fn existing_from_impl( | ||
71 | sema: &'_ hir::Semantics<'_, RootDatabase>, | ||
72 | variant: &ast::Variant, | ||
73 | ) -> Option<()> { | ||
74 | let variant = sema.to_def(variant)?; | ||
75 | let enum_ = variant.parent_enum(sema.db); | ||
76 | let krate = enum_.module(sema.db).krate(); | ||
77 | |||
78 | let from_trait = FamousDefs(sema, krate).core_convert_From()?; | ||
79 | |||
80 | let enum_type = enum_.ty(sema.db); | ||
81 | |||
82 | let wrapped_type = variant.fields(sema.db).get(0)?.signature_ty(sema.db); | ||
83 | |||
84 | if enum_type.impls_trait(sema.db, from_trait, &[wrapped_type]) { | ||
85 | Some(()) | ||
86 | } else { | ||
87 | None | ||
88 | } | ||
89 | } | ||
90 | |||
91 | #[cfg(test)] | ||
92 | mod tests { | ||
93 | use test_utils::mark; | ||
94 | |||
95 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
96 | |||
97 | use super::*; | ||
98 | |||
99 | #[test] | ||
100 | fn test_generate_from_impl_for_enum() { | ||
101 | check_assist( | ||
102 | generate_from_impl_for_enum, | ||
103 | "enum A { <|>One(u32) }", | ||
104 | r#"enum A { One(u32) } | ||
105 | |||
106 | impl From<u32> for A { | ||
107 | fn from(v: u32) -> Self { | ||
108 | A::One(v) | ||
109 | } | ||
110 | }"#, | ||
111 | ); | ||
112 | } | ||
113 | |||
114 | #[test] | ||
115 | fn test_generate_from_impl_for_enum_complicated_path() { | ||
116 | check_assist( | ||
117 | generate_from_impl_for_enum, | ||
118 | r#"enum A { <|>One(foo::bar::baz::Boo) }"#, | ||
119 | r#"enum A { One(foo::bar::baz::Boo) } | ||
120 | |||
121 | impl From<foo::bar::baz::Boo> for A { | ||
122 | fn from(v: foo::bar::baz::Boo) -> Self { | ||
123 | A::One(v) | ||
124 | } | ||
125 | }"#, | ||
126 | ); | ||
127 | } | ||
128 | |||
129 | fn check_not_applicable(ra_fixture: &str) { | ||
130 | let fixture = | ||
131 | format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE); | ||
132 | check_assist_not_applicable(generate_from_impl_for_enum, &fixture) | ||
133 | } | ||
134 | |||
135 | #[test] | ||
136 | fn test_add_from_impl_no_element() { | ||
137 | check_not_applicable("enum A { <|>One }"); | ||
138 | } | ||
139 | |||
140 | #[test] | ||
141 | fn test_add_from_impl_more_than_one_element_in_tuple() { | ||
142 | check_not_applicable("enum A { <|>One(u32, String) }"); | ||
143 | } | ||
144 | |||
145 | #[test] | ||
146 | fn test_add_from_impl_struct_variant() { | ||
147 | check_not_applicable("enum A { <|>One { x: u32 } }"); | ||
148 | } | ||
149 | |||
150 | #[test] | ||
151 | fn test_add_from_impl_already_exists() { | ||
152 | mark::check!(test_add_from_impl_already_exists); | ||
153 | check_not_applicable( | ||
154 | r#" | ||
155 | enum A { <|>One(u32), } | ||
156 | |||
157 | impl From<u32> for A { | ||
158 | fn from(v: u32) -> Self { | ||
159 | A::One(v) | ||
160 | } | ||
161 | } | ||
162 | "#, | ||
163 | ); | ||
164 | } | ||
165 | |||
166 | #[test] | ||
167 | fn test_add_from_impl_different_variant_impl_exists() { | ||
168 | check_assist( | ||
169 | generate_from_impl_for_enum, | ||
170 | r#"enum A { <|>One(u32), Two(String), } | ||
171 | |||
172 | impl From<String> for A { | ||
173 | fn from(v: String) -> Self { | ||
174 | A::Two(v) | ||
175 | } | ||
176 | } | ||
177 | |||
178 | pub trait From<T> { | ||
179 | fn from(T) -> Self; | ||
180 | }"#, | ||
181 | r#"enum A { One(u32), Two(String), } | ||
182 | |||
183 | impl From<u32> for A { | ||
184 | fn from(v: u32) -> Self { | ||
185 | A::One(v) | ||
186 | } | ||
187 | } | ||
188 | |||
189 | impl From<String> for A { | ||
190 | fn from(v: String) -> Self { | ||
191 | A::Two(v) | ||
192 | } | ||
193 | } | ||
194 | |||
195 | pub trait From<T> { | ||
196 | fn from(T) -> Self; | ||
197 | }"#, | ||
198 | ); | ||
199 | } | ||
200 | } | ||
diff --git a/crates/ra_assists/src/handlers/generate_function.rs b/crates/ra_assists/src/handlers/generate_function.rs deleted file mode 100644 index acc97e648..000000000 --- a/crates/ra_assists/src/handlers/generate_function.rs +++ /dev/null | |||
@@ -1,1058 +0,0 @@ | |||
1 | use hir::HirDisplay; | ||
2 | use ra_db::FileId; | ||
3 | use ra_syntax::{ | ||
4 | ast::{ | ||
5 | self, | ||
6 | edit::{AstNodeEdit, IndentLevel}, | ||
7 | make, ArgListOwner, AstNode, ModuleItemOwner, | ||
8 | }, | ||
9 | SyntaxKind, SyntaxNode, TextSize, | ||
10 | }; | ||
11 | use rustc_hash::{FxHashMap, FxHashSet}; | ||
12 | |||
13 | use crate::{ | ||
14 | assist_config::SnippetCap, | ||
15 | utils::{render_snippet, Cursor}, | ||
16 | AssistContext, AssistId, AssistKind, Assists, | ||
17 | }; | ||
18 | |||
19 | // Assist: generate_function | ||
20 | // | ||
21 | // Adds a stub function with a signature matching the function under the cursor. | ||
22 | // | ||
23 | // ``` | ||
24 | // struct Baz; | ||
25 | // fn baz() -> Baz { Baz } | ||
26 | // fn foo() { | ||
27 | // bar<|>("", baz()); | ||
28 | // } | ||
29 | // | ||
30 | // ``` | ||
31 | // -> | ||
32 | // ``` | ||
33 | // struct Baz; | ||
34 | // fn baz() -> Baz { Baz } | ||
35 | // fn foo() { | ||
36 | // bar("", baz()); | ||
37 | // } | ||
38 | // | ||
39 | // fn bar(arg: &str, baz: Baz) { | ||
40 | // ${0:todo!()} | ||
41 | // } | ||
42 | // | ||
43 | // ``` | ||
44 | pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
45 | let path_expr: ast::PathExpr = ctx.find_node_at_offset()?; | ||
46 | let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?; | ||
47 | let path = path_expr.path()?; | ||
48 | |||
49 | if ctx.sema.resolve_path(&path).is_some() { | ||
50 | // The function call already resolves, no need to add a function | ||
51 | return None; | ||
52 | } | ||
53 | |||
54 | let target_module = match path.qualifier() { | ||
55 | Some(qualifier) => match ctx.sema.resolve_path(&qualifier) { | ||
56 | Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module), | ||
57 | _ => return None, | ||
58 | }, | ||
59 | None => None, | ||
60 | }; | ||
61 | |||
62 | let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?; | ||
63 | |||
64 | let target = call.syntax().text_range(); | ||
65 | acc.add( | ||
66 | AssistId("generate_function", AssistKind::Generate), | ||
67 | format!("Generate `{}` function", function_builder.fn_name), | ||
68 | target, | ||
69 | |builder| { | ||
70 | let function_template = function_builder.render(); | ||
71 | builder.edit_file(function_template.file); | ||
72 | let new_fn = function_template.to_string(ctx.config.snippet_cap); | ||
73 | match ctx.config.snippet_cap { | ||
74 | Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn), | ||
75 | None => builder.insert(function_template.insert_offset, new_fn), | ||
76 | } | ||
77 | }, | ||
78 | ) | ||
79 | } | ||
80 | |||
81 | struct FunctionTemplate { | ||
82 | insert_offset: TextSize, | ||
83 | placeholder_expr: ast::MacroCall, | ||
84 | leading_ws: String, | ||
85 | fn_def: ast::Fn, | ||
86 | trailing_ws: String, | ||
87 | file: FileId, | ||
88 | } | ||
89 | |||
90 | impl FunctionTemplate { | ||
91 | fn to_string(&self, cap: Option<SnippetCap>) -> String { | ||
92 | let f = match cap { | ||
93 | Some(cap) => render_snippet( | ||
94 | cap, | ||
95 | self.fn_def.syntax(), | ||
96 | Cursor::Replace(self.placeholder_expr.syntax()), | ||
97 | ), | ||
98 | None => self.fn_def.to_string(), | ||
99 | }; | ||
100 | format!("{}{}{}", self.leading_ws, f, self.trailing_ws) | ||
101 | } | ||
102 | } | ||
103 | |||
104 | struct FunctionBuilder { | ||
105 | target: GeneratedFunctionTarget, | ||
106 | fn_name: ast::Name, | ||
107 | type_params: Option<ast::GenericParamList>, | ||
108 | params: ast::ParamList, | ||
109 | file: FileId, | ||
110 | needs_pub: bool, | ||
111 | } | ||
112 | |||
113 | impl FunctionBuilder { | ||
114 | /// Prepares a generated function that matches `call`. | ||
115 | /// The function is generated in `target_module` or next to `call` | ||
116 | fn from_call( | ||
117 | ctx: &AssistContext, | ||
118 | call: &ast::CallExpr, | ||
119 | path: &ast::Path, | ||
120 | target_module: Option<hir::Module>, | ||
121 | ) -> Option<Self> { | ||
122 | let mut file = ctx.frange.file_id; | ||
123 | let target = match &target_module { | ||
124 | Some(target_module) => { | ||
125 | let module_source = target_module.definition_source(ctx.db()); | ||
126 | let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?; | ||
127 | file = in_file; | ||
128 | target | ||
129 | } | ||
130 | None => next_space_for_fn_after_call_site(&call)?, | ||
131 | }; | ||
132 | let needs_pub = target_module.is_some(); | ||
133 | let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; | ||
134 | let fn_name = fn_name(&path)?; | ||
135 | let (type_params, params) = fn_args(ctx, target_module, &call)?; | ||
136 | |||
137 | Some(Self { target, fn_name, type_params, params, file, needs_pub }) | ||
138 | } | ||
139 | |||
140 | fn render(self) -> FunctionTemplate { | ||
141 | let placeholder_expr = make::expr_todo(); | ||
142 | let fn_body = make::block_expr(vec![], Some(placeholder_expr)); | ||
143 | let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None }; | ||
144 | let mut fn_def = | ||
145 | make::fn_(visibility, self.fn_name, self.type_params, self.params, fn_body); | ||
146 | let leading_ws; | ||
147 | let trailing_ws; | ||
148 | |||
149 | let insert_offset = match self.target { | ||
150 | GeneratedFunctionTarget::BehindItem(it) => { | ||
151 | let indent = IndentLevel::from_node(&it); | ||
152 | leading_ws = format!("\n\n{}", indent); | ||
153 | fn_def = fn_def.indent(indent); | ||
154 | trailing_ws = String::new(); | ||
155 | it.text_range().end() | ||
156 | } | ||
157 | GeneratedFunctionTarget::InEmptyItemList(it) => { | ||
158 | let indent = IndentLevel::from_node(it.syntax()); | ||
159 | leading_ws = format!("\n{}", indent + 1); | ||
160 | fn_def = fn_def.indent(indent + 1); | ||
161 | trailing_ws = format!("\n{}", indent); | ||
162 | it.syntax().text_range().start() + TextSize::of('{') | ||
163 | } | ||
164 | }; | ||
165 | |||
166 | let placeholder_expr = | ||
167 | fn_def.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); | ||
168 | FunctionTemplate { | ||
169 | insert_offset, | ||
170 | placeholder_expr, | ||
171 | leading_ws, | ||
172 | fn_def, | ||
173 | trailing_ws, | ||
174 | file: self.file, | ||
175 | } | ||
176 | } | ||
177 | } | ||
178 | |||
179 | enum GeneratedFunctionTarget { | ||
180 | BehindItem(SyntaxNode), | ||
181 | InEmptyItemList(ast::ItemList), | ||
182 | } | ||
183 | |||
184 | impl GeneratedFunctionTarget { | ||
185 | fn syntax(&self) -> &SyntaxNode { | ||
186 | match self { | ||
187 | GeneratedFunctionTarget::BehindItem(it) => it, | ||
188 | GeneratedFunctionTarget::InEmptyItemList(it) => it.syntax(), | ||
189 | } | ||
190 | } | ||
191 | } | ||
192 | |||
193 | fn fn_name(call: &ast::Path) -> Option<ast::Name> { | ||
194 | let name = call.segment()?.syntax().to_string(); | ||
195 | Some(make::name(&name)) | ||
196 | } | ||
197 | |||
198 | /// Computes the type variables and arguments required for the generated function | ||
199 | fn fn_args( | ||
200 | ctx: &AssistContext, | ||
201 | target_module: hir::Module, | ||
202 | call: &ast::CallExpr, | ||
203 | ) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> { | ||
204 | let mut arg_names = Vec::new(); | ||
205 | let mut arg_types = Vec::new(); | ||
206 | for arg in call.arg_list()?.args() { | ||
207 | arg_names.push(match fn_arg_name(&arg) { | ||
208 | Some(name) => name, | ||
209 | None => String::from("arg"), | ||
210 | }); | ||
211 | arg_types.push(match fn_arg_type(ctx, target_module, &arg) { | ||
212 | Some(ty) => ty, | ||
213 | None => String::from("()"), | ||
214 | }); | ||
215 | } | ||
216 | deduplicate_arg_names(&mut arg_names); | ||
217 | let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| make::param(name, ty)); | ||
218 | Some((None, make::param_list(params))) | ||
219 | } | ||
220 | |||
221 | /// Makes duplicate argument names unique by appending incrementing numbers. | ||
222 | /// | ||
223 | /// ``` | ||
224 | /// let mut names: Vec<String> = | ||
225 | /// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()]; | ||
226 | /// deduplicate_arg_names(&mut names); | ||
227 | /// let expected: Vec<String> = | ||
228 | /// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()]; | ||
229 | /// assert_eq!(names, expected); | ||
230 | /// ``` | ||
231 | fn deduplicate_arg_names(arg_names: &mut Vec<String>) { | ||
232 | let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| { | ||
233 | *m.entry(name).or_insert(0) += 1; | ||
234 | m | ||
235 | }); | ||
236 | let duplicate_arg_names: FxHashSet<String> = arg_name_counts | ||
237 | .into_iter() | ||
238 | .filter(|(_, count)| *count >= 2) | ||
239 | .map(|(name, _)| name.clone()) | ||
240 | .collect(); | ||
241 | |||
242 | let mut counter_per_name = FxHashMap::default(); | ||
243 | for arg_name in arg_names.iter_mut() { | ||
244 | if duplicate_arg_names.contains(arg_name) { | ||
245 | let counter = counter_per_name.entry(arg_name.clone()).or_insert(1); | ||
246 | arg_name.push('_'); | ||
247 | arg_name.push_str(&counter.to_string()); | ||
248 | *counter += 1; | ||
249 | } | ||
250 | } | ||
251 | } | ||
252 | |||
253 | fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> { | ||
254 | match fn_arg { | ||
255 | ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?), | ||
256 | _ => Some( | ||
257 | fn_arg | ||
258 | .syntax() | ||
259 | .descendants() | ||
260 | .filter(|d| ast::NameRef::can_cast(d.kind())) | ||
261 | .last()? | ||
262 | .to_string(), | ||
263 | ), | ||
264 | } | ||
265 | } | ||
266 | |||
267 | fn fn_arg_type( | ||
268 | ctx: &AssistContext, | ||
269 | target_module: hir::Module, | ||
270 | fn_arg: &ast::Expr, | ||
271 | ) -> Option<String> { | ||
272 | let ty = ctx.sema.type_of_expr(fn_arg)?; | ||
273 | if ty.is_unknown() { | ||
274 | return None; | ||
275 | } | ||
276 | |||
277 | if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) { | ||
278 | Some(rendered) | ||
279 | } else { | ||
280 | None | ||
281 | } | ||
282 | } | ||
283 | |||
284 | /// Returns the position inside the current mod or file | ||
285 | /// directly after the current block | ||
286 | /// We want to write the generated function directly after | ||
287 | /// fns, impls or macro calls, but inside mods | ||
288 | fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option<GeneratedFunctionTarget> { | ||
289 | let mut ancestors = expr.syntax().ancestors().peekable(); | ||
290 | let mut last_ancestor: Option<SyntaxNode> = None; | ||
291 | while let Some(next_ancestor) = ancestors.next() { | ||
292 | match next_ancestor.kind() { | ||
293 | SyntaxKind::SOURCE_FILE => { | ||
294 | break; | ||
295 | } | ||
296 | SyntaxKind::ITEM_LIST => { | ||
297 | if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) { | ||
298 | break; | ||
299 | } | ||
300 | } | ||
301 | _ => {} | ||
302 | } | ||
303 | last_ancestor = Some(next_ancestor); | ||
304 | } | ||
305 | last_ancestor.map(GeneratedFunctionTarget::BehindItem) | ||
306 | } | ||
307 | |||
308 | fn next_space_for_fn_in_module( | ||
309 | db: &dyn hir::db::AstDatabase, | ||
310 | module_source: &hir::InFile<hir::ModuleSource>, | ||
311 | ) -> Option<(FileId, GeneratedFunctionTarget)> { | ||
312 | let file = module_source.file_id.original_file(db); | ||
313 | let assist_item = match &module_source.value { | ||
314 | hir::ModuleSource::SourceFile(it) => { | ||
315 | if let Some(last_item) = it.items().last() { | ||
316 | GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) | ||
317 | } else { | ||
318 | GeneratedFunctionTarget::BehindItem(it.syntax().clone()) | ||
319 | } | ||
320 | } | ||
321 | hir::ModuleSource::Module(it) => { | ||
322 | if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) { | ||
323 | GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) | ||
324 | } else { | ||
325 | GeneratedFunctionTarget::InEmptyItemList(it.item_list()?) | ||
326 | } | ||
327 | } | ||
328 | }; | ||
329 | Some((file, assist_item)) | ||
330 | } | ||
331 | |||
332 | #[cfg(test)] | ||
333 | mod tests { | ||
334 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
335 | |||
336 | use super::*; | ||
337 | |||
338 | #[test] | ||
339 | fn add_function_with_no_args() { | ||
340 | check_assist( | ||
341 | generate_function, | ||
342 | r" | ||
343 | fn foo() { | ||
344 | bar<|>(); | ||
345 | } | ||
346 | ", | ||
347 | r" | ||
348 | fn foo() { | ||
349 | bar(); | ||
350 | } | ||
351 | |||
352 | fn bar() { | ||
353 | ${0:todo!()} | ||
354 | } | ||
355 | ", | ||
356 | ) | ||
357 | } | ||
358 | |||
359 | #[test] | ||
360 | fn add_function_from_method() { | ||
361 | // This ensures that the function is correctly generated | ||
362 | // in the next outer mod or file | ||
363 | check_assist( | ||
364 | generate_function, | ||
365 | r" | ||
366 | impl Foo { | ||
367 | fn foo() { | ||
368 | bar<|>(); | ||
369 | } | ||
370 | } | ||
371 | ", | ||
372 | r" | ||
373 | impl Foo { | ||
374 | fn foo() { | ||
375 | bar(); | ||
376 | } | ||
377 | } | ||
378 | |||
379 | fn bar() { | ||
380 | ${0:todo!()} | ||
381 | } | ||
382 | ", | ||
383 | ) | ||
384 | } | ||
385 | |||
386 | #[test] | ||
387 | fn add_function_directly_after_current_block() { | ||
388 | // The new fn should not be created at the end of the file or module | ||
389 | check_assist( | ||
390 | generate_function, | ||
391 | r" | ||
392 | fn foo1() { | ||
393 | bar<|>(); | ||
394 | } | ||
395 | |||
396 | fn foo2() {} | ||
397 | ", | ||
398 | r" | ||
399 | fn foo1() { | ||
400 | bar(); | ||
401 | } | ||
402 | |||
403 | fn bar() { | ||
404 | ${0:todo!()} | ||
405 | } | ||
406 | |||
407 | fn foo2() {} | ||
408 | ", | ||
409 | ) | ||
410 | } | ||
411 | |||
412 | #[test] | ||
413 | fn add_function_with_no_args_in_same_module() { | ||
414 | check_assist( | ||
415 | generate_function, | ||
416 | r" | ||
417 | mod baz { | ||
418 | fn foo() { | ||
419 | bar<|>(); | ||
420 | } | ||
421 | } | ||
422 | ", | ||
423 | r" | ||
424 | mod baz { | ||
425 | fn foo() { | ||
426 | bar(); | ||
427 | } | ||
428 | |||
429 | fn bar() { | ||
430 | ${0:todo!()} | ||
431 | } | ||
432 | } | ||
433 | ", | ||
434 | ) | ||
435 | } | ||
436 | |||
437 | #[test] | ||
438 | fn add_function_with_function_call_arg() { | ||
439 | check_assist( | ||
440 | generate_function, | ||
441 | r" | ||
442 | struct Baz; | ||
443 | fn baz() -> Baz { todo!() } | ||
444 | fn foo() { | ||
445 | bar<|>(baz()); | ||
446 | } | ||
447 | ", | ||
448 | r" | ||
449 | struct Baz; | ||
450 | fn baz() -> Baz { todo!() } | ||
451 | fn foo() { | ||
452 | bar(baz()); | ||
453 | } | ||
454 | |||
455 | fn bar(baz: Baz) { | ||
456 | ${0:todo!()} | ||
457 | } | ||
458 | ", | ||
459 | ); | ||
460 | } | ||
461 | |||
462 | #[test] | ||
463 | fn add_function_with_method_call_arg() { | ||
464 | check_assist( | ||
465 | generate_function, | ||
466 | r" | ||
467 | struct Baz; | ||
468 | impl Baz { | ||
469 | fn foo(&self) -> Baz { | ||
470 | ba<|>r(self.baz()) | ||
471 | } | ||
472 | fn baz(&self) -> Baz { | ||
473 | Baz | ||
474 | } | ||
475 | } | ||
476 | ", | ||
477 | r" | ||
478 | struct Baz; | ||
479 | impl Baz { | ||
480 | fn foo(&self) -> Baz { | ||
481 | bar(self.baz()) | ||
482 | } | ||
483 | fn baz(&self) -> Baz { | ||
484 | Baz | ||
485 | } | ||
486 | } | ||
487 | |||
488 | fn bar(baz: Baz) { | ||
489 | ${0:todo!()} | ||
490 | } | ||
491 | ", | ||
492 | ) | ||
493 | } | ||
494 | |||
495 | #[test] | ||
496 | fn add_function_with_string_literal_arg() { | ||
497 | check_assist( | ||
498 | generate_function, | ||
499 | r#" | ||
500 | fn foo() { | ||
501 | <|>bar("bar") | ||
502 | } | ||
503 | "#, | ||
504 | r#" | ||
505 | fn foo() { | ||
506 | bar("bar") | ||
507 | } | ||
508 | |||
509 | fn bar(arg: &str) { | ||
510 | ${0:todo!()} | ||
511 | } | ||
512 | "#, | ||
513 | ) | ||
514 | } | ||
515 | |||
516 | #[test] | ||
517 | fn add_function_with_char_literal_arg() { | ||
518 | check_assist( | ||
519 | generate_function, | ||
520 | r#" | ||
521 | fn foo() { | ||
522 | <|>bar('x') | ||
523 | } | ||
524 | "#, | ||
525 | r#" | ||
526 | fn foo() { | ||
527 | bar('x') | ||
528 | } | ||
529 | |||
530 | fn bar(arg: char) { | ||
531 | ${0:todo!()} | ||
532 | } | ||
533 | "#, | ||
534 | ) | ||
535 | } | ||
536 | |||
537 | #[test] | ||
538 | fn add_function_with_int_literal_arg() { | ||
539 | check_assist( | ||
540 | generate_function, | ||
541 | r" | ||
542 | fn foo() { | ||
543 | <|>bar(42) | ||
544 | } | ||
545 | ", | ||
546 | r" | ||
547 | fn foo() { | ||
548 | bar(42) | ||
549 | } | ||
550 | |||
551 | fn bar(arg: i32) { | ||
552 | ${0:todo!()} | ||
553 | } | ||
554 | ", | ||
555 | ) | ||
556 | } | ||
557 | |||
558 | #[test] | ||
559 | fn add_function_with_cast_int_literal_arg() { | ||
560 | check_assist( | ||
561 | generate_function, | ||
562 | r" | ||
563 | fn foo() { | ||
564 | <|>bar(42 as u8) | ||
565 | } | ||
566 | ", | ||
567 | r" | ||
568 | fn foo() { | ||
569 | bar(42 as u8) | ||
570 | } | ||
571 | |||
572 | fn bar(arg: u8) { | ||
573 | ${0:todo!()} | ||
574 | } | ||
575 | ", | ||
576 | ) | ||
577 | } | ||
578 | |||
579 | #[test] | ||
580 | fn name_of_cast_variable_is_used() { | ||
581 | // Ensures that the name of the cast type isn't used | ||
582 | // in the generated function signature. | ||
583 | check_assist( | ||
584 | generate_function, | ||
585 | r" | ||
586 | fn foo() { | ||
587 | let x = 42; | ||
588 | bar<|>(x as u8) | ||
589 | } | ||
590 | ", | ||
591 | r" | ||
592 | fn foo() { | ||
593 | let x = 42; | ||
594 | bar(x as u8) | ||
595 | } | ||
596 | |||
597 | fn bar(x: u8) { | ||
598 | ${0:todo!()} | ||
599 | } | ||
600 | ", | ||
601 | ) | ||
602 | } | ||
603 | |||
604 | #[test] | ||
605 | fn add_function_with_variable_arg() { | ||
606 | check_assist( | ||
607 | generate_function, | ||
608 | r" | ||
609 | fn foo() { | ||
610 | let worble = (); | ||
611 | <|>bar(worble) | ||
612 | } | ||
613 | ", | ||
614 | r" | ||
615 | fn foo() { | ||
616 | let worble = (); | ||
617 | bar(worble) | ||
618 | } | ||
619 | |||
620 | fn bar(worble: ()) { | ||
621 | ${0:todo!()} | ||
622 | } | ||
623 | ", | ||
624 | ) | ||
625 | } | ||
626 | |||
627 | #[test] | ||
628 | fn add_function_with_impl_trait_arg() { | ||
629 | check_assist( | ||
630 | generate_function, | ||
631 | r" | ||
632 | trait Foo {} | ||
633 | fn foo() -> impl Foo { | ||
634 | todo!() | ||
635 | } | ||
636 | fn baz() { | ||
637 | <|>bar(foo()) | ||
638 | } | ||
639 | ", | ||
640 | r" | ||
641 | trait Foo {} | ||
642 | fn foo() -> impl Foo { | ||
643 | todo!() | ||
644 | } | ||
645 | fn baz() { | ||
646 | bar(foo()) | ||
647 | } | ||
648 | |||
649 | fn bar(foo: impl Foo) { | ||
650 | ${0:todo!()} | ||
651 | } | ||
652 | ", | ||
653 | ) | ||
654 | } | ||
655 | |||
656 | #[test] | ||
657 | fn borrowed_arg() { | ||
658 | check_assist( | ||
659 | generate_function, | ||
660 | r" | ||
661 | struct Baz; | ||
662 | fn baz() -> Baz { todo!() } | ||
663 | |||
664 | fn foo() { | ||
665 | bar<|>(&baz()) | ||
666 | } | ||
667 | ", | ||
668 | r" | ||
669 | struct Baz; | ||
670 | fn baz() -> Baz { todo!() } | ||
671 | |||
672 | fn foo() { | ||
673 | bar(&baz()) | ||
674 | } | ||
675 | |||
676 | fn bar(baz: &Baz) { | ||
677 | ${0:todo!()} | ||
678 | } | ||
679 | ", | ||
680 | ) | ||
681 | } | ||
682 | |||
683 | #[test] | ||
684 | fn add_function_with_qualified_path_arg() { | ||
685 | check_assist( | ||
686 | generate_function, | ||
687 | r" | ||
688 | mod Baz { | ||
689 | pub struct Bof; | ||
690 | pub fn baz() -> Bof { Bof } | ||
691 | } | ||
692 | fn foo() { | ||
693 | <|>bar(Baz::baz()) | ||
694 | } | ||
695 | ", | ||
696 | r" | ||
697 | mod Baz { | ||
698 | pub struct Bof; | ||
699 | pub fn baz() -> Bof { Bof } | ||
700 | } | ||
701 | fn foo() { | ||
702 | bar(Baz::baz()) | ||
703 | } | ||
704 | |||
705 | fn bar(baz: Baz::Bof) { | ||
706 | ${0:todo!()} | ||
707 | } | ||
708 | ", | ||
709 | ) | ||
710 | } | ||
711 | |||
712 | #[test] | ||
713 | #[ignore] | ||
714 | // FIXME fix printing the generics of a `Ty` to make this test pass | ||
715 | fn add_function_with_generic_arg() { | ||
716 | check_assist( | ||
717 | generate_function, | ||
718 | r" | ||
719 | fn foo<T>(t: T) { | ||
720 | <|>bar(t) | ||
721 | } | ||
722 | ", | ||
723 | r" | ||
724 | fn foo<T>(t: T) { | ||
725 | bar(t) | ||
726 | } | ||
727 | |||
728 | fn bar<T>(t: T) { | ||
729 | ${0:todo!()} | ||
730 | } | ||
731 | ", | ||
732 | ) | ||
733 | } | ||
734 | |||
735 | #[test] | ||
736 | #[ignore] | ||
737 | // FIXME Fix function type printing to make this test pass | ||
738 | fn add_function_with_fn_arg() { | ||
739 | check_assist( | ||
740 | generate_function, | ||
741 | r" | ||
742 | struct Baz; | ||
743 | impl Baz { | ||
744 | fn new() -> Self { Baz } | ||
745 | } | ||
746 | fn foo() { | ||
747 | <|>bar(Baz::new); | ||
748 | } | ||