diff options
Diffstat (limited to 'crates/ra_assists/src/assist_context.rs')
-rw-r--r-- | crates/ra_assists/src/assist_context.rs | 234 |
1 files changed, 234 insertions, 0 deletions
diff --git a/crates/ra_assists/src/assist_context.rs b/crates/ra_assists/src/assist_context.rs new file mode 100644 index 000000000..203ad1273 --- /dev/null +++ b/crates/ra_assists/src/assist_context.rs | |||
@@ -0,0 +1,234 @@ | |||
1 | //! See `AssistContext` | ||
2 | |||
3 | use algo::find_covering_element; | ||
4 | use hir::Semantics; | ||
5 | use ra_db::{FileId, FileRange}; | ||
6 | use ra_fmt::{leading_indent, reindent}; | ||
7 | use ra_ide_db::{ | ||
8 | source_change::{SingleFileChange, SourceChange}, | ||
9 | RootDatabase, | ||
10 | }; | ||
11 | use ra_syntax::{ | ||
12 | algo::{self, find_node_at_offset, SyntaxRewriter}, | ||
13 | AstNode, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize, | ||
14 | TokenAtOffset, | ||
15 | }; | ||
16 | use ra_text_edit::TextEditBuilder; | ||
17 | |||
18 | use crate::{AssistId, AssistLabel, GroupLabel, ResolvedAssist}; | ||
19 | |||
20 | /// `AssistContext` allows to apply an assist or check if it could be applied. | ||
21 | /// | ||
22 | /// Assists use a somewhat over-engineered approach, given the current needs. | ||
23 | /// The assists workflow consists of two phases. In the first phase, a user asks | ||
24 | /// for the list of available assists. In the second phase, the user picks a | ||
25 | /// particular assist and it gets applied. | ||
26 | /// | ||
27 | /// There are two peculiarities here: | ||
28 | /// | ||
29 | /// * first, we ideally avoid computing more things then necessary to answer "is | ||
30 | /// assist applicable" in the first phase. | ||
31 | /// * second, when we are applying assist, we don't have a guarantee that there | ||
32 | /// weren't any changes between the point when user asked for assists and when | ||
33 | /// they applied a particular assist. So, when applying assist, we need to do | ||
34 | /// all the checks from scratch. | ||
35 | /// | ||
36 | /// To avoid repeating the same code twice for both "check" and "apply" | ||
37 | /// functions, we use an approach reminiscent of that of Django's function based | ||
38 | /// views dealing with forms. Each assist receives a runtime parameter, | ||
39 | /// `resolve`. It first check if an edit is applicable (potentially computing | ||
40 | /// info required to compute the actual edit). If it is applicable, and | ||
41 | /// `resolve` is `true`, it then computes the actual edit. | ||
42 | /// | ||
43 | /// So, to implement the original assists workflow, we can first apply each edit | ||
44 | /// with `resolve = false`, and then applying the selected edit again, with | ||
45 | /// `resolve = true` this time. | ||
46 | /// | ||
47 | /// Note, however, that we don't actually use such two-phase logic at the | ||
48 | /// moment, because the LSP API is pretty awkward in this place, and it's much | ||
49 | /// easier to just compute the edit eagerly :-) | ||
50 | pub(crate) struct AssistContext<'a> { | ||
51 | pub(crate) sema: Semantics<'a, RootDatabase>, | ||
52 | pub(super) db: &'a RootDatabase, | ||
53 | pub(crate) frange: FileRange, | ||
54 | source_file: SourceFile, | ||
55 | } | ||
56 | |||
57 | impl<'a> AssistContext<'a> { | ||
58 | pub fn new(sema: Semantics<'a, RootDatabase>, frange: FileRange) -> AssistContext<'a> { | ||
59 | let source_file = sema.parse(frange.file_id); | ||
60 | let db = sema.db; | ||
61 | AssistContext { sema, db, frange, source_file } | ||
62 | } | ||
63 | |||
64 | // NB, this ignores active selection. | ||
65 | pub(crate) fn offset(&self) -> TextSize { | ||
66 | self.frange.range.start() | ||
67 | } | ||
68 | |||
69 | pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> { | ||
70 | self.source_file.syntax().token_at_offset(self.offset()) | ||
71 | } | ||
72 | pub(crate) fn find_token_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> { | ||
73 | self.token_at_offset().find(|it| it.kind() == kind) | ||
74 | } | ||
75 | pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> { | ||
76 | find_node_at_offset(self.source_file.syntax(), self.offset()) | ||
77 | } | ||
78 | pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> { | ||
79 | self.sema | ||
80 | .find_node_at_offset_with_descend(self.source_file.syntax(), self.frange.range.start()) | ||
81 | } | ||
82 | pub(crate) fn covering_element(&self) -> SyntaxElement { | ||
83 | find_covering_element(self.source_file.syntax(), self.frange.range) | ||
84 | } | ||
85 | // FIXME: remove | ||
86 | pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement { | ||
87 | find_covering_element(self.source_file.syntax(), range) | ||
88 | } | ||
89 | } | ||
90 | |||
91 | pub(crate) struct Assists { | ||
92 | resolve: bool, | ||
93 | file: FileId, | ||
94 | buf: Vec<(AssistLabel, Option<SourceChange>)>, | ||
95 | } | ||
96 | |||
97 | impl Assists { | ||
98 | pub(crate) fn new_resolved(ctx: &AssistContext) -> Assists { | ||
99 | Assists { resolve: true, file: ctx.frange.file_id, buf: Vec::new() } | ||
100 | } | ||
101 | pub(crate) fn new_unresolved(ctx: &AssistContext) -> Assists { | ||
102 | Assists { resolve: false, file: ctx.frange.file_id, buf: Vec::new() } | ||
103 | } | ||
104 | |||
105 | pub(crate) fn finish_unresolved(self) -> Vec<AssistLabel> { | ||
106 | assert!(!self.resolve); | ||
107 | self.finish() | ||
108 | .into_iter() | ||
109 | .map(|(label, edit)| { | ||
110 | assert!(edit.is_none()); | ||
111 | label | ||
112 | }) | ||
113 | .collect() | ||
114 | } | ||
115 | |||
116 | pub(crate) fn finish_resolved(self) -> Vec<ResolvedAssist> { | ||
117 | assert!(self.resolve); | ||
118 | self.finish() | ||
119 | .into_iter() | ||
120 | .map(|(label, edit)| ResolvedAssist { label, source_change: edit.unwrap() }) | ||
121 | .collect() | ||
122 | } | ||
123 | |||
124 | pub(crate) fn add( | ||
125 | &mut self, | ||
126 | id: AssistId, | ||
127 | label: impl Into<String>, | ||
128 | target: TextRange, | ||
129 | f: impl FnOnce(&mut AssistBuilder), | ||
130 | ) -> Option<()> { | ||
131 | let label = AssistLabel::new(id, label.into(), None, target); | ||
132 | self.add_impl(label, f) | ||
133 | } | ||
134 | pub(crate) fn add_group( | ||
135 | &mut self, | ||
136 | group: &GroupLabel, | ||
137 | id: AssistId, | ||
138 | label: impl Into<String>, | ||
139 | target: TextRange, | ||
140 | f: impl FnOnce(&mut AssistBuilder), | ||
141 | ) -> Option<()> { | ||
142 | let label = AssistLabel::new(id, label.into(), Some(group.clone()), target); | ||
143 | self.add_impl(label, f) | ||
144 | } | ||
145 | fn add_impl(&mut self, label: AssistLabel, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> { | ||
146 | let change_label = label.label.clone(); | ||
147 | let source_change = if self.resolve { | ||
148 | let mut builder = AssistBuilder::new(self.file); | ||
149 | f(&mut builder); | ||
150 | Some(builder.finish(change_label)) | ||
151 | } else { | ||
152 | None | ||
153 | }; | ||
154 | |||
155 | self.buf.push((label, source_change)); | ||
156 | Some(()) | ||
157 | } | ||
158 | |||
159 | fn finish(mut self) -> Vec<(AssistLabel, Option<SourceChange>)> { | ||
160 | self.buf.sort_by_key(|(label, _edit)| label.target.len()); | ||
161 | self.buf | ||
162 | } | ||
163 | } | ||
164 | |||
165 | pub(crate) struct AssistBuilder { | ||
166 | edit: TextEditBuilder, | ||
167 | cursor_position: Option<TextSize>, | ||
168 | file: FileId, | ||
169 | } | ||
170 | |||
171 | impl AssistBuilder { | ||
172 | pub(crate) fn new(file: FileId) -> AssistBuilder { | ||
173 | AssistBuilder { edit: TextEditBuilder::default(), cursor_position: None, file } | ||
174 | } | ||
175 | |||
176 | /// Remove specified `range` of text. | ||
177 | pub(crate) fn delete(&mut self, range: TextRange) { | ||
178 | self.edit.delete(range) | ||
179 | } | ||
180 | /// Append specified `text` at the given `offset` | ||
181 | pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) { | ||
182 | self.edit.insert(offset, text.into()) | ||
183 | } | ||
184 | /// Replaces specified `range` of text with a given string. | ||
185 | pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) { | ||
186 | self.edit.replace(range, replace_with.into()) | ||
187 | } | ||
188 | pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) { | ||
189 | algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit) | ||
190 | } | ||
191 | /// Replaces specified `node` of text with a given string, reindenting the | ||
192 | /// string to maintain `node`'s existing indent. | ||
193 | // FIXME: remove in favor of ra_syntax::edit::IndentLevel::increase_indent | ||
194 | pub(crate) fn replace_node_and_indent( | ||
195 | &mut self, | ||
196 | node: &SyntaxNode, | ||
197 | replace_with: impl Into<String>, | ||
198 | ) { | ||
199 | let mut replace_with = replace_with.into(); | ||
200 | if let Some(indent) = leading_indent(node) { | ||
201 | replace_with = reindent(&replace_with, &indent) | ||
202 | } | ||
203 | self.replace(node.text_range(), replace_with) | ||
204 | } | ||
205 | pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) { | ||
206 | let node = rewriter.rewrite_root().unwrap(); | ||
207 | let new = rewriter.rewrite(&node); | ||
208 | algo::diff(&node, &new).into_text_edit(&mut self.edit) | ||
209 | } | ||
210 | |||
211 | /// Specify desired position of the cursor after the assist is applied. | ||
212 | pub(crate) fn set_cursor(&mut self, offset: TextSize) { | ||
213 | self.cursor_position = Some(offset) | ||
214 | } | ||
215 | // FIXME: better API | ||
216 | pub(crate) fn set_file(&mut self, assist_file: FileId) { | ||
217 | self.file = assist_file; | ||
218 | } | ||
219 | |||
220 | // FIXME: kill this API | ||
221 | /// Get access to the raw `TextEditBuilder`. | ||
222 | pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder { | ||
223 | &mut self.edit | ||
224 | } | ||
225 | |||
226 | fn finish(self, change_label: String) -> SourceChange { | ||
227 | let edit = self.edit.finish(); | ||
228 | if edit.is_empty() && self.cursor_position.is_none() { | ||
229 | panic!("Only call `add_assist` if the assist can be applied") | ||
230 | } | ||
231 | SingleFileChange { label: change_label, edit, cursor_position: self.cursor_position } | ||
232 | .into_source_change(self.file) | ||
233 | } | ||
234 | } | ||