diff options
Diffstat (limited to 'crates/assists')
48 files changed, 16758 insertions, 0 deletions
diff --git a/crates/assists/Cargo.toml b/crates/assists/Cargo.toml new file mode 100644 index 000000000..a560a35c7 --- /dev/null +++ b/crates/assists/Cargo.toml | |||
@@ -0,0 +1,23 @@ | |||
1 | [package] | ||
2 | name = "assists" | ||
3 | version = "0.0.0" | ||
4 | license = "MIT OR Apache-2.0" | ||
5 | authors = ["rust-analyzer developers"] | ||
6 | edition = "2018" | ||
7 | |||
8 | [lib] | ||
9 | doctest = false | ||
10 | |||
11 | [dependencies] | ||
12 | rustc-hash = "1.1.0" | ||
13 | itertools = "0.9.0" | ||
14 | either = "1.5.3" | ||
15 | |||
16 | stdx = { path = "../stdx" } | ||
17 | syntax = { path = "../syntax" } | ||
18 | text_edit = { path = "../text_edit" } | ||
19 | profile = { path = "../profile" } | ||
20 | base_db = { path = "../base_db" } | ||
21 | ide_db = { path = "../ide_db" } | ||
22 | hir = { path = "../hir" } | ||
23 | test_utils = { path = "../test_utils" } | ||
diff --git a/crates/assists/src/assist_config.rs b/crates/assists/src/assist_config.rs new file mode 100644 index 000000000..cda2abfb9 --- /dev/null +++ b/crates/assists/src/assist_config.rs | |||
@@ -0,0 +1,30 @@ | |||
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/assists/src/assist_context.rs b/crates/assists/src/assist_context.rs new file mode 100644 index 000000000..79574b9ac --- /dev/null +++ b/crates/assists/src/assist_context.rs | |||
@@ -0,0 +1,291 @@ | |||
1 | //! See `AssistContext` | ||
2 | |||
3 | use std::mem; | ||
4 | |||
5 | use algo::find_covering_element; | ||
6 | use base_db::{FileId, FileRange}; | ||
7 | use hir::Semantics; | ||
8 | use ide_db::{ | ||
9 | source_change::{SourceChange, SourceFileEdit}, | ||
10 | RootDatabase, | ||
11 | }; | ||
12 | use syntax::{ | ||
13 | algo::{self, find_node_at_offset, SyntaxRewriter}, | ||
14 | AstNode, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange, TextSize, | ||
15 | TokenAtOffset, | ||
16 | }; | ||
17 | use text_edit::{TextEdit, TextEditBuilder}; | ||
18 | |||
19 | use crate::{ | ||
20 | assist_config::{AssistConfig, SnippetCap}, | ||
21 | Assist, AssistId, AssistKind, GroupLabel, ResolvedAssist, | ||
22 | }; | ||
23 | |||
24 | /// `AssistContext` allows to apply an assist or check if it could be applied. | ||
25 | /// | ||
26 | /// Assists use a somewhat over-engineered approach, given the current needs. | ||
27 | /// The assists workflow consists of two phases. In the first phase, a user asks | ||
28 | /// for the list of available assists. In the second phase, the user picks a | ||
29 | /// particular assist and it gets applied. | ||
30 | /// | ||
31 | /// There are two peculiarities here: | ||
32 | /// | ||
33 | /// * first, we ideally avoid computing more things then necessary to answer "is | ||
34 | /// assist applicable" in the first phase. | ||
35 | /// * second, when we are applying assist, we don't have a guarantee that there | ||
36 | /// weren't any changes between the point when user asked for assists and when | ||
37 | /// they applied a particular assist. So, when applying assist, we need to do | ||
38 | /// all the checks from scratch. | ||
39 | /// | ||
40 | /// To avoid repeating the same code twice for both "check" and "apply" | ||
41 | /// functions, we use an approach reminiscent of that of Django's function based | ||
42 | /// views dealing with forms. Each assist receives a runtime parameter, | ||
43 | /// `resolve`. It first check if an edit is applicable (potentially computing | ||
44 | /// info required to compute the actual edit). If it is applicable, and | ||
45 | /// `resolve` is `true`, it then computes the actual edit. | ||
46 | /// | ||
47 | /// So, to implement the original assists workflow, we can first apply each edit | ||
48 | /// with `resolve = false`, and then applying the selected edit again, with | ||
49 | /// `resolve = true` this time. | ||
50 | /// | ||
51 | /// Note, however, that we don't actually use such two-phase logic at the | ||
52 | /// moment, because the LSP API is pretty awkward in this place, and it's much | ||
53 | /// easier to just compute the edit eagerly :-) | ||
54 | pub(crate) struct AssistContext<'a> { | ||
55 | pub(crate) config: &'a AssistConfig, | ||
56 | pub(crate) sema: Semantics<'a, RootDatabase>, | ||
57 | pub(crate) frange: FileRange, | ||
58 | source_file: SourceFile, | ||
59 | } | ||
60 | |||
61 | impl<'a> AssistContext<'a> { | ||
62 | pub(crate) fn new( | ||
63 | sema: Semantics<'a, RootDatabase>, | ||
64 | config: &'a AssistConfig, | ||
65 | frange: FileRange, | ||
66 | ) -> AssistContext<'a> { | ||
67 | let source_file = sema.parse(frange.file_id); | ||
68 | AssistContext { config, sema, frange, source_file } | ||
69 | } | ||
70 | |||
71 | pub(crate) fn db(&self) -> &RootDatabase { | ||
72 | self.sema.db | ||
73 | } | ||
74 | |||
75 | pub(crate) fn source_file(&self) -> &SourceFile { | ||
76 | &self.source_file | ||
77 | } | ||
78 | |||
79 | // NB, this ignores active selection. | ||
80 | pub(crate) fn offset(&self) -> TextSize { | ||
81 | self.frange.range.start() | ||
82 | } | ||
83 | |||
84 | pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> { | ||
85 | self.source_file.syntax().token_at_offset(self.offset()) | ||
86 | } | ||
87 | pub(crate) fn find_token_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> { | ||
88 | self.token_at_offset().find(|it| it.kind() == kind) | ||
89 | } | ||
90 | pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> { | ||
91 | find_node_at_offset(self.source_file.syntax(), self.offset()) | ||
92 | } | ||
93 | pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> { | ||
94 | self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset()) | ||
95 | } | ||
96 | pub(crate) fn covering_element(&self) -> SyntaxElement { | ||
97 | find_covering_element(self.source_file.syntax(), self.frange.range) | ||
98 | } | ||
99 | // FIXME: remove | ||
100 | pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement { | ||
101 | find_covering_element(self.source_file.syntax(), range) | ||
102 | } | ||
103 | } | ||
104 | |||
105 | pub(crate) struct Assists { | ||
106 | resolve: bool, | ||
107 | file: FileId, | ||
108 | buf: Vec<(Assist, Option<SourceChange>)>, | ||
109 | allowed: Option<Vec<AssistKind>>, | ||
110 | } | ||
111 | |||
112 | impl Assists { | ||
113 | pub(crate) fn new_resolved(ctx: &AssistContext) -> Assists { | ||
114 | Assists { | ||
115 | resolve: true, | ||
116 | file: ctx.frange.file_id, | ||
117 | buf: Vec::new(), | ||
118 | allowed: ctx.config.allowed.clone(), | ||
119 | } | ||
120 | } | ||
121 | |||
122 | pub(crate) fn new_unresolved(ctx: &AssistContext) -> Assists { | ||
123 | Assists { | ||
124 | resolve: false, | ||
125 | file: ctx.frange.file_id, | ||
126 | buf: Vec::new(), | ||
127 | allowed: ctx.config.allowed.clone(), | ||
128 | } | ||
129 | } | ||
130 | |||
131 | pub(crate) fn finish_unresolved(self) -> Vec<Assist> { | ||
132 | assert!(!self.resolve); | ||
133 | self.finish() | ||
134 | .into_iter() | ||
135 | .map(|(label, edit)| { | ||
136 | assert!(edit.is_none()); | ||
137 | label | ||
138 | }) | ||
139 | .collect() | ||
140 | } | ||
141 | |||
142 | pub(crate) fn finish_resolved(self) -> Vec<ResolvedAssist> { | ||
143 | assert!(self.resolve); | ||
144 | self.finish() | ||
145 | .into_iter() | ||
146 | .map(|(label, edit)| ResolvedAssist { assist: label, source_change: edit.unwrap() }) | ||
147 | .collect() | ||
148 | } | ||
149 | |||
150 | pub(crate) fn add( | ||
151 | &mut self, | ||
152 | id: AssistId, | ||
153 | label: impl Into<String>, | ||
154 | target: TextRange, | ||
155 | f: impl FnOnce(&mut AssistBuilder), | ||
156 | ) -> Option<()> { | ||
157 | if !self.is_allowed(&id) { | ||
158 | return None; | ||
159 | } | ||
160 | let label = Assist::new(id, label.into(), None, target); | ||
161 | self.add_impl(label, f) | ||
162 | } | ||
163 | |||
164 | pub(crate) fn add_group( | ||
165 | &mut self, | ||
166 | group: &GroupLabel, | ||
167 | id: AssistId, | ||
168 | label: impl Into<String>, | ||
169 | target: TextRange, | ||
170 | f: impl FnOnce(&mut AssistBuilder), | ||
171 | ) -> Option<()> { | ||
172 | if !self.is_allowed(&id) { | ||
173 | return None; | ||
174 | } | ||
175 | |||
176 | let label = Assist::new(id, label.into(), Some(group.clone()), target); | ||
177 | self.add_impl(label, f) | ||
178 | } | ||
179 | |||
180 | fn add_impl(&mut self, label: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> { | ||
181 | let source_change = if self.resolve { | ||
182 | let mut builder = AssistBuilder::new(self.file); | ||
183 | f(&mut builder); | ||
184 | Some(builder.finish()) | ||
185 | } else { | ||
186 | None | ||
187 | }; | ||
188 | |||
189 | self.buf.push((label, source_change)); | ||
190 | Some(()) | ||
191 | } | ||
192 | |||
193 | fn finish(mut self) -> Vec<(Assist, Option<SourceChange>)> { | ||
194 | self.buf.sort_by_key(|(label, _edit)| label.target.len()); | ||
195 | self.buf | ||
196 | } | ||
197 | |||
198 | fn is_allowed(&self, id: &AssistId) -> bool { | ||
199 | match &self.allowed { | ||
200 | Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)), | ||
201 | None => true, | ||
202 | } | ||
203 | } | ||
204 | } | ||
205 | |||
206 | pub(crate) struct AssistBuilder { | ||
207 | edit: TextEditBuilder, | ||
208 | file_id: FileId, | ||
209 | is_snippet: bool, | ||
210 | change: SourceChange, | ||
211 | } | ||
212 | |||
213 | impl AssistBuilder { | ||
214 | pub(crate) fn new(file_id: FileId) -> AssistBuilder { | ||
215 | AssistBuilder { | ||
216 | edit: TextEdit::builder(), | ||
217 | file_id, | ||
218 | is_snippet: false, | ||
219 | change: SourceChange::default(), | ||
220 | } | ||
221 | } | ||
222 | |||
223 | pub(crate) fn edit_file(&mut self, file_id: FileId) { | ||
224 | self.file_id = file_id; | ||
225 | } | ||
226 | |||
227 | fn commit(&mut self) { | ||
228 | let edit = mem::take(&mut self.edit).finish(); | ||
229 | if !edit.is_empty() { | ||
230 | let new_edit = SourceFileEdit { file_id: self.file_id, edit }; | ||
231 | assert!(!self.change.source_file_edits.iter().any(|it| it.file_id == new_edit.file_id)); | ||
232 | self.change.source_file_edits.push(new_edit); | ||
233 | } | ||
234 | } | ||
235 | |||
236 | /// Remove specified `range` of text. | ||
237 | pub(crate) fn delete(&mut self, range: TextRange) { | ||
238 | self.edit.delete(range) | ||
239 | } | ||
240 | /// Append specified `text` at the given `offset` | ||
241 | pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) { | ||
242 | self.edit.insert(offset, text.into()) | ||
243 | } | ||
244 | /// Append specified `snippet` at the given `offset` | ||
245 | pub(crate) fn insert_snippet( | ||
246 | &mut self, | ||
247 | _cap: SnippetCap, | ||
248 | offset: TextSize, | ||
249 | snippet: impl Into<String>, | ||
250 | ) { | ||
251 | self.is_snippet = true; | ||
252 | self.insert(offset, snippet); | ||
253 | } | ||
254 | /// Replaces specified `range` of text with a given string. | ||
255 | pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) { | ||
256 | self.edit.replace(range, replace_with.into()) | ||
257 | } | ||
258 | /// Replaces specified `range` of text with a given `snippet`. | ||
259 | pub(crate) fn replace_snippet( | ||
260 | &mut self, | ||
261 | _cap: SnippetCap, | ||
262 | range: TextRange, | ||
263 | snippet: impl Into<String>, | ||
264 | ) { | ||
265 | self.is_snippet = true; | ||
266 | self.replace(range, snippet); | ||
267 | } | ||
268 | pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) { | ||
269 | algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit) | ||
270 | } | ||
271 | pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) { | ||
272 | let node = rewriter.rewrite_root().unwrap(); | ||
273 | let new = rewriter.rewrite(&node); | ||
274 | algo::diff(&node, &new).into_text_edit(&mut self.edit); | ||
275 | } | ||
276 | |||
277 | // FIXME: kill this API | ||
278 | /// Get access to the raw `TextEditBuilder`. | ||
279 | pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder { | ||
280 | &mut self.edit | ||
281 | } | ||
282 | |||
283 | fn finish(mut self) -> SourceChange { | ||
284 | self.commit(); | ||
285 | let mut change = mem::take(&mut self.change); | ||
286 | if self.is_snippet { | ||
287 | change.is_snippet = true; | ||
288 | } | ||
289 | change | ||
290 | } | ||
291 | } | ||
diff --git a/crates/assists/src/ast_transform.rs b/crates/assists/src/ast_transform.rs new file mode 100644 index 000000000..4c41c16d8 --- /dev/null +++ b/crates/assists/src/ast_transform.rs | |||
@@ -0,0 +1,206 @@ | |||
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 syntax::{ | ||
6 | algo::SyntaxRewriter, | ||
7 | ast::{self, AstNode}, | ||
8 | }; | ||
9 | |||
10 | pub trait AstTransform<'a> { | ||
11 | fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<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: &syntax::SyntaxNode) -> Option<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 parameters. | ||
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(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
105 | let type_ref = ast::Type::cast(node.clone())?; | ||
106 | let path = match &type_ref { | ||
107 | ast::Type::PathType(path_type) => path_type.path()?, | ||
108 | _ => return None, | ||
109 | }; | ||
110 | // FIXME: use `hir::Path::from_src` instead. | ||
111 | #[allow(deprecated)] | ||
112 | let path = hir::Path::from_ast(path)?; | ||
113 | let resolution = self.source_scope.resolve_hir_path(&path)?; | ||
114 | match resolution { | ||
115 | hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()), | ||
116 | _ => None, | ||
117 | } | ||
118 | } | ||
119 | } | ||
120 | |||
121 | impl<'a> AstTransform<'a> for SubstituteTypeParams<'a> { | ||
122 | fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
123 | self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node)) | ||
124 | } | ||
125 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
126 | Box::new(SubstituteTypeParams { previous: other, ..self }) | ||
127 | } | ||
128 | } | ||
129 | |||
130 | pub struct QualifyPaths<'a> { | ||
131 | target_scope: &'a SemanticsScope<'a>, | ||
132 | source_scope: &'a SemanticsScope<'a>, | ||
133 | previous: Box<dyn AstTransform<'a> + 'a>, | ||
134 | } | ||
135 | |||
136 | impl<'a> QualifyPaths<'a> { | ||
137 | pub fn new(target_scope: &'a SemanticsScope<'a>, source_scope: &'a SemanticsScope<'a>) -> Self { | ||
138 | Self { target_scope, source_scope, previous: Box::new(NullTransformer) } | ||
139 | } | ||
140 | |||
141 | fn get_substitution_inner(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
142 | // FIXME handle value ns? | ||
143 | let from = self.target_scope.module()?; | ||
144 | let p = ast::Path::cast(node.clone())?; | ||
145 | if p.segment().and_then(|s| s.param_list()).is_some() { | ||
146 | // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway | ||
147 | return None; | ||
148 | } | ||
149 | // FIXME: use `hir::Path::from_src` instead. | ||
150 | #[allow(deprecated)] | ||
151 | let hir_path = hir::Path::from_ast(p.clone()); | ||
152 | let resolution = self.source_scope.resolve_hir_path(&hir_path?)?; | ||
153 | match resolution { | ||
154 | PathResolution::Def(def) => { | ||
155 | let found_path = from.find_use_path(self.source_scope.db.upcast(), def)?; | ||
156 | let mut path = path_to_ast(found_path); | ||
157 | |||
158 | let type_args = p | ||
159 | .segment() | ||
160 | .and_then(|s| s.generic_arg_list()) | ||
161 | .map(|arg_list| apply(self, arg_list)); | ||
162 | if let Some(type_args) = type_args { | ||
163 | let last_segment = path.segment().unwrap(); | ||
164 | path = path.with_segment(last_segment.with_type_args(type_args)) | ||
165 | } | ||
166 | |||
167 | Some(path.syntax().clone()) | ||
168 | } | ||
169 | PathResolution::Local(_) | ||
170 | | PathResolution::TypeParam(_) | ||
171 | | PathResolution::SelfType(_) => None, | ||
172 | PathResolution::Macro(_) => None, | ||
173 | PathResolution::AssocItem(_) => None, | ||
174 | } | ||
175 | } | ||
176 | } | ||
177 | |||
178 | pub fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: N) -> N { | ||
179 | SyntaxRewriter::from_fn(|element| match element { | ||
180 | syntax::SyntaxElement::Node(n) => { | ||
181 | let replacement = transformer.get_substitution(&n)?; | ||
182 | Some(replacement.into()) | ||
183 | } | ||
184 | _ => None, | ||
185 | }) | ||
186 | .rewrite_ast(&node) | ||
187 | } | ||
188 | |||
189 | impl<'a> AstTransform<'a> for QualifyPaths<'a> { | ||
190 | fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
191 | self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node)) | ||
192 | } | ||
193 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
194 | Box::new(QualifyPaths { previous: other, ..self }) | ||
195 | } | ||
196 | } | ||
197 | |||
198 | pub(crate) fn path_to_ast(path: hir::ModPath) -> ast::Path { | ||
199 | let parse = ast::SourceFile::parse(&path.to_string()); | ||
200 | parse | ||
201 | .tree() | ||
202 | .syntax() | ||
203 | .descendants() | ||
204 | .find_map(ast::Path::cast) | ||
205 | .unwrap_or_else(|| panic!("failed to parse path {:?}, `{}`", path, path)) | ||
206 | } | ||
diff --git a/crates/assists/src/handlers/add_custom_impl.rs b/crates/assists/src/handlers/add_custom_impl.rs new file mode 100644 index 000000000..8757fa33f --- /dev/null +++ b/crates/assists/src/handlers/add_custom_impl.rs | |||
@@ -0,0 +1,208 @@ | |||
1 | use itertools::Itertools; | ||
2 | use syntax::{ | ||
3 | ast::{self, AstNode}, | ||
4 | Direction, SmolStr, | ||
5 | SyntaxKind::{IDENT, WHITESPACE}, | ||
6 | TextRange, TextSize, | ||
7 | }; | ||
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 | |||
65 | if has_more_derives { | ||
66 | let new_attr_input = format!("({})", new_attr_input.iter().format(", ")); | ||
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/assists/src/handlers/add_explicit_type.rs b/crates/assists/src/handlers/add_explicit_type.rs new file mode 100644 index 000000000..563cbf505 --- /dev/null +++ b/crates/assists/src/handlers/add_explicit_type.rs | |||
@@ -0,0 +1,211 @@ | |||
1 | use hir::HirDisplay; | ||
2 | use 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/assists/src/handlers/add_missing_impl_members.rs b/crates/assists/src/handlers/add_missing_impl_members.rs new file mode 100644 index 000000000..81b61ebf8 --- /dev/null +++ b/crates/assists/src/handlers/add_missing_impl_members.rs | |||
@@ -0,0 +1,711 @@ | |||
1 | use hir::HasSource; | ||
2 | use 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 = profile::span("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/assists/src/handlers/add_turbo_fish.rs b/crates/assists/src/handlers/add_turbo_fish.rs new file mode 100644 index 000000000..f4f997d8e --- /dev/null +++ b/crates/assists/src/handlers/add_turbo_fish.rs | |||
@@ -0,0 +1,164 @@ | |||
1 | use ide_db::defs::{classify_name_ref, Definition, NameRefClass}; | ||
2 | use 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::ExternCrate(_) | 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/assists/src/handlers/apply_demorgan.rs b/crates/assists/src/handlers/apply_demorgan.rs new file mode 100644 index 000000000..1a6fdafda --- /dev/null +++ b/crates/assists/src/handlers/apply_demorgan.rs | |||
@@ -0,0 +1,93 @@ | |||
1 | use syntax::ast::{self, AstNode}; | ||
2 | |||
3 | use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKind, Assists}; | ||
4 | |||
5 | // Assist: apply_demorgan | ||
6 | // | ||
7 | // Apply https://en.wikipedia.org/wiki/De_Morgan%27s_laws[De Morgan's law]. | ||
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/assists/src/handlers/auto_import.rs b/crates/assists/src/handlers/auto_import.rs new file mode 100644 index 000000000..cce789972 --- /dev/null +++ b/crates/assists/src/handlers/auto_import.rs | |||
@@ -0,0 +1,1088 @@ | |||
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 ide_db::{imports_locator, RootDatabase}; | ||
9 | use rustc_hash::FxHashSet; | ||
10 | use syntax::{ | ||
11 | ast::{self, AstNode}, | ||
12 | SyntaxNode, | ||
13 | }; | ||
14 | |||
15 | use crate::{ | ||
16 | utils::insert_use_statement, AssistContext, AssistId, AssistKind, Assists, GroupLabel, | ||
17 | }; | ||
18 | |||
19 | // Assist: auto_import | ||
20 | // | ||
21 | // If the name is unresolved, provides all possible imports for it. | ||
22 | // | ||
23 | // ``` | ||
24 | // fn main() { | ||
25 | // let map = HashMap<|>::new(); | ||
26 | // } | ||
27 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | ||
28 | // ``` | ||
29 | // -> | ||
30 | // ``` | ||
31 | // use std::collections::HashMap; | ||
32 | // | ||
33 | // fn main() { | ||
34 | // let map = HashMap::new(); | ||
35 | // } | ||
36 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | ||
37 | // ``` | ||
38 | pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
39 | let auto_import_assets = AutoImportAssets::new(ctx)?; | ||
40 | let proposed_imports = auto_import_assets.search_for_imports(ctx); | ||
41 | if proposed_imports.is_empty() { | ||
42 | return None; | ||
43 | } | ||
44 | |||
45 | let range = ctx.sema.original_range(&auto_import_assets.syntax_under_caret).range; | ||
46 | let group = auto_import_assets.get_import_group_message(); | ||
47 | for import in proposed_imports { | ||
48 | acc.add_group( | ||
49 | &group, | ||
50 | AssistId("auto_import", AssistKind::QuickFix), | ||
51 | format!("Import `{}`", &import), | ||
52 | range, | ||
53 | |builder| { | ||
54 | insert_use_statement( | ||
55 | &auto_import_assets.syntax_under_caret, | ||
56 | &import, | ||
57 | ctx, | ||
58 | builder.text_edit_builder(), | ||
59 | ); | ||
60 | }, | ||
61 | ); | ||
62 | } | ||
63 | Some(()) | ||
64 | } | ||
65 | |||
66 | #[derive(Debug)] | ||
67 | struct AutoImportAssets { | ||
68 | import_candidate: ImportCandidate, | ||
69 | module_with_name_to_import: Module, | ||
70 | syntax_under_caret: SyntaxNode, | ||
71 | } | ||
72 | |||
73 | impl AutoImportAssets { | ||
74 | fn new(ctx: &AssistContext) -> Option<Self> { | ||
75 | if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() { | ||
76 | Self::for_regular_path(path_under_caret, &ctx) | ||
77 | } else { | ||
78 | Self::for_method_call(ctx.find_node_at_offset_with_descend()?, &ctx) | ||
79 | } | ||
80 | } | ||
81 | |||
82 | fn for_method_call(method_call: ast::MethodCallExpr, ctx: &AssistContext) -> Option<Self> { | ||
83 | let syntax_under_caret = method_call.syntax().to_owned(); | ||
84 | let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?; | ||
85 | Some(Self { | ||
86 | import_candidate: ImportCandidate::for_method_call(&ctx.sema, &method_call)?, | ||
87 | module_with_name_to_import, | ||
88 | syntax_under_caret, | ||
89 | }) | ||
90 | } | ||
91 | |||
92 | fn for_regular_path(path_under_caret: ast::Path, ctx: &AssistContext) -> Option<Self> { | ||
93 | let syntax_under_caret = path_under_caret.syntax().to_owned(); | ||
94 | if syntax_under_caret.ancestors().find_map(ast::Use::cast).is_some() { | ||
95 | return None; | ||
96 | } | ||
97 | |||
98 | let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?; | ||
99 | Some(Self { | ||
100 | import_candidate: ImportCandidate::for_regular_path(&ctx.sema, &path_under_caret)?, | ||
101 | module_with_name_to_import, | ||
102 | syntax_under_caret, | ||
103 | }) | ||
104 | } | ||
105 | |||
106 | fn get_search_query(&self) -> &str { | ||
107 | match &self.import_candidate { | ||
108 | ImportCandidate::UnqualifiedName(name) => name, | ||
109 | ImportCandidate::QualifierStart(qualifier_start) => qualifier_start, | ||
110 | ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => trait_assoc_item_name, | ||
111 | ImportCandidate::TraitMethod(_, trait_method_name) => trait_method_name, | ||
112 | } | ||
113 | } | ||
114 | |||
115 | fn get_import_group_message(&self) -> GroupLabel { | ||
116 | let name = match &self.import_candidate { | ||
117 | ImportCandidate::UnqualifiedName(name) => format!("Import {}", name), | ||
118 | ImportCandidate::QualifierStart(qualifier_start) => { | ||
119 | format!("Import {}", qualifier_start) | ||
120 | } | ||
121 | ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => { | ||
122 | format!("Import a trait for item {}", trait_assoc_item_name) | ||
123 | } | ||
124 | ImportCandidate::TraitMethod(_, trait_method_name) => { | ||
125 | format!("Import a trait for method {}", trait_method_name) | ||
126 | } | ||
127 | }; | ||
128 | GroupLabel(name) | ||
129 | } | ||
130 | |||
131 | fn search_for_imports(&self, ctx: &AssistContext) -> BTreeSet<ModPath> { | ||
132 | let _p = profile::span("auto_import::search_for_imports"); | ||
133 | let db = ctx.db(); | ||
134 | let current_crate = self.module_with_name_to_import.krate(); | ||
135 | imports_locator::find_imports(&ctx.sema, current_crate, &self.get_search_query()) | ||
136 | .into_iter() | ||
137 | .filter_map(|candidate| match &self.import_candidate { | ||
138 | ImportCandidate::TraitAssocItem(assoc_item_type, _) => { | ||
139 | let located_assoc_item = match candidate { | ||
140 | Either::Left(ModuleDef::Function(located_function)) => located_function | ||
141 | .as_assoc_item(db) | ||
142 | .map(|assoc| assoc.container(db)) | ||
143 | .and_then(Self::assoc_to_trait), | ||
144 | Either::Left(ModuleDef::Const(located_const)) => located_const | ||
145 | .as_assoc_item(db) | ||
146 | .map(|assoc| assoc.container(db)) | ||
147 | .and_then(Self::assoc_to_trait), | ||
148 | _ => None, | ||
149 | }?; | ||
150 | |||
151 | let mut trait_candidates = FxHashSet::default(); | ||
152 | trait_candidates.insert(located_assoc_item.into()); | ||
153 | |||
154 | assoc_item_type | ||
155 | .iterate_path_candidates( | ||
156 | db, | ||
157 | current_crate, | ||
158 | &trait_candidates, | ||
159 | None, | ||
160 | |_, assoc| Self::assoc_to_trait(assoc.container(db)), | ||
161 | ) | ||
162 | .map(ModuleDef::from) | ||
163 | .map(Either::Left) | ||
164 | } | ||
165 | ImportCandidate::TraitMethod(function_callee, _) => { | ||
166 | let located_assoc_item = | ||
167 | if let Either::Left(ModuleDef::Function(located_function)) = candidate { | ||
168 | located_function | ||
169 | .as_assoc_item(db) | ||
170 | .map(|assoc| assoc.container(db)) | ||
171 | .and_then(Self::assoc_to_trait) | ||
172 | } else { | ||
173 | None | ||
174 | }?; | ||
175 | |||
176 | let mut trait_candidates = FxHashSet::default(); | ||
177 | trait_candidates.insert(located_assoc_item.into()); | ||
178 | |||
179 | function_callee | ||
180 | .iterate_method_candidates( | ||
181 | db, | ||
182 | current_crate, | ||
183 | &trait_candidates, | ||
184 | None, | ||
185 | |_, function| { | ||
186 | Self::assoc_to_trait(function.as_assoc_item(db)?.container(db)) | ||
187 | }, | ||
188 | ) | ||
189 | .map(ModuleDef::from) | ||
190 | .map(Either::Left) | ||
191 | } | ||
192 | _ => Some(candidate), | ||
193 | }) | ||
194 | .filter_map(|candidate| match candidate { | ||
195 | Either::Left(module_def) => { | ||
196 | self.module_with_name_to_import.find_use_path(db, module_def) | ||
197 | } | ||
198 | Either::Right(macro_def) => { | ||
199 | self.module_with_name_to_import.find_use_path(db, macro_def) | ||
200 | } | ||
201 | }) | ||
202 | .filter(|use_path| !use_path.segments.is_empty()) | ||
203 | .take(20) | ||
204 | .collect::<BTreeSet<_>>() | ||
205 | } | ||
206 | |||
207 | fn assoc_to_trait(assoc: AssocItemContainer) -> Option<Trait> { | ||
208 | if let AssocItemContainer::Trait(extracted_trait) = assoc { | ||
209 | Some(extracted_trait) | ||
210 | } else { | ||
211 | None | ||
212 | } | ||
213 | } | ||
214 | } | ||
215 | |||
216 | #[derive(Debug)] | ||
217 | enum ImportCandidate { | ||
218 | /// Simple name like 'HashMap' | ||
219 | UnqualifiedName(String), | ||
220 | /// First part of the qualified name. | ||
221 | /// For 'std::collections::HashMap', that will be 'std'. | ||
222 | QualifierStart(String), | ||
223 | /// A trait associated function (with no self parameter) or associated constant. | ||
224 | /// For 'test_mod::TestEnum::test_function', `Type` is the `test_mod::TestEnum` expression type | ||
225 | /// and `String` is the `test_function` | ||
226 | TraitAssocItem(Type, String), | ||
227 | /// A trait method with self parameter. | ||
228 | /// For 'test_enum.test_method()', `Type` is the `test_enum` expression type | ||
229 | /// and `String` is the `test_method` | ||
230 | TraitMethod(Type, String), | ||
231 | } | ||
232 | |||
233 | impl ImportCandidate { | ||
234 | fn for_method_call( | ||
235 | sema: &Semantics<RootDatabase>, | ||
236 | method_call: &ast::MethodCallExpr, | ||
237 | ) -> Option<Self> { | ||
238 | if sema.resolve_method_call(method_call).is_some() { | ||
239 | return None; | ||
240 | } | ||
241 | Some(Self::TraitMethod( | ||
242 | sema.type_of_expr(&method_call.expr()?)?, | ||
243 | method_call.name_ref()?.syntax().to_string(), | ||
244 | )) | ||
245 | } | ||
246 | |||
247 | fn for_regular_path( | ||
248 | sema: &Semantics<RootDatabase>, | ||
249 | path_under_caret: &ast::Path, | ||
250 | ) -> Option<Self> { | ||
251 | if sema.resolve_path(path_under_caret).is_some() { | ||
252 | return None; | ||
253 | } | ||
254 | |||
255 | let segment = path_under_caret.segment()?; | ||
256 | if let Some(qualifier) = path_under_caret.qualifier() { | ||
257 | let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?; | ||
258 | let qualifier_start_path = | ||
259 | qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?; | ||
260 | if let Some(qualifier_start_resolution) = sema.resolve_path(&qualifier_start_path) { | ||
261 | let qualifier_resolution = if qualifier_start_path == qualifier { | ||
262 | qualifier_start_resolution | ||
263 | } else { | ||
264 | sema.resolve_path(&qualifier)? | ||
265 | }; | ||
266 | if let PathResolution::Def(ModuleDef::Adt(assoc_item_path)) = qualifier_resolution { | ||
267 | Some(ImportCandidate::TraitAssocItem( | ||
268 | assoc_item_path.ty(sema.db), | ||
269 | segment.syntax().to_string(), | ||
270 | )) | ||
271 | } else { | ||
272 | None | ||
273 | } | ||
274 | } else { | ||
275 | Some(ImportCandidate::QualifierStart(qualifier_start.syntax().to_string())) | ||
276 | } | ||
277 | } else { | ||
278 | Some(ImportCandidate::UnqualifiedName( | ||
279 | segment.syntax().descendants().find_map(ast::NameRef::cast)?.syntax().to_string(), | ||
280 | )) | ||
281 | } | ||
282 | } | ||
283 | } | ||
284 | |||
285 | #[cfg(test)] | ||
286 | mod tests { | ||
287 | use super::*; | ||
288 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
289 | |||
290 | #[test] | ||
291 | fn applicable_when_found_an_import() { | ||
292 | check_assist( | ||
293 | auto_import, | ||
294 | r" | ||
295 | <|>PubStruct | ||
296 | |||
297 | pub mod PubMod { | ||
298 | pub struct PubStruct; | ||
299 | } | ||
300 | ", | ||
301 | r" | ||
302 | use PubMod::PubStruct; | ||
303 | |||
304 | PubStruct | ||
305 | |||
306 | pub mod PubMod { | ||
307 | pub struct PubStruct; | ||
308 | } | ||
309 | ", | ||
310 | ); | ||
311 | } | ||
312 | |||
313 | #[test] | ||
314 | fn applicable_when_found_an_import_in_macros() { | ||
315 | check_assist( | ||
316 | auto_import, | ||
317 | r" | ||
318 | macro_rules! foo { | ||
319 | ($i:ident) => { fn foo(a: $i) {} } | ||
320 | } | ||
321 | foo!(Pub<|>Struct); | ||
322 | |||
323 | pub mod PubMod { | ||
324 | pub struct PubStruct; | ||
325 | } | ||
326 | ", | ||
327 | r" | ||
328 | use PubMod::PubStruct; | ||
329 | |||
330 | macro_rules! foo { | ||
331 | ($i:ident) => { fn foo(a: $i) {} } | ||
332 | } | ||
333 | foo!(PubStruct); | ||
334 | |||
335 | pub mod PubMod { | ||
336 | pub struct PubStruct; | ||
337 | } | ||
338 | ", | ||
339 | ); | ||
340 | } | ||
341 | |||
342 | #[test] | ||
343 | fn auto_imports_are_merged() { | ||
344 | check_assist( | ||
345 | auto_import, | ||
346 | r" | ||
347 | use PubMod::PubStruct1; | ||
348 | |||
349 | struct Test { | ||
350 | test: Pub<|>Struct2<u8>, | ||
351 | } | ||
352 | |||
353 | pub mod PubMod { | ||
354 | pub struct PubStruct1; | ||
355 | pub struct PubStruct2<T> { | ||
356 | _t: T, | ||
357 | } | ||
358 | } | ||
359 | ", | ||
360 | r" | ||
361 | use PubMod::{PubStruct2, PubStruct1}; | ||
362 | |||
363 | struct Test { | ||
364 | test: PubStruct2<u8>, | ||
365 | } | ||
366 | |||
367 | pub mod PubMod { | ||
368 | pub struct PubStruct1; | ||
369 | pub struct PubStruct2<T> { | ||
370 | _t: T, | ||
371 | } | ||
372 | } | ||
373 | ", | ||
374 | ); | ||
375 | } | ||
376 | |||
377 | #[test] | ||
378 | fn applicable_when_found_multiple_imports() { | ||
379 | check_assist( | ||
380 | auto_import, | ||
381 | r" | ||
382 | PubSt<|>ruct | ||
383 | |||
384 | pub mod PubMod1 { | ||
385 | pub struct PubStruct; | ||
386 | } | ||
387 | pub mod PubMod2 { | ||
388 | pub struct PubStruct; | ||
389 | } | ||
390 | pub mod PubMod3 { | ||
391 | pub struct PubStruct; | ||
392 | } | ||
393 | ", | ||
394 | r" | ||
395 | use PubMod3::PubStruct; | ||
396 | |||
397 | PubStruct | ||
398 | |||
399 | pub mod PubMod1 { | ||
400 | pub struct PubStruct; | ||
401 | } | ||
402 | pub mod PubMod2 { | ||
403 | pub struct PubStruct; | ||
404 | } | ||
405 | pub mod PubMod3 { | ||
406 | pub struct PubStruct; | ||
407 | } | ||
408 | ", | ||
409 | ); | ||
410 | } | ||
411 | |||
412 | #[test] | ||
413 | fn not_applicable_for_already_imported_types() { | ||
414 | check_assist_not_applicable( | ||
415 | auto_import, | ||
416 | r" | ||
417 | use PubMod::PubStruct; | ||
418 | |||
419 | PubStruct<|> | ||
420 | |||
421 | pub mod PubMod { | ||
422 | pub struct PubStruct; | ||
423 | } | ||
424 | ", | ||
425 | ); | ||
426 | } | ||
427 | |||
428 | #[test] | ||
429 | fn not_applicable_for_types_with_private_paths() { | ||
430 | check_assist_not_applicable( | ||
431 | auto_import, | ||
432 | r" | ||
433 | PrivateStruct<|> | ||
434 | |||
435 | pub mod PubMod { | ||
436 | struct PrivateStruct; | ||
437 | } | ||
438 | ", | ||
439 | ); | ||
440 | } | ||
441 | |||
442 | #[test] | ||
443 | fn not_applicable_when_no_imports_found() { | ||
444 | check_assist_not_applicable( | ||
445 | auto_import, | ||
446 | " | ||
447 | PubStruct<|>", | ||
448 | ); | ||
449 | } | ||
450 | |||
451 | #[test] | ||
452 | fn not_applicable_in_import_statements() { | ||
453 | check_assist_not_applicable( | ||
454 | auto_import, | ||
455 | r" | ||
456 | use PubStruct<|>; | ||
457 | |||
458 | pub mod PubMod { | ||
459 | pub struct PubStruct; | ||
460 | }", | ||
461 | ); | ||
462 | } | ||
463 | |||
464 | #[test] | ||
465 | fn function_import() { | ||
466 | check_assist( | ||
467 | auto_import, | ||
468 | r" | ||
469 | test_function<|> | ||
470 | |||
471 | pub mod PubMod { | ||
472 | pub fn test_function() {}; | ||
473 | } | ||
474 | ", | ||
475 | r" | ||
476 | use PubMod::test_function; | ||
477 | |||
478 | test_function | ||
479 | |||
480 | pub mod PubMod { | ||
481 | pub fn test_function() {}; | ||
482 | } | ||
483 | ", | ||
484 | ); | ||
485 | } | ||
486 | |||
487 | #[test] | ||
488 | fn macro_import() { | ||
489 | check_assist( | ||
490 | auto_import, | ||
491 | r" | ||
492 | //- /lib.rs crate:crate_with_macro | ||
493 | #[macro_export] | ||
494 | macro_rules! foo { | ||
495 | () => () | ||
496 | } | ||
497 | |||
498 | //- /main.rs crate:main deps:crate_with_macro | ||
499 | fn main() { | ||
500 | foo<|> | ||
501 | } | ||
502 | ", | ||
503 | r"use crate_with_macro::foo; | ||
504 | |||
505 | fn main() { | ||
506 | foo | ||
507 | } | ||
508 | ", | ||
509 | ); | ||
510 | } | ||
511 | |||
512 | #[test] | ||
513 | fn auto_import_target() { | ||
514 | check_assist_target( | ||
515 | auto_import, | ||
516 | r" | ||
517 | struct AssistInfo { | ||
518 | group_label: Option<<|>GroupLabel>, | ||
519 | } | ||
520 | |||
521 | mod m { pub struct GroupLabel; } | ||
522 | ", | ||
523 | "GroupLabel", | ||
524 | ) | ||
525 | } | ||
526 | |||
527 | #[test] | ||
528 | fn not_applicable_when_path_start_is_imported() { | ||
529 | check_assist_not_applicable( | ||
530 | auto_import, | ||
531 | r" | ||
532 | pub mod mod1 { | ||
533 | pub mod mod2 { | ||
534 | pub mod mod3 { | ||
535 | pub struct TestStruct; | ||
536 | } | ||
537 | } | ||
538 | } | ||
539 | |||
540 | use mod1::mod2; | ||
541 | fn main() { | ||
542 | mod2::mod3::TestStruct<|> | ||
543 | } | ||
544 | ", | ||
545 | ); | ||
546 | } | ||
547 | |||
548 | #[test] | ||
549 | fn not_applicable_for_imported_function() { | ||
550 | check_assist_not_applicable( | ||
551 | auto_import, | ||
552 | r" | ||
553 | pub mod test_mod { | ||
554 | pub fn test_function() {} | ||
555 | } | ||
556 | |||
557 | use test_mod::test_function; | ||
558 | fn main() { | ||
559 | test_function<|> | ||
560 | } | ||
561 | ", | ||
562 | ); | ||
563 | } | ||
564 | |||
565 | #[test] | ||
566 | fn associated_struct_function() { | ||
567 | check_assist( | ||
568 | auto_import, | ||
569 | r" | ||
570 | mod test_mod { | ||
571 | pub struct TestStruct {} | ||
572 | impl TestStruct { | ||
573 | pub fn test_function() {} | ||
574 | } | ||
575 | } | ||
576 | |||
577 | fn main() { | ||
578 | TestStruct::test_function<|> | ||
579 | } | ||
580 | ", | ||
581 | r" | ||
582 | use test_mod::TestStruct; | ||
583 | |||
584 | mod test_mod { | ||
585 | pub struct TestStruct {} | ||
586 | impl TestStruct { | ||
587 | pub fn test_function() {} | ||
588 | } | ||
589 | } | ||
590 | |||
591 | fn main() { | ||
592 | TestStruct::test_function | ||
593 | } | ||
594 | ", | ||
595 | ); | ||
596 | } | ||
597 | |||
598 | #[test] | ||
599 | fn associated_struct_const() { | ||
600 | check_assist( | ||
601 | auto_import, | ||
602 | r" | ||
603 | mod test_mod { | ||
604 | pub struct TestStruct {} | ||
605 | impl TestStruct { | ||
606 | const TEST_CONST: u8 = 42; | ||
607 | } | ||
608 | } | ||
609 | |||
610 | fn main() { | ||
611 | TestStruct::TEST_CONST<|> | ||
612 | } | ||
613 | ", | ||
614 | r" | ||
615 | use test_mod::TestStruct; | ||
616 | |||
617 | mod test_mod { | ||
618 | pub struct TestStruct {} | ||
619 | impl TestStruct { | ||
620 | const TEST_CONST: u8 = 42; | ||
621 | } | ||
622 | } | ||
623 | |||
624 | fn main() { | ||
625 | TestStruct::TEST_CONST | ||
626 | } | ||
627 | ", | ||
628 | ); | ||
629 | } | ||
630 | |||
631 | #[test] | ||
632 | fn associated_trait_function() { | ||
633 | check_assist( | ||
634 | auto_import, | ||
635 | r" | ||
636 | mod test_mod { | ||
637 | pub trait TestTrait { | ||
638 | fn test_function(); | ||
639 | } | ||
640 | pub struct TestStruct {} | ||
641 | impl TestTrait for TestStruct { | ||
642 | fn test_function() {} | ||
643 | } | ||
644 | } | ||
645 | |||
646 | fn main() { | ||
647 | test_mod::TestStruct::test_function<|> | ||
648 | } | ||
649 | ", | ||
650 | r" | ||
651 | use test_mod::TestTrait; | ||
652 | |||
653 | mod test_mod { | ||
654 | pub trait TestTrait { | ||
655 | fn test_function(); | ||
656 | } | ||
657 | pub struct TestStruct {} | ||
658 | impl TestTrait for TestStruct { | ||
659 | fn test_function() {} | ||
660 | } | ||
661 | } | ||
662 | |||
663 | fn main() { | ||
664 | test_mod::TestStruct::test_function | ||
665 | } | ||
666 | ", | ||
667 | ); | ||
668 | } | ||
669 | |||
670 | #[test] | ||
671 | fn not_applicable_for_imported_trait_for_function() { | ||
672 | check_assist_not_applicable( | ||
673 | auto_import, | ||
674 | r" | ||
675 | mod test_mod { | ||
676 | pub trait TestTrait { | ||
677 | fn test_function(); | ||
678 | } | ||
679 | pub trait TestTrait2 { | ||
680 | fn test_function(); | ||
681 | } | ||
682 | pub enum TestEnum { | ||
683 | One, | ||
684 | Two, | ||
685 | } | ||
686 | impl TestTrait2 for TestEnum { | ||
687 | fn test_function() {} | ||
688 | } | ||
689 | impl TestTrait for TestEnum { | ||
690 | fn test_function() {} | ||
691 | } | ||
692 | } | ||
693 | |||
694 | use test_mod::TestTrait2; | ||
695 | fn main() { | ||
696 | test_mod::TestEnum::test_function<|>; | ||
697 | } | ||
698 | ", | ||
699 | ) | ||
700 | } | ||
701 | |||
702 | #[test] | ||
703 | fn associated_trait_const() { | ||
704 | check_assist( | ||
705 | auto_import, | ||
706 | r" | ||
707 | mod test_mod { | ||
708 | pub trait TestTrait { | ||
709 | const TEST_CONST: u8; | ||
710 | } | ||
711 | pub struct TestStruct {} | ||
712 | impl TestTrait for TestStruct { | ||
713 | const TEST_CONST: u8 = 42; | ||
714 | } | ||
715 | } | ||
716 | |||
717 | fn main() { | ||
718 | test_mod::TestStruct::TEST_CONST<|> | ||
719 | } | ||
720 | ", | ||
721 | r" | ||
722 | use test_mod::TestTrait; | ||
723 | |||
724 | mod test_mod { | ||
725 | pub trait TestTrait { | ||
726 | const TEST_CONST: u8; | ||
727 | } | ||
728 | pub struct TestStruct {} | ||
729 | impl TestTrait for TestStruct { | ||
730 | const TEST_CONST: u8 = 42; | ||
731 | } | ||
732 | } | ||
733 | |||
734 | fn main() { | ||
735 | test_mod::TestStruct::TEST_CONST | ||
736 | } | ||
737 | ", | ||
738 | ); | ||
739 | } | ||
740 | |||
741 | #[test] | ||
742 | fn not_applicable_for_imported_trait_for_const() { | ||
743 | check_assist_not_applicable( | ||
744 | auto_import, | ||
745 | r" | ||
746 | mod test_mod { | ||
747 | pub trait TestTrait { | ||
748 | const TEST_CONST: u8; | ||
749 | } | ||
750 | pub trait TestTrait2 { | ||
751 | const TEST_CONST: f64; | ||
752 | } | ||
753 | pub enum TestEnum { | ||
754 | One, | ||
755 | Two, | ||
756 | } | ||
757 | impl TestTrait2 for TestEnum { | ||
758 | const TEST_CONST: f64 = 42.0; | ||
759 | } | ||
760 | impl TestTrait for TestEnum { | ||
761 | const TEST_CONST: u8 = 42; | ||
762 | } | ||
763 | } | ||
764 | |||
765 | use test_mod::TestTrait2; | ||
766 | fn main() { | ||
767 | test_mod::TestEnum::TEST_CONST<|>; | ||
768 | } | ||
769 | ", | ||
770 | ) | ||
771 | } | ||
772 | |||
773 | #[test] | ||
774 | fn trait_method() { | ||
775 | check_assist( | ||
776 | auto_import, | ||
777 | r" | ||
778 | mod test_mod { | ||
779 | pub trait TestTrait { | ||
780 | fn test_method(&self); | ||
781 | } | ||
782 | pub struct TestStruct {} | ||
783 | impl TestTrait for TestStruct { | ||
784 | fn test_method(&self) {} | ||
785 | } | ||
786 | } | ||
787 | |||
788 | fn main() { | ||
789 | let test_struct = test_mod::TestStruct {}; | ||
790 | test_struct.test_meth<|>od() | ||
791 | } | ||
792 | ", | ||
793 | r" | ||
794 | use test_mod::TestTrait; | ||
795 | |||
796 | mod test_mod { | ||
797 | pub trait TestTrait { | ||
798 | fn test_method(&self); | ||
799 | } | ||
800 | pub struct TestStruct {} | ||
801 | impl TestTrait for TestStruct { | ||
802 | fn test_method(&self) {} | ||
803 | } | ||
804 | } | ||
805 | |||
806 | fn main() { | ||
807 | let test_struct = test_mod::TestStruct {}; | ||
808 | test_struct.test_method() | ||
809 | } | ||
810 | ", | ||
811 | ); | ||
812 | } | ||
813 | |||
814 | #[test] | ||
815 | fn trait_method_cross_crate() { | ||
816 | check_assist( | ||
817 | auto_import, | ||
818 | r" | ||
819 | //- /main.rs crate:main deps:dep | ||
820 | fn main() { | ||
821 | let test_struct = dep::test_mod::TestStruct {}; | ||
822 | test_struct.test_meth<|>od() | ||
823 | } | ||
824 | //- /dep.rs crate:dep | ||
825 | pub mod test_mod { | ||
826 | pub trait TestTrait { | ||
827 | fn test_method(&self); | ||
828 | } | ||
829 | pub struct TestStruct {} | ||
830 | impl TestTrait for TestStruct { | ||
831 | fn test_method(&self) {} | ||
832 | } | ||
833 | } | ||
834 | ", | ||
835 | r" | ||
836 | use dep::test_mod::TestTrait; | ||
837 | |||
838 | fn main() { | ||
839 | let test_struct = dep::test_mod::TestStruct {}; | ||
840 | test_struct.test_method() | ||
841 | } | ||
842 | ", | ||
843 | ); | ||
844 | } | ||
845 | |||
846 | #[test] | ||
847 | fn assoc_fn_cross_crate() { | ||
848 | check_assist( | ||
849 | auto_import, | ||
850 | r" | ||
851 | //- /main.rs crate:main deps:dep | ||
852 | fn main() { | ||
853 | dep::test_mod::TestStruct::test_func<|>tion | ||
854 | } | ||
855 | //- /dep.rs crate:dep | ||
856 | pub mod test_mod { | ||
857 | pub trait TestTrait { | ||
858 | fn test_function(); | ||
859 | } | ||
860 | pub struct TestStruct {} | ||
861 | impl TestTrait for TestStruct { | ||
862 | fn test_function() {} | ||
863 | } | ||
864 | } | ||
865 | ", | ||
866 | r" | ||
867 | use dep::test_mod::TestTrait; | ||
868 | |||
869 | fn main() { | ||
870 | dep::test_mod::TestStruct::test_function | ||
871 | } | ||
872 | ", | ||
873 | ); | ||
874 | } | ||
875 | |||
876 | #[test] | ||
877 | fn assoc_const_cross_crate() { | ||
878 | check_assist( | ||
879 | auto_import, | ||
880 | r" | ||
881 | //- /main.rs crate:main deps:dep | ||
882 | fn main() { | ||
883 | dep::test_mod::TestStruct::CONST<|> | ||
884 | } | ||
885 | //- /dep.rs crate:dep | ||
886 | pub mod test_mod { | ||
887 | pub trait TestTrait { | ||
888 | const CONST: bool; | ||
889 | } | ||
890 | pub struct TestStruct {} | ||
891 | impl TestTrait for TestStruct { | ||
892 | const CONST: bool = true; | ||
893 | } | ||
894 | } | ||
895 | ", | ||
896 | r" | ||
897 | use dep::test_mod::TestTrait; | ||
898 | |||
899 | fn main() { | ||
900 | dep::test_mod::TestStruct::CONST | ||
901 | } | ||
902 | ", | ||
903 | ); | ||
904 | } | ||
905 | |||
906 | #[test] | ||
907 | fn assoc_fn_as_method_cross_crate() { | ||
908 | check_assist_not_applicable( | ||
909 | auto_import, | ||
910 | r" | ||
911 | //- /main.rs crate:main deps:dep | ||
912 | fn main() { | ||
913 | let test_struct = dep::test_mod::TestStruct {}; | ||
914 | test_struct.test_func<|>tion() | ||
915 | } | ||
916 | //- /dep.rs crate:dep | ||
917 | pub mod test_mod { | ||
918 | pub trait TestTrait { | ||
919 | fn test_function(); | ||
920 | } | ||
921 | pub struct TestStruct {} | ||
922 | impl TestTrait for TestStruct { | ||
923 | fn test_function() {} | ||
924 | } | ||
925 | } | ||
926 | ", | ||
927 | ); | ||
928 | } | ||
929 | |||
930 | #[test] | ||
931 | fn private_trait_cross_crate() { | ||
932 | check_assist_not_applicable( | ||
933 | auto_import, | ||
934 | r" | ||
935 | //- /main.rs crate:main deps:dep | ||
936 | fn main() { | ||
937 | let test_struct = dep::test_mod::TestStruct {}; | ||
938 | test_struct.test_meth<|>od() | ||
939 | } | ||
940 | //- /dep.rs crate:dep | ||
941 | pub mod test_mod { | ||
942 | trait TestTrait { | ||
943 | fn test_method(&self); | ||
944 | } | ||
945 | pub struct TestStruct {} | ||
946 | impl TestTrait for TestStruct { | ||
947 | fn test_method(&self) {} | ||
948 | } | ||
949 | } | ||
950 | ", | ||
951 | ); | ||
952 | } | ||
953 | |||
954 | #[test] | ||
955 | fn not_applicable_for_imported_trait_for_method() { | ||
956 | check_assist_not_applicable( | ||
957 | auto_import, | ||
958 | r" | ||
959 | mod test_mod { | ||
960 | pub trait TestTrait { | ||
961 | fn test_method(&self); | ||
962 | } | ||
963 | pub trait TestTrait2 { | ||
964 | fn test_method(&self); | ||
965 | } | ||
966 | pub enum TestEnum { | ||
967 | One, | ||
968 | Two, | ||
969 | } | ||
970 | impl TestTrait2 for TestEnum { | ||
971 | fn test_method(&self) {} | ||
972 | } | ||
973 | impl TestTrait for TestEnum { | ||
974 | fn test_method(&self) {} | ||
975 | } | ||
976 | } | ||
977 | |||
978 | use test_mod::TestTrait2; | ||
979 | fn main() { | ||
980 | let one = test_mod::TestEnum::One; | ||
981 | one.test<|>_method(); | ||
982 | } | ||
983 | ", | ||
984 | ) | ||
985 | } | ||
986 | |||
987 | #[test] | ||
988 | fn dep_import() { | ||
989 | check_assist( | ||
990 | auto_import, | ||
991 | r" | ||
992 | //- /lib.rs crate:dep | ||
993 | pub struct Struct; | ||
994 | |||
995 | //- /main.rs crate:main deps:dep | ||
996 | fn main() { | ||
997 | Struct<|> | ||
998 | } | ||
999 | ", | ||
1000 | r"use dep::Struct; | ||
1001 | |||
1002 | fn main() { | ||
1003 | Struct | ||
1004 | } | ||
1005 | ", | ||
1006 | ); | ||
1007 | } | ||
1008 | |||
1009 | #[test] | ||
1010 | fn whole_segment() { | ||
1011 | // Tests that only imports whose last segment matches the identifier get suggested. | ||
1012 | check_assist( | ||
1013 | auto_import, | ||
1014 | r" | ||
1015 | //- /lib.rs crate:dep | ||
1016 | pub mod fmt { | ||
1017 | pub trait Display {} | ||
1018 | } | ||
1019 | |||
1020 | pub fn panic_fmt() {} | ||
1021 | |||
1022 | //- /main.rs crate:main deps:dep | ||
1023 | struct S; | ||
1024 | |||
1025 | impl f<|>mt::Display for S {} | ||
1026 | ", | ||
1027 | r"use dep::fmt; | ||
1028 | |||
1029 | struct S; | ||
1030 | |||
1031 | impl fmt::Display for S {} | ||
1032 | ", | ||
1033 | ); | ||
1034 | } | ||
1035 | |||
1036 | #[test] | ||
1037 | fn macro_generated() { | ||
1038 | // Tests that macro-generated items are suggested from external crates. | ||
1039 | check_assist( | ||
1040 | auto_import, | ||
1041 | r" | ||
1042 | //- /lib.rs crate:dep | ||
1043 | macro_rules! mac { | ||
1044 | () => { | ||
1045 | pub struct Cheese; | ||
1046 | }; | ||
1047 | } | ||
1048 | |||
1049 | mac!(); | ||
1050 | |||
1051 | //- /main.rs crate:main deps:dep | ||
1052 | fn main() { | ||
1053 | Cheese<|>; | ||
1054 | } | ||
1055 | ", | ||
1056 | r"use dep::Cheese; | ||
1057 | |||
1058 | fn main() { | ||
1059 | Cheese; | ||
1060 | } | ||
1061 | ", | ||
1062 | ); | ||
1063 | } | ||
1064 | |||
1065 | #[test] | ||
1066 | fn casing() { | ||
1067 | // Tests that differently cased names don't interfere and we only suggest the matching one. | ||
1068 | check_assist( | ||
1069 | auto_import, | ||
1070 | r" | ||
1071 | //- /lib.rs crate:dep | ||
1072 | pub struct FMT; | ||
1073 | pub struct fmt; | ||
1074 | |||
1075 | //- /main.rs crate:main deps:dep | ||
1076 | fn main() { | ||
1077 | FMT<|>; | ||
1078 | } | ||
1079 | ", | ||
1080 | r"use dep::FMT; | ||
1081 | |||
1082 | fn main() { | ||
1083 | FMT; | ||
1084 | } | ||
1085 | ", | ||
1086 | ); | ||
1087 | } | ||
1088 | } | ||
diff --git a/crates/assists/src/handlers/change_return_type_to_result.rs b/crates/assists/src/handlers/change_return_type_to_result.rs new file mode 100644 index 000000000..be480943c --- /dev/null +++ b/crates/assists/src/handlers/change_return_type_to_result.rs | |||
@@ -0,0 +1,998 @@ | |||
1 | use std::iter; | ||
2 | |||
3 | use syntax::{ | ||
4 | ast::{self, make, BlockExpr, Expr, LoopBodyOwner}, | ||
5 | AstNode, SyntaxNode, | ||
6 | }; | ||
7 | use test_utils::mark; | ||
8 | |||
9 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
10 | |||
11 | // Assist: change_return_type_to_result | ||
12 | // | ||
13 | // Change the function's return type to Result. | ||
14 | // | ||
15 | // ``` | ||
16 | // fn foo() -> i32<|> { 42i32 } | ||
17 | // ``` | ||
18 | // -> | ||
19 | // ``` | ||
20 | // fn foo() -> Result<i32, ${0:_}> { Ok(42i32) } | ||
21 | // ``` | ||
22 | pub(crate) fn change_return_type_to_result(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
23 | let ret_type = ctx.find_node_at_offset::<ast::RetType>()?; | ||
24 | // FIXME: extend to lambdas as well | ||
25 | let fn_def = ret_type.syntax().parent().and_then(ast::Fn::cast)?; | ||
26 | |||
27 | let type_ref = &ret_type.ty()?; | ||
28 | let ret_type_str = type_ref.syntax().text().to_string(); | ||
29 | let first_part_ret_type = ret_type_str.splitn(2, '<').next(); | ||
30 | if let Some(ret_type_first_part) = first_part_ret_type { | ||
31 | if ret_type_first_part.ends_with("Result") { | ||
32 | mark::hit!(change_return_type_to_result_simple_return_type_already_result); | ||
33 | return None; | ||
34 | } | ||
35 | } | ||
36 | |||
37 | let block_expr = &fn_def.body()?; | ||
38 | |||
39 | acc.add( | ||
40 | AssistId("change_return_type_to_result", AssistKind::RefactorRewrite), | ||
41 | "Wrap return type in Result", | ||
42 | type_ref.syntax().text_range(), | ||
43 | |builder| { | ||
44 | let mut tail_return_expr_collector = TailReturnCollector::new(); | ||
45 | tail_return_expr_collector.collect_jump_exprs(block_expr, false); | ||
46 | tail_return_expr_collector.collect_tail_exprs(block_expr); | ||
47 | |||
48 | for ret_expr_arg in tail_return_expr_collector.exprs_to_wrap { | ||
49 | let ok_wrapped = make::expr_call( | ||
50 | make::expr_path(make::path_unqualified(make::path_segment(make::name_ref( | ||
51 | "Ok", | ||
52 | )))), | ||
53 | make::arg_list(iter::once(ret_expr_arg.clone())), | ||
54 | ); | ||
55 | builder.replace_ast(ret_expr_arg, ok_wrapped); | ||
56 | } | ||
57 | |||
58 | match ctx.config.snippet_cap { | ||
59 | Some(cap) => { | ||
60 | let snippet = format!("Result<{}, ${{0:_}}>", type_ref); | ||
61 | builder.replace_snippet(cap, type_ref.syntax().text_range(), snippet) | ||
62 | } | ||
63 | None => builder | ||
64 | .replace(type_ref.syntax().text_range(), format!("Result<{}, _>", type_ref)), | ||
65 | } | ||
66 | }, | ||
67 | ) | ||
68 | } | ||
69 | |||
70 | struct TailReturnCollector { | ||
71 | exprs_to_wrap: Vec<ast::Expr>, | ||
72 | } | ||
73 | |||
74 | impl TailReturnCollector { | ||
75 | fn new() -> Self { | ||
76 | Self { exprs_to_wrap: vec![] } | ||
77 | } | ||
78 | /// Collect all`return` expression | ||
79 | fn collect_jump_exprs(&mut self, block_expr: &BlockExpr, collect_break: bool) { | ||
80 | let statements = block_expr.statements(); | ||
81 | for stmt in statements { | ||
82 | let expr = match &stmt { | ||
83 | ast::Stmt::ExprStmt(stmt) => stmt.expr(), | ||
84 | ast::Stmt::LetStmt(stmt) => stmt.initializer(), | ||
85 | ast::Stmt::Item(_) => continue, | ||
86 | }; | ||
87 | if let Some(expr) = &expr { | ||
88 | self.handle_exprs(expr, collect_break); | ||
89 | } | ||
90 | } | ||
91 | |||
92 | // Browse tail expressions for each block | ||
93 | if let Some(expr) = block_expr.expr() { | ||
94 | if let Some(last_exprs) = get_tail_expr_from_block(&expr) { | ||
95 | for last_expr in last_exprs { | ||
96 | let last_expr = match last_expr { | ||
97 | NodeType::Node(expr) => expr, | ||
98 | NodeType::Leaf(expr) => expr.syntax().clone(), | ||
99 | }; | ||
100 | |||
101 | if let Some(last_expr) = Expr::cast(last_expr.clone()) { | ||
102 | self.handle_exprs(&last_expr, collect_break); | ||
103 | } else if let Some(expr_stmt) = ast::Stmt::cast(last_expr) { | ||
104 | let expr_stmt = match &expr_stmt { | ||
105 | ast::Stmt::ExprStmt(stmt) => stmt.expr(), | ||
106 | ast::Stmt::LetStmt(stmt) => stmt.initializer(), | ||
107 | ast::Stmt::Item(_) => None, | ||
108 | }; | ||
109 | if let Some(expr) = &expr_stmt { | ||
110 | self.handle_exprs(expr, collect_break); | ||
111 | } | ||
112 | } | ||
113 | } | ||
114 | } | ||
115 | } | ||
116 | } | ||
117 | |||
118 | fn handle_exprs(&mut self, expr: &Expr, collect_break: bool) { | ||
119 | match expr { | ||
120 | Expr::BlockExpr(block_expr) => { | ||
121 | self.collect_jump_exprs(&block_expr, collect_break); | ||
122 | } | ||
123 | Expr::ReturnExpr(ret_expr) => { | ||
124 | if let Some(ret_expr_arg) = &ret_expr.expr() { | ||
125 | self.exprs_to_wrap.push(ret_expr_arg.clone()); | ||
126 | } | ||
127 | } | ||
128 | Expr::BreakExpr(break_expr) if collect_break => { | ||
129 | if let Some(break_expr_arg) = &break_expr.expr() { | ||
130 | self.exprs_to_wrap.push(break_expr_arg.clone()); | ||
131 | } | ||
132 | } | ||
133 | Expr::IfExpr(if_expr) => { | ||
134 | for block in if_expr.blocks() { | ||
135 | self.collect_jump_exprs(&block, collect_break); | ||
136 | } | ||
137 | } | ||
138 | Expr::LoopExpr(loop_expr) => { | ||
139 | if let Some(block_expr) = loop_expr.loop_body() { | ||
140 | self.collect_jump_exprs(&block_expr, collect_break); | ||
141 | } | ||
142 | } | ||
143 | Expr::ForExpr(for_expr) => { | ||
144 | if let Some(block_expr) = for_expr.loop_body() { | ||
145 | self.collect_jump_exprs(&block_expr, collect_break); | ||
146 | } | ||
147 | } | ||
148 | Expr::WhileExpr(while_expr) => { | ||
149 | if let Some(block_expr) = while_expr.loop_body() { | ||
150 | self.collect_jump_exprs(&block_expr, collect_break); | ||
151 | } | ||
152 | } | ||
153 | Expr::MatchExpr(match_expr) => { | ||
154 | if let Some(arm_list) = match_expr.match_arm_list() { | ||
155 | arm_list.arms().filter_map(|match_arm| match_arm.expr()).for_each(|expr| { | ||
156 | self.handle_exprs(&expr, collect_break); | ||
157 | }); | ||
158 | } | ||
159 | } | ||
160 | _ => {} | ||
161 | } | ||
162 | } | ||
163 | |||
164 | fn collect_tail_exprs(&mut self, block: &BlockExpr) { | ||
165 | if let Some(expr) = block.expr() { | ||
166 | self.handle_exprs(&expr, true); | ||
167 | self.fetch_tail_exprs(&expr); | ||
168 | } | ||
169 | } | ||
170 | |||
171 | fn fetch_tail_exprs(&mut self, expr: &Expr) { | ||
172 | if let Some(exprs) = get_tail_expr_from_block(expr) { | ||
173 | for node_type in &exprs { | ||
174 | match node_type { | ||
175 | NodeType::Leaf(expr) => { | ||
176 | self.exprs_to_wrap.push(expr.clone()); | ||
177 | } | ||
178 | NodeType::Node(expr) => { | ||
179 | if let Some(last_expr) = Expr::cast(expr.clone()) { | ||
180 | self.fetch_tail_exprs(&last_expr); | ||
181 | } | ||
182 | } | ||
183 | } | ||
184 | } | ||
185 | } | ||
186 | } | ||
187 | } | ||
188 | |||
189 | #[derive(Debug)] | ||
190 | enum NodeType { | ||
191 | Leaf(ast::Expr), | ||
192 | Node(SyntaxNode), | ||
193 | } | ||
194 | |||
195 | /// Get a tail expression inside a block | ||
196 | fn get_tail_expr_from_block(expr: &Expr) -> Option<Vec<NodeType>> { | ||
197 | match expr { | ||
198 | Expr::IfExpr(if_expr) => { | ||
199 | let mut nodes = vec![]; | ||
200 | for block in if_expr.blocks() { | ||
201 | if let Some(block_expr) = block.expr() { | ||
202 | if let Some(tail_exprs) = get_tail_expr_from_block(&block_expr) { | ||
203 | nodes.extend(tail_exprs); | ||
204 | } | ||
205 | } else if let Some(last_expr) = block.syntax().last_child() { | ||
206 | nodes.push(NodeType::Node(last_expr)); | ||
207 | } else { | ||
208 | nodes.push(NodeType::Node(block.syntax().clone())); | ||
209 | } | ||
210 | } | ||
211 | Some(nodes) | ||
212 | } | ||
213 | Expr::LoopExpr(loop_expr) => { | ||
214 | loop_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) | ||
215 | } | ||
216 | Expr::ForExpr(for_expr) => { | ||
217 | for_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) | ||
218 | } | ||
219 | Expr::WhileExpr(while_expr) => { | ||
220 | while_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)]) | ||
221 | } | ||
222 | Expr::BlockExpr(block_expr) => { | ||
223 | block_expr.expr().map(|lc| vec![NodeType::Node(lc.syntax().clone())]) | ||
224 | } | ||
225 | Expr::MatchExpr(match_expr) => { | ||
226 | let arm_list = match_expr.match_arm_list()?; | ||
227 | let arms: Vec<NodeType> = arm_list | ||
228 | .arms() | ||
229 | .filter_map(|match_arm| match_arm.expr()) | ||
230 | .map(|expr| match expr { | ||
231 | Expr::ReturnExpr(ret_expr) => NodeType::Node(ret_expr.syntax().clone()), | ||
232 | Expr::BreakExpr(break_expr) => NodeType::Node(break_expr.syntax().clone()), | ||
233 | _ => match expr.syntax().last_child() { | ||
234 | Some(last_expr) => NodeType::Node(last_expr), | ||
235 | None => NodeType::Node(expr.syntax().clone()), | ||
236 | }, | ||
237 | }) | ||
238 | .collect(); | ||
239 | |||
240 | Some(arms) | ||
241 | } | ||
242 | Expr::BreakExpr(expr) => expr.expr().map(|e| vec![NodeType::Leaf(e)]), | ||
243 | Expr::ReturnExpr(ret_expr) => Some(vec![NodeType::Node(ret_expr.syntax().clone())]), | ||
244 | |||
245 | Expr::CallExpr(_) | ||
246 | | Expr::Literal(_) | ||
247 | | Expr::TupleExpr(_) | ||
248 | | Expr::ArrayExpr(_) | ||
249 | | Expr::ParenExpr(_) | ||
250 | | Expr::PathExpr(_) | ||
251 | | Expr::RecordExpr(_) | ||
252 | | Expr::IndexExpr(_) | ||
253 | | Expr::MethodCallExpr(_) | ||
254 | | Expr::AwaitExpr(_) | ||
255 | | Expr::CastExpr(_) | ||
256 | | Expr::RefExpr(_) | ||
257 | | Expr::PrefixExpr(_) | ||
258 | | Expr::RangeExpr(_) | ||
259 | | Expr::BinExpr(_) | ||
260 | | Expr::MacroCall(_) | ||
261 | | Expr::BoxExpr(_) => Some(vec![NodeType::Leaf(expr.clone())]), | ||
262 | _ => None, | ||
263 | } | ||
264 | } | ||
265 | |||
266 | #[cfg(test)] | ||
267 | mod tests { | ||
268 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
269 | |||
270 | use super::*; | ||
271 | |||
272 | #[test] | ||
273 | fn change_return_type_to_result_simple() { | ||
274 | check_assist( | ||
275 | change_return_type_to_result, | ||
276 | r#"fn foo() -> i3<|>2 { | ||
277 | let test = "test"; | ||
278 | return 42i32; | ||
279 | }"#, | ||
280 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
281 | let test = "test"; | ||
282 | return Ok(42i32); | ||
283 | }"#, | ||
284 | ); | ||
285 | } | ||
286 | |||
287 | #[test] | ||
288 | fn change_return_type_to_result_simple_return_type() { | ||
289 | check_assist( | ||
290 | change_return_type_to_result, | ||
291 | r#"fn foo() -> i32<|> { | ||
292 | let test = "test"; | ||
293 | return 42i32; | ||
294 | }"#, | ||
295 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
296 | let test = "test"; | ||
297 | return Ok(42i32); | ||
298 | }"#, | ||
299 | ); | ||
300 | } | ||
301 | |||
302 | #[test] | ||
303 | fn change_return_type_to_result_simple_return_type_bad_cursor() { | ||
304 | check_assist_not_applicable( | ||
305 | change_return_type_to_result, | ||
306 | r#"fn foo() -> i32 { | ||
307 | let test = "test";<|> | ||
308 | return 42i32; | ||
309 | }"#, | ||
310 | ); | ||
311 | } | ||
312 | |||
313 | #[test] | ||
314 | fn change_return_type_to_result_simple_return_type_already_result_std() { | ||
315 | check_assist_not_applicable( | ||
316 | change_return_type_to_result, | ||
317 | r#"fn foo() -> std::result::Result<i32<|>, String> { | ||
318 | let test = "test"; | ||
319 | return 42i32; | ||
320 | }"#, | ||
321 | ); | ||
322 | } | ||
323 | |||
324 | #[test] | ||
325 | fn change_return_type_to_result_simple_return_type_already_result() { | ||
326 | mark::check!(change_return_type_to_result_simple_return_type_already_result); | ||
327 | check_assist_not_applicable( | ||
328 | change_return_type_to_result, | ||
329 | r#"fn foo() -> Result<i32<|>, String> { | ||
330 | let test = "test"; | ||
331 | return 42i32; | ||
332 | }"#, | ||
333 | ); | ||
334 | } | ||
335 | |||
336 | #[test] | ||
337 | fn change_return_type_to_result_simple_with_cursor() { | ||
338 | check_assist( | ||
339 | change_return_type_to_result, | ||
340 | r#"fn foo() -> <|>i32 { | ||
341 | let test = "test"; | ||
342 | return 42i32; | ||
343 | }"#, | ||
344 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
345 | let test = "test"; | ||
346 | return Ok(42i32); | ||
347 | }"#, | ||
348 | ); | ||
349 | } | ||
350 | |||
351 | #[test] | ||
352 | fn change_return_type_to_result_simple_with_tail() { | ||
353 | check_assist( | ||
354 | change_return_type_to_result, | ||
355 | r#"fn foo() -><|> i32 { | ||
356 | let test = "test"; | ||
357 | 42i32 | ||
358 | }"#, | ||
359 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
360 | let test = "test"; | ||
361 | Ok(42i32) | ||
362 | }"#, | ||
363 | ); | ||
364 | } | ||
365 | |||
366 | #[test] | ||
367 | fn change_return_type_to_result_simple_with_tail_only() { | ||
368 | check_assist( | ||
369 | change_return_type_to_result, | ||
370 | r#"fn foo() -> i32<|> { | ||
371 | 42i32 | ||
372 | }"#, | ||
373 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
374 | Ok(42i32) | ||
375 | }"#, | ||
376 | ); | ||
377 | } | ||
378 | #[test] | ||
379 | fn change_return_type_to_result_simple_with_tail_block_like() { | ||
380 | check_assist( | ||
381 | change_return_type_to_result, | ||
382 | r#"fn foo() -> i32<|> { | ||
383 | if true { | ||
384 | 42i32 | ||
385 | } else { | ||
386 | 24i32 | ||
387 | } | ||
388 | }"#, | ||
389 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
390 | if true { | ||
391 | Ok(42i32) | ||
392 | } else { | ||
393 | Ok(24i32) | ||
394 | } | ||
395 | }"#, | ||
396 | ); | ||
397 | } | ||
398 | |||
399 | #[test] | ||
400 | fn change_return_type_to_result_simple_with_nested_if() { | ||
401 | check_assist( | ||
402 | change_return_type_to_result, | ||
403 | r#"fn foo() -> i32<|> { | ||
404 | if true { | ||
405 | if false { | ||
406 | 1 | ||
407 | } else { | ||
408 | 2 | ||
409 | } | ||
410 | } else { | ||
411 | 24i32 | ||
412 | } | ||
413 | }"#, | ||
414 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
415 | if true { | ||
416 | if false { | ||
417 | Ok(1) | ||
418 | } else { | ||
419 | Ok(2) | ||
420 | } | ||
421 | } else { | ||
422 | Ok(24i32) | ||
423 | } | ||
424 | }"#, | ||
425 | ); | ||
426 | } | ||
427 | |||
428 | #[test] | ||
429 | fn change_return_type_to_result_simple_with_await() { | ||
430 | check_assist( | ||
431 | change_return_type_to_result, | ||
432 | r#"async fn foo() -> i<|>32 { | ||
433 | if true { | ||
434 | if false { | ||
435 | 1.await | ||
436 | } else { | ||
437 | 2.await | ||
438 | } | ||
439 | } else { | ||
440 | 24i32.await | ||
441 | } | ||
442 | }"#, | ||
443 | r#"async fn foo() -> Result<i32, ${0:_}> { | ||
444 | if true { | ||
445 | if false { | ||
446 | Ok(1.await) | ||
447 | } else { | ||
448 | Ok(2.await) | ||
449 | } | ||
450 | } else { | ||
451 | Ok(24i32.await) | ||
452 | } | ||
453 | }"#, | ||
454 | ); | ||
455 | } | ||
456 | |||
457 | #[test] | ||
458 | fn change_return_type_to_result_simple_with_array() { | ||
459 | check_assist( | ||
460 | change_return_type_to_result, | ||
461 | r#"fn foo() -> [i32;<|> 3] { | ||
462 | [1, 2, 3] | ||
463 | }"#, | ||
464 | r#"fn foo() -> Result<[i32; 3], ${0:_}> { | ||
465 | Ok([1, 2, 3]) | ||
466 | }"#, | ||
467 | ); | ||
468 | } | ||
469 | |||
470 | #[test] | ||
471 | fn change_return_type_to_result_simple_with_cast() { | ||
472 | check_assist( | ||
473 | change_return_type_to_result, | ||
474 | r#"fn foo() -<|>> i32 { | ||
475 | if true { | ||
476 | if false { | ||
477 | 1 as i32 | ||
478 | } else { | ||
479 | 2 as i32 | ||
480 | } | ||
481 | } else { | ||
482 | 24 as i32 | ||
483 | } | ||
484 | }"#, | ||
485 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
486 | if true { | ||
487 | if false { | ||
488 | Ok(1 as i32) | ||
489 | } else { | ||
490 | Ok(2 as i32) | ||
491 | } | ||
492 | } else { | ||
493 | Ok(24 as i32) | ||
494 | } | ||
495 | }"#, | ||
496 | ); | ||
497 | } | ||
498 | |||
499 | #[test] | ||
500 | fn change_return_type_to_result_simple_with_tail_block_like_match() { | ||
501 | check_assist( | ||
502 | change_return_type_to_result, | ||
503 | r#"fn foo() -> i32<|> { | ||
504 | let my_var = 5; | ||
505 | match my_var { | ||
506 | 5 => 42i32, | ||
507 | _ => 24i32, | ||
508 | } | ||
509 | }"#, | ||
510 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
511 | let my_var = 5; | ||
512 | match my_var { | ||
513 | 5 => Ok(42i32), | ||
514 | _ => Ok(24i32), | ||
515 | } | ||
516 | }"#, | ||
517 | ); | ||
518 | } | ||
519 | |||
520 | #[test] | ||
521 | fn change_return_type_to_result_simple_with_loop_with_tail() { | ||
522 | check_assist( | ||
523 | change_return_type_to_result, | ||
524 | r#"fn foo() -> i32<|> { | ||
525 | let my_var = 5; | ||
526 | loop { | ||
527 | println!("test"); | ||
528 | 5 | ||
529 | } | ||
530 | |||
531 | my_var | ||
532 | }"#, | ||
533 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
534 | let my_var = 5; | ||
535 | loop { | ||
536 | println!("test"); | ||
537 | 5 | ||
538 | } | ||
539 | |||
540 | Ok(my_var) | ||
541 | }"#, | ||
542 | ); | ||
543 | } | ||
544 | |||
545 | #[test] | ||
546 | fn change_return_type_to_result_simple_with_loop_in_let_stmt() { | ||
547 | check_assist( | ||
548 | change_return_type_to_result, | ||
549 | r#"fn foo() -> i32<|> { | ||
550 | let my_var = let x = loop { | ||
551 | break 1; | ||
552 | }; | ||
553 | |||
554 | my_var | ||
555 | }"#, | ||
556 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
557 | let my_var = let x = loop { | ||
558 | break 1; | ||
559 | }; | ||
560 | |||
561 | Ok(my_var) | ||
562 | }"#, | ||
563 | ); | ||
564 | } | ||
565 | |||
566 | #[test] | ||
567 | fn change_return_type_to_result_simple_with_tail_block_like_match_return_expr() { | ||
568 | check_assist( | ||
569 | change_return_type_to_result, | ||
570 | r#"fn foo() -> i32<|> { | ||
571 | let my_var = 5; | ||
572 | let res = match my_var { | ||
573 | 5 => 42i32, | ||
574 | _ => return 24i32, | ||
575 | }; | ||
576 | |||
577 | res | ||
578 | }"#, | ||
579 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
580 | let my_var = 5; | ||
581 | let res = match my_var { | ||
582 | 5 => 42i32, | ||
583 | _ => return Ok(24i32), | ||
584 | }; | ||
585 | |||
586 | Ok(res) | ||
587 | }"#, | ||
588 | ); | ||
589 | |||
590 | check_assist( | ||
591 | change_return_type_to_result, | ||
592 | r#"fn foo() -> i32<|> { | ||
593 | let my_var = 5; | ||
594 | let res = if my_var == 5 { | ||
595 | 42i32 | ||
596 | } else { | ||
597 | return 24i32; | ||
598 | }; | ||
599 | |||
600 | res | ||
601 | }"#, | ||
602 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
603 | let my_var = 5; | ||
604 | let res = if my_var == 5 { | ||
605 | 42i32 | ||
606 | } else { | ||
607 | return Ok(24i32); | ||
608 | }; | ||
609 | |||
610 | Ok(res) | ||
611 | }"#, | ||
612 | ); | ||
613 | } | ||
614 | |||
615 | #[test] | ||
616 | fn change_return_type_to_result_simple_with_tail_block_like_match_deeper() { | ||
617 | check_assist( | ||
618 | change_return_type_to_result, | ||
619 | r#"fn foo() -> i32<|> { | ||
620 | let my_var = 5; | ||
621 | match my_var { | ||
622 | 5 => { | ||
623 | if true { | ||
624 | 42i32 | ||
625 | } else { | ||
626 | 25i32 | ||
627 | } | ||
628 | }, | ||
629 | _ => { | ||
630 | let test = "test"; | ||
631 | if test == "test" { | ||
632 | return bar(); | ||
633 | } | ||
634 | 53i32 | ||
635 | }, | ||
636 | } | ||
637 | }"#, | ||
638 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
639 | let my_var = 5; | ||
640 | match my_var { | ||
641 | 5 => { | ||
642 | if true { | ||
643 | Ok(42i32) | ||
644 | } else { | ||
645 | Ok(25i32) | ||
646 | } | ||
647 | }, | ||
648 | _ => { | ||
649 | let test = "test"; | ||
650 | if test == "test" { | ||
651 | return Ok(bar()); | ||
652 | } | ||
653 | Ok(53i32) | ||
654 | }, | ||
655 | } | ||
656 | }"#, | ||
657 | ); | ||
658 | } | ||
659 | |||
660 | #[test] | ||
661 | fn change_return_type_to_result_simple_with_tail_block_like_early_return() { | ||
662 | check_assist( | ||
663 | change_return_type_to_result, | ||
664 | r#"fn foo() -> i<|>32 { | ||
665 | let test = "test"; | ||
666 | if test == "test" { | ||
667 | return 24i32; | ||
668 | } | ||
669 | 53i32 | ||
670 | }"#, | ||
671 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
672 | let test = "test"; | ||
673 | if test == "test" { | ||
674 | return Ok(24i32); | ||
675 | } | ||
676 | Ok(53i32) | ||
677 | }"#, | ||
678 | ); | ||
679 | } | ||
680 | |||
681 | #[test] | ||
682 | fn change_return_type_to_result_simple_with_closure() { | ||
683 | check_assist( | ||
684 | change_return_type_to_result, | ||
685 | r#"fn foo(the_field: u32) -><|> u32 { | ||
686 | let true_closure = || { | ||
687 | return true; | ||
688 | }; | ||
689 | if the_field < 5 { | ||
690 | let mut i = 0; | ||
691 | |||
692 | |||
693 | if true_closure() { | ||
694 | return 99; | ||
695 | } else { | ||
696 | return 0; | ||
697 | } | ||
698 | } | ||
699 | |||
700 | the_field | ||
701 | }"#, | ||
702 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
703 | let true_closure = || { | ||
704 | return true; | ||
705 | }; | ||
706 | if the_field < 5 { | ||
707 | let mut i = 0; | ||
708 | |||
709 | |||
710 | if true_closure() { | ||
711 | return Ok(99); | ||
712 | } else { | ||
713 | return Ok(0); | ||
714 | } | ||
715 | } | ||
716 | |||
717 | Ok(the_field) | ||
718 | }"#, | ||
719 | ); | ||
720 | |||
721 | check_assist( | ||
722 | change_return_type_to_result, | ||
723 | r#"fn foo(the_field: u32) -> u32<|> { | ||
724 | let true_closure = || { | ||
725 | return true; | ||
726 | }; | ||
727 | if the_field < 5 { | ||
728 | let mut i = 0; | ||
729 | |||
730 | |||
731 | if true_closure() { | ||
732 | return 99; | ||
733 | } else { | ||
734 | return 0; | ||
735 | } | ||
736 | } | ||
737 | let t = None; | ||
738 | |||
739 | t.unwrap_or_else(|| the_field) | ||
740 | }"#, | ||
741 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
742 | let true_closure = || { | ||
743 | return true; | ||
744 | }; | ||
745 | if the_field < 5 { | ||
746 | let mut i = 0; | ||
747 | |||
748 | |||
749 | if true_closure() { | ||
750 | return Ok(99); | ||
751 | } else { | ||
752 | return Ok(0); | ||
753 | } | ||
754 | } | ||
755 | let t = None; | ||
756 | |||
757 | Ok(t.unwrap_or_else(|| the_field)) | ||
758 | }"#, | ||
759 | ); | ||
760 | } | ||
761 | |||
762 | #[test] | ||
763 | fn change_return_type_to_result_simple_with_weird_forms() { | ||
764 | check_assist( | ||
765 | change_return_type_to_result, | ||
766 | r#"fn foo() -> i32<|> { | ||
767 | let test = "test"; | ||
768 | if test == "test" { | ||
769 | return 24i32; | ||
770 | } | ||
771 | let mut i = 0; | ||
772 | loop { | ||
773 | if i == 1 { | ||
774 | break 55; | ||
775 | } | ||
776 | i += 1; | ||
777 | } | ||
778 | }"#, | ||
779 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
780 | let test = "test"; | ||
781 | if test == "test" { | ||
782 | return Ok(24i32); | ||
783 | } | ||
784 | let mut i = 0; | ||
785 | loop { | ||
786 | if i == 1 { | ||
787 | break Ok(55); | ||
788 | } | ||
789 | i += 1; | ||
790 | } | ||
791 | }"#, | ||
792 | ); | ||
793 | |||
794 | check_assist( | ||
795 | change_return_type_to_result, | ||
796 | r#"fn foo() -> i32<|> { | ||
797 | let test = "test"; | ||
798 | if test == "test" { | ||
799 | return 24i32; | ||
800 | } | ||
801 | let mut i = 0; | ||
802 | loop { | ||
803 | loop { | ||
804 | if i == 1 { | ||
805 | break 55; | ||
806 | } | ||
807 | i += 1; | ||
808 | } | ||
809 | } | ||
810 | }"#, | ||
811 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
812 | let test = "test"; | ||
813 | if test == "test" { | ||
814 | return Ok(24i32); | ||
815 | } | ||
816 | let mut i = 0; | ||
817 | loop { | ||
818 | loop { | ||
819 | if i == 1 { | ||
820 | break Ok(55); | ||
821 | } | ||
822 | i += 1; | ||
823 | } | ||
824 | } | ||
825 | }"#, | ||
826 | ); | ||
827 | |||
828 | check_assist( | ||
829 | change_return_type_to_result, | ||
830 | r#"fn foo() -> i3<|>2 { | ||
831 | let test = "test"; | ||
832 | let other = 5; | ||
833 | if test == "test" { | ||
834 | let res = match other { | ||
835 | 5 => 43, | ||
836 | _ => return 56, | ||
837 | }; | ||
838 | } | ||
839 | let mut i = 0; | ||
840 | loop { | ||
841 | loop { | ||
842 | if i == 1 { | ||
843 | break 55; | ||
844 | } | ||
845 | i += 1; | ||
846 | } | ||
847 | } | ||
848 | }"#, | ||
849 | r#"fn foo() -> Result<i32, ${0:_}> { | ||
850 | let test = "test"; | ||
851 | let other = 5; | ||
852 | if test == "test" { | ||
853 | let res = match other { | ||
854 | 5 => 43, | ||
855 | _ => return Ok(56), | ||
856 | }; | ||
857 | } | ||
858 | let mut i = 0; | ||
859 | loop { | ||
860 | loop { | ||
861 | if i == 1 { | ||
862 | break Ok(55); | ||
863 | } | ||
864 | i += 1; | ||
865 | } | ||
866 | } | ||
867 | }"#, | ||
868 | ); | ||
869 | |||
870 | check_assist( | ||
871 | change_return_type_to_result, | ||
872 | r#"fn foo(the_field: u32) -> u32<|> { | ||
873 | if the_field < 5 { | ||
874 | let mut i = 0; | ||
875 | loop { | ||
876 | if i > 5 { | ||
877 | return 55u32; | ||
878 | } | ||
879 | i += 3; | ||
880 | } | ||
881 | |||
882 | match i { | ||
883 | 5 => return 99, | ||
884 | _ => return 0, | ||
885 | }; | ||
886 | } | ||
887 | |||
888 | the_field | ||
889 | }"#, | ||
890 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
891 | if the_field < 5 { | ||
892 | let mut i = 0; | ||
893 | loop { | ||
894 | if i > 5 { | ||
895 | return Ok(55u32); | ||
896 | } | ||
897 | i += 3; | ||
898 | } | ||
899 | |||
900 | match i { | ||
901 | 5 => return Ok(99), | ||
902 | _ => return Ok(0), | ||
903 | }; | ||
904 | } | ||
905 | |||
906 | Ok(the_field) | ||
907 | }"#, | ||
908 | ); | ||
909 | |||
910 | check_assist( | ||
911 | change_return_type_to_result, | ||
912 | r#"fn foo(the_field: u32) -> u3<|>2 { | ||
913 | if the_field < 5 { | ||
914 | let mut i = 0; | ||
915 | |||
916 | match i { | ||
917 | 5 => return 99, | ||
918 | _ => return 0, | ||
919 | } | ||
920 | } | ||
921 | |||
922 | the_field | ||
923 | }"#, | ||
924 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
925 | if the_field < 5 { | ||
926 | let mut i = 0; | ||
927 | |||
928 | match i { | ||
929 | 5 => return Ok(99), | ||
930 | _ => return Ok(0), | ||
931 | } | ||
932 | } | ||
933 | |||
934 | Ok(the_field) | ||
935 | }"#, | ||
936 | ); | ||
937 | |||
938 | check_assist( | ||
939 | change_return_type_to_result, | ||
940 | r#"fn foo(the_field: u32) -> u32<|> { | ||
941 | if the_field < 5 { | ||
942 | let mut i = 0; | ||
943 | |||
944 | if i == 5 { | ||
945 | return 99 | ||
946 | } else { | ||
947 | return 0 | ||
948 | } | ||
949 | } | ||
950 | |||
951 | the_field | ||
952 | }"#, | ||
953 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
954 | if the_field < 5 { | ||
955 | let mut i = 0; | ||
956 | |||
957 | if i == 5 { | ||
958 | return Ok(99) | ||
959 | } else { | ||
960 | return Ok(0) | ||
961 | } | ||
962 | } | ||
963 | |||
964 | Ok(the_field) | ||
965 | }"#, | ||
966 | ); | ||
967 | |||
968 | check_assist( | ||
969 | change_return_type_to_result, | ||
970 | r#"fn foo(the_field: u32) -> <|>u32 { | ||
971 | if the_field < 5 { | ||
972 | let mut i = 0; | ||
973 | |||
974 | if i == 5 { | ||
975 | return 99; | ||
976 | } else { | ||
977 | return 0; | ||
978 | } | ||
979 | } | ||
980 | |||
981 | the_field | ||
982 | }"#, | ||
983 | r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> { | ||
984 | if the_field < 5 { | ||
985 | let mut i = 0; | ||
986 | |||
987 | if i == 5 { | ||
988 | return Ok(99); | ||
989 | } else { | ||
990 | return Ok(0); | ||
991 | } | ||
992 | } | ||
993 | |||
994 | Ok(the_field) | ||
995 | }"#, | ||
996 | ); | ||
997 | } | ||
998 | } | ||
diff --git a/crates/assists/src/handlers/change_visibility.rs b/crates/assists/src/handlers/change_visibility.rs new file mode 100644 index 000000000..32dc05378 --- /dev/null +++ b/crates/assists/src/handlers/change_visibility.rs | |||
@@ -0,0 +1,200 @@ | |||
1 | use 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/assists/src/handlers/early_return.rs b/crates/assists/src/handlers/early_return.rs new file mode 100644 index 000000000..7fd78e9d4 --- /dev/null +++ b/crates/assists/src/handlers/early_return.rs | |||
@@ -0,0 +1,515 @@ | |||
1 | use std::{iter::once, ops::RangeInclusive}; | ||
2 | |||
3 | use 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 | ); | ||