diff options
Diffstat (limited to 'crates/ra_assists/src/assist_context.rs')
-rw-r--r-- | crates/ra_assists/src/assist_context.rs | 233 |
1 files changed, 233 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..3085c4330 --- /dev/null +++ b/crates/ra_assists/src/assist_context.rs | |||
@@ -0,0 +1,233 @@ | |||
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::{Assist, AssistId, 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.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset()) | ||
80 | } | ||
81 | pub(crate) fn covering_element(&self) -> SyntaxElement { | ||
82 | find_covering_element(self.source_file.syntax(), self.frange.range) | ||
83 | } | ||
84 | // FIXME: remove | ||
85 | pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement { | ||
86 | find_covering_element(self.source_file.syntax(), range) | ||
87 | } | ||
88 | } | ||
89 | |||
90 | pub(crate) struct Assists { | ||
91 | resolve: bool, | ||
92 | file: FileId, | ||
93 | buf: Vec<(Assist, Option<SourceChange>)>, | ||
94 | } | ||
95 | |||
96 | impl Assists { | ||
97 | pub(crate) fn new_resolved(ctx: &AssistContext) -> Assists { | ||
98 | Assists { resolve: true, file: ctx.frange.file_id, buf: Vec::new() } | ||
99 | } | ||
100 | pub(crate) fn new_unresolved(ctx: &AssistContext) -> Assists { | ||
101 | Assists { resolve: false, file: ctx.frange.file_id, buf: Vec::new() } | ||
102 | } | ||
103 | |||
104 | pub(crate) fn finish_unresolved(self) -> Vec<Assist> { | ||
105 | assert!(!self.resolve); | ||
106 | self.finish() | ||
107 | .into_iter() | ||
108 | .map(|(label, edit)| { | ||
109 | assert!(edit.is_none()); | ||
110 | label | ||
111 | }) | ||
112 | .collect() | ||
113 | } | ||
114 | |||
115 | pub(crate) fn finish_resolved(self) -> Vec<ResolvedAssist> { | ||
116 | assert!(self.resolve); | ||
117 | self.finish() | ||
118 | .into_iter() | ||
119 | .map(|(label, edit)| ResolvedAssist { assist: label, source_change: edit.unwrap() }) | ||
120 | .collect() | ||
121 | } | ||
122 | |||
123 | pub(crate) fn add( | ||
124 | &mut self, | ||
125 | id: AssistId, | ||
126 | label: impl Into<String>, | ||
127 | target: TextRange, | ||
128 | f: impl FnOnce(&mut AssistBuilder), | ||
129 | ) -> Option<()> { | ||
130 | let label = Assist::new(id, label.into(), None, target); | ||
131 | self.add_impl(label, f) | ||
132 | } | ||
133 | pub(crate) fn add_group( | ||
134 | &mut self, | ||
135 | group: &GroupLabel, | ||
136 | id: AssistId, | ||
137 | label: impl Into<String>, | ||
138 | target: TextRange, | ||
139 | f: impl FnOnce(&mut AssistBuilder), | ||
140 | ) -> Option<()> { | ||
141 | let label = Assist::new(id, label.into(), Some(group.clone()), target); | ||
142 | self.add_impl(label, f) | ||
143 | } | ||
144 | fn add_impl(&mut self, label: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> { | ||
145 | let change_label = label.label.clone(); | ||
146 | let source_change = if self.resolve { | ||
147 | let mut builder = AssistBuilder::new(self.file); | ||
148 | f(&mut builder); | ||
149 | Some(builder.finish(change_label)) | ||
150 | } else { | ||
151 | None | ||
152 | }; | ||
153 | |||
154 | self.buf.push((label, source_change)); | ||
155 | Some(()) | ||
156 | } | ||
157 | |||
158 | fn finish(mut self) -> Vec<(Assist, Option<SourceChange>)> { | ||
159 | self.buf.sort_by_key(|(label, _edit)| label.target.len()); | ||
160 | self.buf | ||
161 | } | ||
162 | } | ||
163 | |||
164 | pub(crate) struct AssistBuilder { | ||
165 | edit: TextEditBuilder, | ||
166 | cursor_position: Option<TextSize>, | ||
167 | file: FileId, | ||
168 | } | ||
169 | |||
170 | impl AssistBuilder { | ||
171 | pub(crate) fn new(file: FileId) -> AssistBuilder { | ||
172 | AssistBuilder { edit: TextEditBuilder::default(), cursor_position: None, file } | ||
173 | } | ||
174 | |||
175 | /// Remove specified `range` of text. | ||
176 | pub(crate) fn delete(&mut self, range: TextRange) { | ||
177 | self.edit.delete(range) | ||
178 | } | ||
179 | /// Append specified `text` at the given `offset` | ||
180 | pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) { | ||
181 | self.edit.insert(offset, text.into()) | ||
182 | } | ||
183 | /// Replaces specified `range` of text with a given string. | ||
184 | pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) { | ||
185 | self.edit.replace(range, replace_with.into()) | ||
186 | } | ||
187 | pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) { | ||
188 | algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit) | ||
189 | } | ||
190 | /// Replaces specified `node` of text with a given string, reindenting the | ||
191 | /// string to maintain `node`'s existing indent. | ||
192 | // FIXME: remove in favor of ra_syntax::edit::IndentLevel::increase_indent | ||
193 | pub(crate) fn replace_node_and_indent( | ||
194 | &mut self, | ||
195 | node: &SyntaxNode, | ||
196 | replace_with: impl Into<String>, | ||
197 | ) { | ||
198 | let mut replace_with = replace_with.into(); | ||
199 | if let Some(indent) = leading_indent(node) { | ||
200 | replace_with = reindent(&replace_with, &indent) | ||
201 | } | ||
202 | self.replace(node.text_range(), replace_with) | ||
203 | } | ||
204 | pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) { | ||
205 | let node = rewriter.rewrite_root().unwrap(); | ||
206 | let new = rewriter.rewrite(&node); | ||
207 | algo::diff(&node, &new).into_text_edit(&mut self.edit) | ||
208 | } | ||
209 | |||
210 | /// Specify desired position of the cursor after the assist is applied. | ||
211 | pub(crate) fn set_cursor(&mut self, offset: TextSize) { | ||
212 | self.cursor_position = Some(offset) | ||
213 | } | ||
214 | // FIXME: better API | ||
215 | pub(crate) fn set_file(&mut self, assist_file: FileId) { | ||
216 | self.file = assist_file; | ||
217 | } | ||
218 | |||
219 | // FIXME: kill this API | ||
220 | /// Get access to the raw `TextEditBuilder`. | ||
221 | pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder { | ||
222 | &mut self.edit | ||
223 | } | ||
224 | |||
225 | fn finish(self, change_label: String) -> SourceChange { | ||
226 | let edit = self.edit.finish(); | ||
227 | if edit.is_empty() && self.cursor_position.is_none() { | ||
228 | panic!("Only call `add_assist` if the assist can be applied") | ||
229 | } | ||
230 | SingleFileChange { label: change_label, edit, cursor_position: self.cursor_position } | ||
231 | .into_source_change(self.file) | ||
232 | } | ||
233 | } | ||