diff options
Diffstat (limited to 'crates')
1587 files changed, 129005 insertions, 126973 deletions
diff --git a/crates/arena/Cargo.toml b/crates/arena/Cargo.toml new file mode 100644 index 000000000..f2bb5cc45 --- /dev/null +++ b/crates/arena/Cargo.toml | |||
@@ -0,0 +1,9 @@ | |||
1 | [package] | ||
2 | name = "arena" | ||
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 | ||
diff --git a/crates/ra_arena/src/lib.rs b/crates/arena/src/lib.rs index 3169aa5b8..3169aa5b8 100644 --- a/crates/ra_arena/src/lib.rs +++ b/crates/arena/src/lib.rs | |||
diff --git a/crates/ra_arena/src/map.rs b/crates/arena/src/map.rs index 0f33907c0..0f33907c0 100644 --- a/crates/ra_arena/src/map.rs +++ b/crates/arena/src/map.rs | |||
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/ra_assists/src/assist_config.rs b/crates/assists/src/assist_config.rs index cda2abfb9..cda2abfb9 100644 --- a/crates/ra_assists/src/assist_config.rs +++ b/crates/assists/src/assist_config.rs | |||
diff --git a/crates/assists/src/assist_context.rs b/crates/assists/src/assist_context.rs new file mode 100644 index 000000000..11c171fc2 --- /dev/null +++ b/crates/assists/src/assist_context.rs | |||
@@ -0,0 +1,293 @@ | |||
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 | label::Label, | ||
10 | source_change::{SourceChange, SourceFileEdit}, | ||
11 | RootDatabase, | ||
12 | }; | ||
13 | use syntax::{ | ||
14 | algo::{self, find_node_at_offset, SyntaxRewriter}, | ||
15 | AstNode, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange, TextSize, | ||
16 | TokenAtOffset, | ||
17 | }; | ||
18 | use text_edit::{TextEdit, TextEditBuilder}; | ||
19 | |||
20 | use crate::{ | ||
21 | assist_config::{AssistConfig, SnippetCap}, | ||
22 | Assist, AssistId, AssistKind, GroupLabel, ResolvedAssist, | ||
23 | }; | ||
24 | |||
25 | /// `AssistContext` allows to apply an assist or check if it could be applied. | ||
26 | /// | ||
27 | /// Assists use a somewhat over-engineered approach, given the current needs. | ||
28 | /// The assists workflow consists of two phases. In the first phase, a user asks | ||
29 | /// for the list of available assists. In the second phase, the user picks a | ||
30 | /// particular assist and it gets applied. | ||
31 | /// | ||
32 | /// There are two peculiarities here: | ||
33 | /// | ||
34 | /// * first, we ideally avoid computing more things then necessary to answer "is | ||
35 | /// assist applicable" in the first phase. | ||
36 | /// * second, when we are applying assist, we don't have a guarantee that there | ||
37 | /// weren't any changes between the point when user asked for assists and when | ||
38 | /// they applied a particular assist. So, when applying assist, we need to do | ||
39 | /// all the checks from scratch. | ||
40 | /// | ||
41 | /// To avoid repeating the same code twice for both "check" and "apply" | ||
42 | /// functions, we use an approach reminiscent of that of Django's function based | ||
43 | /// views dealing with forms. Each assist receives a runtime parameter, | ||
44 | /// `resolve`. It first check if an edit is applicable (potentially computing | ||
45 | /// info required to compute the actual edit). If it is applicable, and | ||
46 | /// `resolve` is `true`, it then computes the actual edit. | ||
47 | /// | ||
48 | /// So, to implement the original assists workflow, we can first apply each edit | ||
49 | /// with `resolve = false`, and then applying the selected edit again, with | ||
50 | /// `resolve = true` this time. | ||
51 | /// | ||
52 | /// Note, however, that we don't actually use such two-phase logic at the | ||
53 | /// moment, because the LSP API is pretty awkward in this place, and it's much | ||
54 | /// easier to just compute the edit eagerly :-) | ||
55 | pub(crate) struct AssistContext<'a> { | ||
56 | pub(crate) config: &'a AssistConfig, | ||
57 | pub(crate) sema: Semantics<'a, RootDatabase>, | ||
58 | pub(crate) frange: FileRange, | ||
59 | source_file: SourceFile, | ||
60 | } | ||
61 | |||
62 | impl<'a> AssistContext<'a> { | ||
63 | pub(crate) fn new( | ||
64 | sema: Semantics<'a, RootDatabase>, | ||
65 | config: &'a AssistConfig, | ||
66 | frange: FileRange, | ||
67 | ) -> AssistContext<'a> { | ||
68 | let source_file = sema.parse(frange.file_id); | ||
69 | AssistContext { config, sema, frange, source_file } | ||
70 | } | ||
71 | |||
72 | pub(crate) fn db(&self) -> &RootDatabase { | ||
73 | self.sema.db | ||
74 | } | ||
75 | |||
76 | pub(crate) fn source_file(&self) -> &SourceFile { | ||
77 | &self.source_file | ||
78 | } | ||
79 | |||
80 | // NB, this ignores active selection. | ||
81 | pub(crate) fn offset(&self) -> TextSize { | ||
82 | self.frange.range.start() | ||
83 | } | ||
84 | |||
85 | pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> { | ||
86 | self.source_file.syntax().token_at_offset(self.offset()) | ||
87 | } | ||
88 | pub(crate) fn find_token_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> { | ||
89 | self.token_at_offset().find(|it| it.kind() == kind) | ||
90 | } | ||
91 | pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> { | ||
92 | find_node_at_offset(self.source_file.syntax(), self.offset()) | ||
93 | } | ||
94 | pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> { | ||
95 | self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset()) | ||
96 | } | ||
97 | pub(crate) fn covering_element(&self) -> SyntaxElement { | ||
98 | find_covering_element(self.source_file.syntax(), self.frange.range) | ||
99 | } | ||
100 | // FIXME: remove | ||
101 | pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement { | ||
102 | find_covering_element(self.source_file.syntax(), range) | ||
103 | } | ||
104 | } | ||
105 | |||
106 | pub(crate) struct Assists { | ||
107 | resolve: bool, | ||
108 | file: FileId, | ||
109 | buf: Vec<(Assist, Option<SourceChange>)>, | ||
110 | allowed: Option<Vec<AssistKind>>, | ||
111 | } | ||
112 | |||
113 | impl Assists { | ||
114 | pub(crate) fn new_resolved(ctx: &AssistContext) -> Assists { | ||
115 | Assists { | ||
116 | resolve: true, | ||
117 | file: ctx.frange.file_id, | ||
118 | buf: Vec::new(), | ||
119 | allowed: ctx.config.allowed.clone(), | ||
120 | } | ||
121 | } | ||
122 | |||
123 | pub(crate) fn new_unresolved(ctx: &AssistContext) -> Assists { | ||
124 | Assists { | ||
125 | resolve: false, | ||
126 | file: ctx.frange.file_id, | ||
127 | buf: Vec::new(), | ||
128 | allowed: ctx.config.allowed.clone(), | ||
129 | } | ||
130 | } | ||
131 | |||
132 | pub(crate) fn finish_unresolved(self) -> Vec<Assist> { | ||
133 | assert!(!self.resolve); | ||
134 | self.finish() | ||
135 | .into_iter() | ||
136 | .map(|(label, edit)| { | ||
137 | assert!(edit.is_none()); | ||
138 | label | ||
139 | }) | ||
140 | .collect() | ||
141 | } | ||
142 | |||
143 | pub(crate) fn finish_resolved(self) -> Vec<ResolvedAssist> { | ||
144 | assert!(self.resolve); | ||
145 | self.finish() | ||
146 | .into_iter() | ||
147 | .map(|(label, edit)| ResolvedAssist { assist: label, source_change: edit.unwrap() }) | ||
148 | .collect() | ||
149 | } | ||
150 | |||
151 | pub(crate) fn add( | ||
152 | &mut self, | ||
153 | id: AssistId, | ||
154 | label: impl Into<String>, | ||
155 | target: TextRange, | ||
156 | f: impl FnOnce(&mut AssistBuilder), | ||
157 | ) -> Option<()> { | ||
158 | if !self.is_allowed(&id) { | ||
159 | return None; | ||
160 | } | ||
161 | let label = Label::new(label.into()); | ||
162 | let assist = Assist { id, label, group: None, target }; | ||
163 | self.add_impl(assist, f) | ||
164 | } | ||
165 | |||
166 | pub(crate) fn add_group( | ||
167 | &mut self, | ||
168 | group: &GroupLabel, | ||
169 | id: AssistId, | ||
170 | label: impl Into<String>, | ||
171 | target: TextRange, | ||
172 | f: impl FnOnce(&mut AssistBuilder), | ||
173 | ) -> Option<()> { | ||
174 | if !self.is_allowed(&id) { | ||
175 | return None; | ||
176 | } | ||
177 | let label = Label::new(label.into()); | ||
178 | let assist = Assist { id, label, group: Some(group.clone()), target }; | ||
179 | self.add_impl(assist, f) | ||
180 | } | ||
181 | |||
182 | fn add_impl(&mut self, assist: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> { | ||
183 | let source_change = if self.resolve { | ||
184 | let mut builder = AssistBuilder::new(self.file); | ||
185 | f(&mut builder); | ||
186 | Some(builder.finish()) | ||
187 | } else { | ||
188 | None | ||
189 | }; | ||
190 | |||
191 | self.buf.push((assist, source_change)); | ||
192 | Some(()) | ||
193 | } | ||
194 | |||
195 | fn finish(mut self) -> Vec<(Assist, Option<SourceChange>)> { | ||
196 | self.buf.sort_by_key(|(label, _edit)| label.target.len()); | ||
197 | self.buf | ||
198 | } | ||
199 | |||
200 | fn is_allowed(&self, id: &AssistId) -> bool { | ||
201 | match &self.allowed { | ||
202 | Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)), | ||
203 | None => true, | ||
204 | } | ||
205 | } | ||
206 | } | ||
207 | |||
208 | pub(crate) struct AssistBuilder { | ||
209 | edit: TextEditBuilder, | ||
210 | file_id: FileId, | ||
211 | is_snippet: bool, | ||
212 | change: SourceChange, | ||
213 | } | ||
214 | |||
215 | impl AssistBuilder { | ||
216 | pub(crate) fn new(file_id: FileId) -> AssistBuilder { | ||
217 | AssistBuilder { | ||
218 | edit: TextEdit::builder(), | ||
219 | file_id, | ||
220 | is_snippet: false, | ||
221 | change: SourceChange::default(), | ||
222 | } | ||
223 | } | ||
224 | |||
225 | pub(crate) fn edit_file(&mut self, file_id: FileId) { | ||
226 | self.file_id = file_id; | ||
227 | } | ||
228 | |||
229 | fn commit(&mut self) { | ||
230 | let edit = mem::take(&mut self.edit).finish(); | ||
231 | if !edit.is_empty() { | ||
232 | let new_edit = SourceFileEdit { file_id: self.file_id, edit }; | ||
233 | assert!(!self.change.source_file_edits.iter().any(|it| it.file_id == new_edit.file_id)); | ||
234 | self.change.source_file_edits.push(new_edit); | ||
235 | } | ||
236 | } | ||
237 | |||
238 | /// Remove specified `range` of text. | ||
239 | pub(crate) fn delete(&mut self, range: TextRange) { | ||
240 | self.edit.delete(range) | ||
241 | } | ||
242 | /// Append specified `text` at the given `offset` | ||
243 | pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) { | ||
244 | self.edit.insert(offset, text.into()) | ||
245 | } | ||
246 | /// Append specified `snippet` at the given `offset` | ||
247 | pub(crate) fn insert_snippet( | ||
248 | &mut self, | ||
249 | _cap: SnippetCap, | ||
250 | offset: TextSize, | ||
251 | snippet: impl Into<String>, | ||
252 | ) { | ||
253 | self.is_snippet = true; | ||
254 | self.insert(offset, snippet); | ||
255 | } | ||
256 | /// Replaces specified `range` of text with a given string. | ||
257 | pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) { | ||
258 | self.edit.replace(range, replace_with.into()) | ||
259 | } | ||
260 | /// Replaces specified `range` of text with a given `snippet`. | ||
261 | pub(crate) fn replace_snippet( | ||
262 | &mut self, | ||
263 | _cap: SnippetCap, | ||
264 | range: TextRange, | ||
265 | snippet: impl Into<String>, | ||
266 | ) { | ||
267 | self.is_snippet = true; | ||
268 | self.replace(range, snippet); | ||
269 | } | ||
270 | pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) { | ||
271 | algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit) | ||
272 | } | ||
273 | pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) { | ||
274 | let node = rewriter.rewrite_root().unwrap(); | ||
275 | let new = rewriter.rewrite(&node); | ||
276 | algo::diff(&node, &new).into_text_edit(&mut self.edit); | ||
277 | } | ||
278 | |||
279 | // FIXME: kill this API | ||
280 | /// Get access to the raw `TextEditBuilder`. | ||
281 | pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder { | ||
282 | &mut self.edit | ||
283 | } | ||
284 | |||
285 | fn finish(mut self) -> SourceChange { | ||
286 | self.commit(); | ||
287 | let mut change = mem::take(&mut self.change); | ||
288 | if self.is_snippet { | ||
289 | change.is_snippet = true; | ||
290 | } | ||
291 | change | ||
292 | } | ||
293 | } | ||
diff --git a/crates/assists/src/ast_transform.rs b/crates/assists/src/ast_transform.rs new file mode 100644 index 000000000..5216862ba --- /dev/null +++ b/crates/assists/src/ast_transform.rs | |||
@@ -0,0 +1,200 @@ | |||
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 fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: N) -> N { | ||
11 | SyntaxRewriter::from_fn(|element| match element { | ||
12 | syntax::SyntaxElement::Node(n) => { | ||
13 | let replacement = transformer.get_substitution(&n)?; | ||
14 | Some(replacement.into()) | ||
15 | } | ||
16 | _ => None, | ||
17 | }) | ||
18 | .rewrite_ast(&node) | ||
19 | } | ||
20 | |||
21 | pub trait AstTransform<'a> { | ||
22 | fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode>; | ||
23 | |||
24 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a>; | ||
25 | fn or<T: AstTransform<'a> + 'a>(self, other: T) -> Box<dyn AstTransform<'a> + 'a> | ||
26 | where | ||
27 | Self: Sized + 'a, | ||
28 | { | ||
29 | self.chain_before(Box::new(other)) | ||
30 | } | ||
31 | } | ||
32 | |||
33 | struct NullTransformer; | ||
34 | |||
35 | impl<'a> AstTransform<'a> for NullTransformer { | ||
36 | fn get_substitution(&self, _node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
37 | None | ||
38 | } | ||
39 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
40 | other | ||
41 | } | ||
42 | } | ||
43 | |||
44 | pub struct SubstituteTypeParams<'a> { | ||
45 | source_scope: &'a SemanticsScope<'a>, | ||
46 | substs: FxHashMap<hir::TypeParam, ast::Type>, | ||
47 | previous: Box<dyn AstTransform<'a> + 'a>, | ||
48 | } | ||
49 | |||
50 | impl<'a> SubstituteTypeParams<'a> { | ||
51 | pub fn for_trait_impl( | ||
52 | source_scope: &'a SemanticsScope<'a>, | ||
53 | // FIXME: there's implicit invariant that `trait_` and `source_scope` match... | ||
54 | trait_: hir::Trait, | ||
55 | impl_def: ast::Impl, | ||
56 | ) -> SubstituteTypeParams<'a> { | ||
57 | let substs = get_syntactic_substs(impl_def).unwrap_or_default(); | ||
58 | let generic_def: hir::GenericDef = trait_.into(); | ||
59 | let substs_by_param: FxHashMap<_, _> = generic_def | ||
60 | .params(source_scope.db) | ||
61 | .into_iter() | ||
62 | // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky | ||
63 | .skip(1) | ||
64 | // The actual list of trait type parameters may be longer than the one | ||
65 | // used in the `impl` block due to trailing default type parameters. | ||
66 | // For that case we extend the `substs` with an empty iterator so we | ||
67 | // can still hit those trailing values and check if they actually have | ||
68 | // a default type. If they do, go for that type from `hir` to `ast` so | ||
69 | // the resulting change can be applied correctly. | ||
70 | .zip(substs.into_iter().map(Some).chain(std::iter::repeat(None))) | ||
71 | .filter_map(|(k, v)| match v { | ||
72 | Some(v) => Some((k, v)), | ||
73 | None => { | ||
74 | let default = k.default(source_scope.db)?; | ||
75 | Some(( | ||
76 | k, | ||
77 | ast::make::ty( | ||
78 | &default | ||
79 | .display_source_code(source_scope.db, source_scope.module()?.into()) | ||
80 | .ok()?, | ||
81 | ), | ||
82 | )) | ||
83 | } | ||
84 | }) | ||
85 | .collect(); | ||
86 | return SubstituteTypeParams { | ||
87 | source_scope, | ||
88 | substs: substs_by_param, | ||
89 | previous: Box::new(NullTransformer), | ||
90 | }; | ||
91 | |||
92 | // FIXME: It would probably be nicer if we could get this via HIR (i.e. get the | ||
93 | // trait ref, and then go from the types in the substs back to the syntax). | ||
94 | fn get_syntactic_substs(impl_def: ast::Impl) -> Option<Vec<ast::Type>> { | ||
95 | let target_trait = impl_def.trait_()?; | ||
96 | let path_type = match target_trait { | ||
97 | ast::Type::PathType(path) => path, | ||
98 | _ => return None, | ||
99 | }; | ||
100 | let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?; | ||
101 | |||
102 | let mut result = Vec::new(); | ||
103 | for generic_arg in generic_arg_list.generic_args() { | ||
104 | match generic_arg { | ||
105 | ast::GenericArg::TypeArg(type_arg) => result.push(type_arg.ty()?), | ||
106 | ast::GenericArg::AssocTypeArg(_) | ||
107 | | ast::GenericArg::LifetimeArg(_) | ||
108 | | ast::GenericArg::ConstArg(_) => (), | ||
109 | } | ||
110 | } | ||
111 | |||
112 | Some(result) | ||
113 | } | ||
114 | } | ||
115 | fn get_substitution_inner(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
116 | let type_ref = ast::Type::cast(node.clone())?; | ||
117 | let path = match &type_ref { | ||
118 | ast::Type::PathType(path_type) => path_type.path()?, | ||
119 | _ => return None, | ||
120 | }; | ||
121 | let resolution = self.source_scope.speculative_resolve(&path)?; | ||
122 | match resolution { | ||
123 | hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()), | ||
124 | _ => None, | ||
125 | } | ||
126 | } | ||
127 | } | ||
128 | |||
129 | impl<'a> AstTransform<'a> for SubstituteTypeParams<'a> { | ||
130 | fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
131 | self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node)) | ||
132 | } | ||
133 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
134 | Box::new(SubstituteTypeParams { previous: other, ..self }) | ||
135 | } | ||
136 | } | ||
137 | |||
138 | pub struct QualifyPaths<'a> { | ||
139 | target_scope: &'a SemanticsScope<'a>, | ||
140 | source_scope: &'a SemanticsScope<'a>, | ||
141 | previous: Box<dyn AstTransform<'a> + 'a>, | ||
142 | } | ||
143 | |||
144 | impl<'a> QualifyPaths<'a> { | ||
145 | pub fn new(target_scope: &'a SemanticsScope<'a>, source_scope: &'a SemanticsScope<'a>) -> Self { | ||
146 | Self { target_scope, source_scope, previous: Box::new(NullTransformer) } | ||
147 | } | ||
148 | |||
149 | fn get_substitution_inner(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
150 | // FIXME handle value ns? | ||
151 | let from = self.target_scope.module()?; | ||
152 | let p = ast::Path::cast(node.clone())?; | ||
153 | if p.segment().and_then(|s| s.param_list()).is_some() { | ||
154 | // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway | ||
155 | return None; | ||
156 | } | ||
157 | let resolution = self.source_scope.speculative_resolve(&p)?; | ||
158 | match resolution { | ||
159 | PathResolution::Def(def) => { | ||
160 | let found_path = from.find_use_path(self.source_scope.db.upcast(), def)?; | ||
161 | let mut path = path_to_ast(found_path); | ||
162 | |||
163 | let type_args = p | ||
164 | .segment() | ||
165 | .and_then(|s| s.generic_arg_list()) | ||
166 | .map(|arg_list| apply(self, arg_list)); | ||
167 | if let Some(type_args) = type_args { | ||
168 | let last_segment = path.segment().unwrap(); | ||
169 | path = path.with_segment(last_segment.with_type_args(type_args)) | ||
170 | } | ||
171 | |||
172 | Some(path.syntax().clone()) | ||
173 | } | ||
174 | PathResolution::Local(_) | ||
175 | | PathResolution::TypeParam(_) | ||
176 | | PathResolution::SelfType(_) => None, | ||
177 | PathResolution::Macro(_) => None, | ||
178 | PathResolution::AssocItem(_) => None, | ||
179 | } | ||
180 | } | ||
181 | } | ||
182 | |||
183 | impl<'a> AstTransform<'a> for QualifyPaths<'a> { | ||
184 | fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> { | ||
185 | self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node)) | ||
186 | } | ||
187 | fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> { | ||
188 | Box::new(QualifyPaths { previous: other, ..self }) | ||
189 | } | ||
190 | } | ||
191 | |||
192 | pub(crate) fn path_to_ast(path: hir::ModPath) -> ast::Path { | ||
193 | let parse = ast::SourceFile::parse(&path.to_string()); | ||
194 | parse | ||
195 | .tree() | ||
196 | .syntax() | ||
197 | .descendants() | ||
198 | .find_map(ast::Path::cast) | ||
199 | .unwrap_or_else(|| panic!("failed to parse path {:?}, `{}`", path, path)) | ||
200 | } | ||
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..83a2ada9a --- /dev/null +++ b/crates/assists/src/handlers/add_missing_impl_members.rs | |||
@@ -0,0 +1,766 @@ | |||
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 | pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
54 | add_missing_impl_members_inner( | ||
55 | acc, | ||
56 | ctx, | ||
57 | AddMissingImplMembersMode::NoDefaultMethods, | ||
58 | "add_impl_missing_members", | ||
59 | "Implement missing members", | ||
60 | ) | ||
61 | } | ||
62 | |||
63 | // Assist: add_impl_default_members | ||
64 | // | ||
65 | // Adds scaffold for overriding default impl members. | ||
66 | // | ||
67 | // ``` | ||
68 | // trait Trait { | ||
69 | // Type X; | ||
70 | // fn foo(&self); | ||
71 | // fn bar(&self) {} | ||
72 | // } | ||
73 | // | ||
74 | // impl Trait for () { | ||
75 | // Type X = (); | ||
76 | // fn foo(&self) {}<|> | ||
77 | // | ||
78 | // } | ||
79 | // ``` | ||
80 | // -> | ||
81 | // ``` | ||
82 | // trait Trait { | ||
83 | // Type X; | ||
84 | // fn foo(&self); | ||
85 | // fn bar(&self) {} | ||
86 | // } | ||
87 | // | ||
88 | // impl Trait for () { | ||
89 | // Type X = (); | ||
90 | // fn foo(&self) {} | ||
91 | // | ||
92 | // $0fn bar(&self) {} | ||
93 | // } | ||
94 | // ``` | ||
95 | pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
96 | add_missing_impl_members_inner( | ||
97 | acc, | ||
98 | ctx, | ||
99 | AddMissingImplMembersMode::DefaultMethodsOnly, | ||
100 | "add_impl_default_members", | ||
101 | "Implement default members", | ||
102 | ) | ||
103 | } | ||
104 | |||
105 | fn add_missing_impl_members_inner( | ||
106 | acc: &mut Assists, | ||
107 | ctx: &AssistContext, | ||
108 | mode: AddMissingImplMembersMode, | ||
109 | assist_id: &'static str, | ||
110 | label: &'static str, | ||
111 | ) -> Option<()> { | ||
112 | let _p = profile::span("add_missing_impl_members_inner"); | ||
113 | let impl_def = ctx.find_node_at_offset::<ast::Impl>()?; | ||
114 | let impl_item_list = impl_def.assoc_item_list()?; | ||
115 | |||
116 | let trait_ = resolve_target_trait(&ctx.sema, &impl_def)?; | ||
117 | |||
118 | let def_name = |item: &ast::AssocItem| -> Option<SmolStr> { | ||
119 | match item { | ||
120 | ast::AssocItem::Fn(def) => def.name(), | ||
121 | ast::AssocItem::TypeAlias(def) => def.name(), | ||
122 | ast::AssocItem::Const(def) => def.name(), | ||
123 | ast::AssocItem::MacroCall(_) => None, | ||
124 | } | ||
125 | .map(|it| it.text().clone()) | ||
126 | }; | ||
127 | |||
128 | let missing_items = get_missing_assoc_items(&ctx.sema, &impl_def) | ||
129 | .iter() | ||
130 | .map(|i| match i { | ||
131 | hir::AssocItem::Function(i) => ast::AssocItem::Fn(i.source(ctx.db()).value), | ||
132 | hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(i.source(ctx.db()).value), | ||
133 | hir::AssocItem::Const(i) => ast::AssocItem::Const(i.source(ctx.db()).value), | ||
134 | }) | ||
135 | .filter(|t| def_name(&t).is_some()) | ||
136 | .filter(|t| match t { | ||
137 | ast::AssocItem::Fn(def) => match mode { | ||
138 | AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(), | ||
139 | AddMissingImplMembersMode::NoDefaultMethods => def.body().is_none(), | ||
140 | }, | ||
141 | _ => mode == AddMissingImplMembersMode::NoDefaultMethods, | ||
142 | }) | ||
143 | .collect::<Vec<_>>(); | ||
144 | |||
145 | if missing_items.is_empty() { | ||
146 | return None; | ||
147 | } | ||
148 | |||
149 | let target = impl_def.syntax().text_range(); | ||
150 | acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| { | ||
151 | let n_existing_items = impl_item_list.assoc_items().count(); | ||
152 | let source_scope = ctx.sema.scope_for_def(trait_); | ||
153 | let target_scope = ctx.sema.scope(impl_item_list.syntax()); | ||
154 | let ast_transform = QualifyPaths::new(&target_scope, &source_scope) | ||
155 | .or(SubstituteTypeParams::for_trait_impl(&source_scope, trait_, impl_def)); | ||
156 | let items = missing_items | ||
157 | .into_iter() | ||
158 | .map(|it| ast_transform::apply(&*ast_transform, it)) | ||
159 | .map(|it| match it { | ||
160 | ast::AssocItem::Fn(def) => ast::AssocItem::Fn(add_body(def)), | ||
161 | ast::AssocItem::TypeAlias(def) => ast::AssocItem::TypeAlias(def.remove_bounds()), | ||
162 | _ => it, | ||
163 | }) | ||
164 | .map(|it| edit::remove_attrs_and_docs(&it)); | ||
165 | let new_impl_item_list = impl_item_list.append_items(items); | ||
166 | let first_new_item = new_impl_item_list.assoc_items().nth(n_existing_items).unwrap(); | ||
167 | |||
168 | let original_range = impl_item_list.syntax().text_range(); | ||
169 | match ctx.config.snippet_cap { | ||
170 | None => builder.replace(original_range, new_impl_item_list.to_string()), | ||
171 | Some(cap) => { | ||
172 | let mut cursor = Cursor::Before(first_new_item.syntax()); | ||
173 | let placeholder; | ||
174 | if let ast::AssocItem::Fn(func) = &first_new_item { | ||
175 | if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) { | ||
176 | if m.syntax().text() == "todo!()" { | ||
177 | placeholder = m; | ||
178 | cursor = Cursor::Replace(placeholder.syntax()); | ||
179 | } | ||
180 | } | ||
181 | } | ||
182 | builder.replace_snippet( | ||
183 | cap, | ||
184 | original_range, | ||
185 | render_snippet(cap, new_impl_item_list.syntax(), cursor), | ||
186 | ) | ||
187 | } | ||
188 | }; | ||
189 | }) | ||
190 | } | ||
191 | |||
192 | fn add_body(fn_def: ast::Fn) -> ast::Fn { | ||
193 | if fn_def.body().is_some() { | ||
194 | return fn_def; | ||
195 | } | ||
196 | let body = make::block_expr(None, Some(make::expr_todo())).indent(IndentLevel(1)); | ||
197 | fn_def.with_body(body) | ||
198 | } | ||
199 | |||
200 | #[cfg(test)] | ||
201 | mod tests { | ||
202 | use crate::tests::{check_assist, check_assist_not_applicable}; | ||
203 | |||
204 | use super::*; | ||
205 | |||
206 | #[test] | ||
207 | fn test_add_missing_impl_members() { | ||
208 | check_assist( | ||
209 | add_missing_impl_members, | ||
210 | r#" | ||
211 | trait Foo { | ||
212 | type Output; | ||
213 | |||
214 | const CONST: usize = 42; | ||
215 | |||
216 | fn foo(&self); | ||
217 | fn bar(&self); | ||
218 | fn baz(&self); | ||
219 | } | ||
220 | |||
221 | struct S; | ||
222 | |||
223 | impl Foo for S { | ||
224 | fn bar(&self) {} | ||
225 | <|> | ||
226 | }"#, | ||
227 | r#" | ||
228 | trait Foo { | ||
229 | type Output; | ||
230 | |||
231 | const CONST: usize = 42; | ||
232 | |||
233 | fn foo(&self); | ||
234 | fn bar(&self); | ||
235 | fn baz(&self); | ||
236 | } | ||
237 | |||
238 | struct S; | ||
239 | |||
240 | impl Foo for S { | ||
241 | fn bar(&self) {} | ||
242 | |||
243 | $0type Output; | ||
244 | |||
245 | const CONST: usize = 42; | ||
246 | |||
247 | fn foo(&self) { | ||
248 | todo!() | ||
249 | } | ||
250 | |||
251 | fn baz(&self) { | ||
252 | todo!() | ||
253 | } | ||
254 | }"#, | ||
255 | ); | ||
256 | } | ||
257 | |||
258 | #[test] | ||
259 | fn test_copied_overriden_members() { | ||
260 | check_assist( | ||
261 | add_missing_impl_members, | ||
262 | r#" | ||
263 | trait Foo { | ||
264 | fn foo(&self); | ||
265 | fn bar(&self) -> bool { true } | ||
266 | fn baz(&self) -> u32 { 42 } | ||
267 | } | ||
268 | |||
269 | struct S; | ||
270 | |||
271 | impl Foo for S { | ||
272 | fn bar(&self) {} | ||
273 | <|> | ||
274 | }"#, | ||
275 | r#" | ||
276 | trait Foo { | ||
277 | fn foo(&self); | ||
278 | fn bar(&self) -> bool { true } | ||
279 | fn baz(&self) -> u32 { 42 } | ||
280 | } | ||
281 | |||
282 | struct S; | ||
283 | |||
284 | impl Foo for S { | ||
285 | fn bar(&self) {} | ||
286 | |||
287 | fn foo(&self) { | ||
288 | ${0:todo!()} | ||
289 | } | ||
290 | }"#, | ||
291 | ); | ||
292 | } | ||
293 | |||
294 | #[test] | ||
295 | fn test_empty_impl_def() { | ||
296 | check_assist( | ||
297 | add_missing_impl_members, | ||
298 | r#" | ||
299 | trait Foo { fn foo(&self); } | ||
300 | struct S; | ||
301 | impl Foo for S { <|> }"#, | ||
302 | r#" | ||
303 | trait Foo { fn foo(&self); } | ||
304 | struct S; | ||
305 | impl Foo for S { | ||
306 | fn foo(&self) { | ||
307 | ${0:todo!()} | ||
308 | } | ||
309 | }"#, | ||
310 | ); | ||
311 | } | ||
312 | |||
313 | #[test] | ||
314 | fn fill_in_type_params_1() { | ||
315 | check_assist( | ||
316 | add_missing_impl_members, | ||
317 | r#" | ||
318 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
319 | struct S; | ||
320 | impl Foo<u32> for S { <|> }"#, | ||
321 | r#" | ||
322 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
323 | struct S; | ||
324 | impl Foo<u32> for S { | ||
325 | fn foo(&self, t: u32) -> &u32 { | ||
326 | ${0:todo!()} | ||
327 | } | ||
328 | }"#, | ||
329 | ); | ||
330 | } | ||
331 | |||
332 | #[test] | ||
333 | fn fill_in_type_params_2() { | ||
334 | check_assist( | ||
335 | add_missing_impl_members, | ||
336 | r#" | ||
337 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
338 | struct S; | ||
339 | impl<U> Foo<U> for S { <|> }"#, | ||
340 | r#" | ||
341 | trait Foo<T> { fn foo(&self, t: T) -> &T; } | ||
342 | struct S; | ||
343 | impl<U> Foo<U> for S { | ||
344 | fn foo(&self, t: U) -> &U { | ||
345 | ${0:todo!()} | ||
346 | } | ||
347 | }"#, | ||
348 | ); | ||
349 | } | ||
350 | |||
351 | #[test] | ||
352 | fn test_cursor_after_empty_impl_def() { | ||
353 | check_assist( | ||
354 | add_missing_impl_members, | ||
355 | r#" | ||
356 | trait Foo { fn foo(&self); } | ||
357 | struct S; | ||
358 | impl Foo for S {}<|>"#, | ||
359 | r#" | ||
360 | trait Foo { fn foo(&self); } | ||
361 | struct S; | ||
362 | impl Foo for S { | ||
363 | fn foo(&self) { | ||
364 | ${0:todo!()} | ||
365 | } | ||
366 | }"#, | ||
367 | ) | ||
368 | } | ||
369 | |||
370 | #[test] | ||
371 | fn test_qualify_path_1() { | ||
372 | check_assist( | ||
373 | add_missing_impl_members, | ||
374 | r#" | ||
375 | mod foo { | ||
376 | pub struct Bar; | ||
377 | trait Foo { fn foo(&self, bar: Bar); } | ||
378 | } | ||
379 | struct S; | ||
380 | impl foo::Foo for S { <|> }"#, | ||
381 | r#" | ||
382 | mod foo { | ||
383 | pub struct Bar; | ||
384 | trait Foo { fn foo(&self, bar: Bar); } | ||
385 | } | ||
386 | struct S; | ||
387 | impl foo::Foo for S { | ||
388 | fn foo(&self, bar: foo::Bar) { | ||
389 | ${0:todo!()} | ||
390 | } | ||
391 | }"#, | ||
392 | ); | ||
393 | } | ||
394 | |||
395 | #[test] | ||
396 | fn test_qualify_path_generic() { | ||
397 | check_assist( | ||
398 | add_missing_impl_members, | ||
399 | r#" | ||
400 | mod foo { | ||
401 | pub struct Bar<T>; | ||
402 | trait Foo { fn foo(&self, bar: Bar<u32>); } | ||
403 | } | ||
404 | struct S; | ||
405 | impl foo::Foo for S { <|> }"#, | ||
406 | r#" | ||
407 | mod foo { | ||
408 | pub struct Bar<T>; | ||
409 | trait Foo { fn foo(&self, bar: Bar<u32>); } | ||
410 | } | ||
411 | struct S; | ||
412 | impl foo::Foo for S { | ||
413 | fn foo(&self, bar: foo::Bar<u32>) { | ||
414 | ${0:todo!()} | ||
415 | } | ||
416 | }"#, | ||
417 | ); | ||
418 | } | ||
419 | |||
420 | #[test] | ||
421 | fn test_qualify_path_and_substitute_param() { | ||
422 | check_assist( | ||
423 | add_missing_impl_members, | ||
424 | r#" | ||
425 | mod foo { | ||
426 | pub struct Bar<T>; | ||
427 | trait Foo<T> { fn foo(&self, bar: Bar<T>); } | ||
428 | } | ||
429 | struct S; | ||
430 | impl foo::Foo<u32> for S { <|> }"#, | ||
431 | r#" | ||
432 | mod foo { | ||
433 | pub struct Bar<T>; | ||
434 | trait Foo<T> { fn foo(&self, bar: Bar<T>); } | ||
435 | } | ||
436 | struct S; | ||
437 | impl foo::Foo<u32> for S { | ||
438 | fn foo(&self, bar: foo::Bar<u32>) { | ||
439 | ${0:todo!()} | ||
440 | } | ||
441 | }"#, | ||
442 | ); | ||
443 | } | ||
444 | |||
445 | #[test] | ||
446 | fn test_substitute_param_no_qualify() { | ||
447 | // when substituting params, the substituted param should not be qualified! | ||
448 | check_assist( | ||
449 | add_missing_impl_members, | ||
450 | r#" | ||
451 | mod foo { | ||
452 | trait Foo<T> { fn foo(&self, bar: T); } | ||
453 | pub struct Param; | ||
454 | } | ||
455 | struct Param; | ||
456 | struct S; | ||
457 | impl foo::Foo<Param> for S { <|> }"#, | ||
458 | r#" | ||
459 | mod foo { | ||
460 | trait Foo<T> { fn foo(&self, bar: T); } | ||
461 | pub struct Param; | ||
462 | } | ||
463 | struct Param; | ||
464 | struct S; | ||
465 | impl foo::Foo<Param> for S { | ||
466 | fn foo(&self, bar: Param) { | ||
467 | ${0:todo!()} | ||
468 | } | ||
469 | }"#, | ||
470 | ); | ||
471 | } | ||
472 | |||
473 | #[test] | ||
474 | fn test_qualify_path_associated_item() { | ||
475 | check_assist( | ||
476 | add_missing_impl_members, | ||
477 | r#" | ||
478 | mod foo { | ||
479 | pub struct Bar<T>; | ||
480 | impl Bar<T> { type Assoc = u32; } | ||
481 | trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); } | ||
482 | } | ||
483 | struct S; | ||
484 | impl foo::Foo for S { <|> }"#, | ||
485 | r#" | ||
486 | mod foo { | ||
487 | pub struct Bar<T>; | ||
488 | impl Bar<T> { type Assoc = u32; } | ||
489 | trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); } | ||
490 | } | ||
491 | struct S; | ||
492 | impl foo::Foo for S { | ||
493 | fn foo(&self, bar: foo::Bar<u32>::Assoc) { | ||
494 | ${0:todo!()} | ||
495 | } | ||
496 | }"#, | ||
497 | ); | ||
498 | } | ||
499 | |||
500 | #[test] | ||
501 | fn test_qualify_path_nested() { | ||
502 | check_assist( | ||
503 | add_missing_impl_members, | ||
504 | r#" | ||
505 | mod foo { | ||
506 | pub struct Bar<T>; | ||
507 | pub struct Baz; | ||
508 | trait Foo { fn foo(&self, bar: Bar<Baz>); } | ||
509 | } | ||
510 | struct S; | ||
511 | impl foo::Foo for S { <|> }"#, | ||
512 | r#" | ||
513 | mod foo { | ||
514 | pub struct Bar<T>; | ||
515 | pub struct Baz; | ||
516 | trait Foo { fn foo(&self, bar: Bar<Baz>); } | ||
517 | } | ||
518 | struct S; | ||
519 | impl foo::Foo for S { | ||
520 | fn foo(&self, bar: foo::Bar<foo::Baz>) { | ||
521 | ${0:todo!()} | ||
522 | } | ||
523 | }"#, | ||
524 | ); | ||
525 | } | ||
526 | |||
527 | #[test] | ||
528 | fn test_qualify_path_fn_trait_notation() { | ||
529 | check_assist( | ||
530 | add_missing_impl_members, | ||
531 | r#" | ||
532 | mod foo { | ||
533 | pub trait Fn<Args> { type Output; } | ||
534 | trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } | ||
535 | } | ||
536 | struct S; | ||
537 | impl foo::Foo for S { <|> }"#, | ||
538 | r#" | ||
539 | mod foo { | ||
540 | pub trait Fn<Args> { type Output; } | ||
541 | trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } | ||
542 | } | ||
543 | struct S; | ||
544 | impl foo::Foo for S { | ||
545 | fn foo(&self, bar: dyn Fn(u32) -> i32) { | ||
546 | ${0:todo!()} | ||
547 | } | ||
548 | }"#, | ||
549 | ); | ||
550 | } | ||
551 | |||
552 | #[test] | ||
553 | fn test_empty_trait() { | ||
554 | check_assist_not_applicable( | ||
555 | add_missing_impl_members, | ||
556 | r#" | ||
557 | trait Foo; | ||
558 | struct S; | ||
559 | impl Foo for S { <|> }"#, | ||
560 | ) | ||
561 | } | ||
562 | |||
563 | #[test] | ||
564 | fn test_ignore_unnamed_trait_members_and_default_methods() { | ||
565 | check_assist_not_applicable( | ||
566 | add_missing_impl_members, | ||
567 | r#" | ||
568 | trait Foo { | ||
569 | fn (arg: u32); | ||
570 | fn valid(some: u32) -> bool { false } | ||
571 | } | ||
572 | struct S; | ||
573 | impl Foo for S { <|> }"#, | ||
574 | ) | ||
575 | } | ||
576 | |||
577 | #[test] | ||
578 | fn test_with_docstring_and_attrs() { | ||
579 | check_assist( | ||
580 | add_missing_impl_members, | ||
581 | r#" | ||
582 | #[doc(alias = "test alias")] | ||
583 | trait Foo { | ||
584 | /// doc string | ||
585 | type Output; | ||
586 | |||
587 | #[must_use] | ||
588 | fn foo(&self); | ||
589 | } | ||
590 | struct S; | ||
591 | impl Foo for S {}<|>"#, | ||
592 | r#" | ||
593 | #[doc(alias = "test alias")] | ||
594 | trait Foo { | ||
595 | /// doc string | ||
596 | type Output; | ||
597 | |||
598 | #[must_use] | ||
599 | fn foo(&self); | ||
600 | } | ||
601 | struct S; | ||
602 | impl Foo for S { | ||
603 | $0type Output; | ||
604 | |||
605 | fn foo(&self) { | ||
606 | todo!() | ||
607 | } | ||
608 | }"#, | ||
609 | ) | ||
610 | } | ||
611 | |||
612 | #[test] | ||
613 | fn test_default_methods() { | ||
614 | check_assist( | ||
615 | add_missing_default_members, | ||
616 | r#" | ||
617 | trait Foo { | ||
618 | type Output; | ||
619 | |||
620 | const CONST: usize = 42; | ||
621 | |||
622 | fn valid(some: u32) -> bool { false } | ||
623 | fn foo(some: u32) -> bool; | ||
624 | } | ||
625 | struct S; | ||
626 | impl Foo for S { <|> }"#, | ||
627 | r#" | ||
628 | trait Foo { | ||
629 | type Output; | ||
630 | |||
631 | const CONST: usize = 42; | ||
632 | |||
633 | fn valid(some: u32) -> bool { false } | ||
634 | fn foo(some: u32) -> bool; | ||
635 | } | ||
636 | struct S; | ||
637 | impl Foo for S { | ||
638 | $0fn valid(some: u32) -> bool { false } | ||
639 | }"#, | ||
640 | ) | ||
641 | } | ||
642 | |||
643 | #[test] | ||
644 | fn test_generic_single_default_parameter() { | ||
645 | check_assist( | ||
646 | add_missing_impl_members, | ||
647 | r#" | ||
648 | trait Foo<T = Self> { | ||
649 | fn bar(&self, other: &T); | ||
650 | } | ||
651 | |||
652 | struct S; | ||
653 | impl Foo for S { <|> }"#, | ||
654 | r#" | ||
655 | trait Foo<T = Self> { | ||
656 | fn bar(&self, other: &T); | ||
657 | } | ||
658 | |||
659 | struct S; | ||
660 | impl Foo for S { | ||
661 | fn bar(&self, other: &Self) { | ||
662 | ${0:todo!()} | ||
663 | } | ||
664 | }"#, | ||
665 | ) | ||
666 | } | ||
667 | |||
668 | #[test] | ||
669 | fn test_generic_default_parameter_is_second() { | ||
670 | check_assist( | ||
671 | add_missing_impl_members, | ||
672 | r#" | ||
673 | trait Foo<T1, T2 = Self> { | ||
674 | fn bar(&self, this: &T1, that: &T2); | ||
675 | } | ||
676 | |||
677 | struct S<T>; | ||
678 | impl Foo<T> for S<T> { <|> }"#, | ||
679 | r#" | ||
680 | trait Foo<T1, T2 = Self> { | ||
681 | fn bar(&self, this: &T1, that: &T2); | ||
682 | } | ||
683 | |||
684 | struct S<T>; | ||
685 | impl Foo<T> for S<T> { | ||
686 | fn bar(&self, this: &T, that: &Self) { | ||
687 | ${0:todo!()} | ||
688 | } | ||
689 | }"#, | ||
690 | ) | ||
691 | } | ||
692 | |||
693 | #[test] | ||
694 | fn test_assoc_type_bounds_are_removed() { | ||
695 | check_assist( | ||
696 | add_missing_impl_members, | ||
697 | r#" | ||
698 | trait Tr { | ||
699 | type Ty: Copy + 'static; | ||
700 | } | ||
701 | |||
702 | impl Tr for ()<|> { | ||
703 | }"#, | ||
704 | r#" | ||
705 | trait Tr { | ||
706 | type Ty: Copy + 'static; | ||
707 | } | ||
708 | |||
709 | impl Tr for () { | ||
710 | $0type Ty; | ||
711 | }"#, | ||
712 | ) | ||
713 | } | ||
714 | |||
715 | #[test] | ||
716 | fn test_whitespace_fixup_preserves_bad_tokens() { | ||
717 | check_assist( | ||
718 | add_missing_impl_members, | ||
719 | r#" | ||
720 | trait Tr { | ||
721 | fn foo(); | ||
722 | } | ||
723 | |||
724 | impl Tr for ()<|> { | ||
725 | +++ | ||
726 | }"#, | ||
727 | r#" | ||
728 | trait Tr { | ||
729 | fn foo(); | ||
730 | } | ||
731 | |||
732 | impl Tr for () { | ||
733 | fn foo() { | ||
734 | ${0:todo!()} | ||
735 | } | ||
736 | +++ | ||
737 | }"#, | ||
738 | ) | ||
739 | } | ||
740 | |||
741 | #[test] | ||
742 | fn test_whitespace_fixup_preserves_comments() { | ||
743 | check_assist( | ||
744 | add_missing_impl_members, | ||
745 | r#" | ||
746 | trait Tr { | ||
747 | fn foo(); | ||
748 | } | ||
749 | |||
750 | impl Tr for ()<|> { | ||
751 | // very important | ||
752 | }"#, | ||
753 | r#" | ||
754 | trait Tr { | ||
755 | fn foo(); | ||
756 | } | ||
757 | |||
758 | impl Tr for () { | ||
759 | fn foo() { | ||
760 | ${0:todo!()} | ||
761 | } | ||
762 | // very important | ||
763 | }"#, | ||
764 | ) | ||
765 | } | ||
766 | } | ||
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..c4770f336 --- /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::{ | ||