diff options
Diffstat (limited to 'crates/assists/src/assist_context.rs')
-rw-r--r-- | crates/assists/src/assist_context.rs | 293 |
1 files changed, 293 insertions, 0 deletions
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 | } | ||