aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/assist_context.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/assist_context.rs')
-rw-r--r--crates/ra_assists/src/assist_context.rs306
1 files changed, 0 insertions, 306 deletions
diff --git a/crates/ra_assists/src/assist_context.rs b/crates/ra_assists/src/assist_context.rs
deleted file mode 100644
index afd3fd4b9..000000000
--- a/crates/ra_assists/src/assist_context.rs
+++ /dev/null
@@ -1,306 +0,0 @@
1//! See `AssistContext`
2
3use std::mem;
4
5use algo::find_covering_element;
6use hir::Semantics;
7use ra_db::{FileId, FileRange};
8use ra_fmt::{leading_indent, reindent};
9use ra_ide_db::{
10 source_change::{SourceChange, SourceFileEdit},
11 RootDatabase,
12};
13use ra_syntax::{
14 algo::{self, find_node_at_offset, SyntaxRewriter},
15 AstNode, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize,
16 TokenAtOffset,
17};
18use ra_text_edit::TextEditBuilder;
19
20use 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 :-)
55pub(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
62impl<'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
106pub(crate) struct Assists {
107 resolve: bool,
108 file: FileId,
109 buf: Vec<(Assist, Option<SourceChange>)>,
110 allowed: Option<Vec<AssistKind>>,
111}
112
113impl Assists {
114 pub(crate) fn new_resolved(ctx: &AssistContext) -> Assists {
115 Assists {
116 resolve: true,
117 file: ctx.frange.file_id,
118 buf: Vec::new(),
119 allowed: ctx.config.allowed.clone(),
120 }
121 }
122
123 pub(crate) fn new_unresolved(ctx: &AssistContext) -> Assists {
124 Assists {
125 resolve: false,
126 file: ctx.frange.file_id,
127 buf: Vec::new(),
128 allowed: ctx.config.allowed.clone(),
129 }
130 }
131
132 pub(crate) fn finish_unresolved(self) -> Vec<Assist> {
133 assert!(!self.resolve);
134 self.finish()
135 .into_iter()
136 .map(|(label, edit)| {
137 assert!(edit.is_none());
138 label
139 })
140 .collect()
141 }
142
143 pub(crate) fn finish_resolved(self) -> Vec<ResolvedAssist> {
144 assert!(self.resolve);
145 self.finish()
146 .into_iter()
147 .map(|(label, edit)| ResolvedAssist { assist: label, source_change: edit.unwrap() })
148 .collect()
149 }
150
151 pub(crate) fn add(
152 &mut self,
153 id: AssistId,
154 label: impl Into<String>,
155 target: TextRange,
156 f: impl FnOnce(&mut AssistBuilder),
157 ) -> Option<()> {
158 if !self.is_allowed(&id) {
159 return None;
160 }
161 let label = Assist::new(id, label.into(), None, target);
162 self.add_impl(label, f)
163 }
164
165 pub(crate) fn add_group(
166 &mut self,
167 group: &GroupLabel,
168 id: AssistId,
169 label: impl Into<String>,
170 target: TextRange,
171 f: impl FnOnce(&mut AssistBuilder),
172 ) -> Option<()> {
173 if !self.is_allowed(&id) {
174 return None;
175 }
176
177 let label = Assist::new(id, label.into(), Some(group.clone()), target);
178 self.add_impl(label, f)
179 }
180
181 fn add_impl(&mut self, label: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> {
182 let source_change = if self.resolve {
183 let mut builder = AssistBuilder::new(self.file);
184 f(&mut builder);
185 Some(builder.finish())
186 } else {
187 None
188 };
189
190 self.buf.push((label, source_change));
191 Some(())
192 }
193
194 fn finish(mut self) -> Vec<(Assist, Option<SourceChange>)> {
195 self.buf.sort_by_key(|(label, _edit)| label.target.len());
196 self.buf
197 }
198
199 fn is_allowed(&self, id: &AssistId) -> bool {
200 match &self.allowed {
201 Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
202 None => true,
203 }
204 }
205}
206
207pub(crate) struct AssistBuilder {
208 edit: TextEditBuilder,
209 file_id: FileId,
210 is_snippet: bool,
211 change: SourceChange,
212}
213
214impl AssistBuilder {
215 pub(crate) fn new(file_id: FileId) -> AssistBuilder {
216 AssistBuilder {
217 edit: TextEditBuilder::default(),
218 file_id,
219 is_snippet: false,
220 change: SourceChange::default(),
221 }
222 }
223
224 pub(crate) fn edit_file(&mut self, file_id: FileId) {
225 self.file_id = file_id;
226 }
227
228 fn commit(&mut self) {
229 let edit = mem::take(&mut self.edit).finish();
230 if !edit.is_empty() {
231 let new_edit = SourceFileEdit { file_id: self.file_id, edit };
232 assert!(!self.change.source_file_edits.iter().any(|it| it.file_id == new_edit.file_id));
233 self.change.source_file_edits.push(new_edit);
234 }
235 }
236
237 /// Remove specified `range` of text.
238 pub(crate) fn delete(&mut self, range: TextRange) {
239 self.edit.delete(range)
240 }
241 /// Append specified `text` at the given `offset`
242 pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
243 self.edit.insert(offset, text.into())
244 }
245 /// Append specified `snippet` at the given `offset`
246 pub(crate) fn insert_snippet(
247 &mut self,
248 _cap: SnippetCap,
249 offset: TextSize,
250 snippet: impl Into<String>,
251 ) {
252 self.is_snippet = true;
253 self.insert(offset, snippet);
254 }
255 /// Replaces specified `range` of text with a given string.
256 pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
257 self.edit.replace(range, replace_with.into())
258 }
259 /// Replaces specified `range` of text with a given `snippet`.
260 pub(crate) fn replace_snippet(
261 &mut self,
262 _cap: SnippetCap,
263 range: TextRange,
264 snippet: impl Into<String>,
265 ) {
266 self.is_snippet = true;
267 self.replace(range, snippet);
268 }
269 pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
270 algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
271 }
272 /// Replaces specified `node` of text with a given string, reindenting the
273 /// string to maintain `node`'s existing indent.
274 // FIXME: remove in favor of ra_syntax::edit::IndentLevel::increase_indent
275 pub(crate) fn replace_node_and_indent(
276 &mut self,
277 node: &SyntaxNode,
278 replace_with: impl Into<String>,
279 ) {
280 let mut replace_with = replace_with.into();
281 if let Some(indent) = leading_indent(node) {
282 replace_with = reindent(&replace_with, &indent)
283 }
284 self.replace(node.text_range(), replace_with)
285 }
286 pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
287 let node = rewriter.rewrite_root().unwrap();
288 let new = rewriter.rewrite(&node);
289 algo::diff(&node, &new).into_text_edit(&mut self.edit);
290 }
291
292 // FIXME: kill this API
293 /// Get access to the raw `TextEditBuilder`.
294 pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder {
295 &mut self.edit
296 }
297
298 fn finish(mut self) -> SourceChange {
299 self.commit();
300 let mut change = mem::take(&mut self.change);
301 if self.is_snippet {
302 change.is_snippet = true;
303 }
304 change
305 }
306}