1 //! See [`AssistContext`].
2 
3 use std::mem;
4 
5 use hir::Semantics;
6 use ide_db::{
7     base_db::{AnchoredPathBuf, FileId, FileRange},
8     helpers::SnippetCap,
9 };
10 use ide_db::{
11     label::Label,
12     source_change::{FileSystemEdit, SourceChange},
13     RootDatabase,
14 };
15 use syntax::{
16     algo::{self, find_node_at_offset, find_node_at_range},
17     AstNode, AstToken, Direction, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxNodePtr,
18     SyntaxToken, TextRange, TextSize, TokenAtOffset,
19 };
20 use text_edit::{TextEdit, TextEditBuilder};
21 
22 use crate::{
23     assist_config::AssistConfig, Assist, AssistId, AssistKind, AssistResolveStrategy, GroupLabel,
24 };
25 
26 /// `AssistContext` allows to apply an assist or check if it could be applied.
27 ///
28 /// Assists use a somewhat over-engineered approach, given the current needs.
29 /// The assists workflow consists of two phases. In the first phase, a user asks
30 /// for the list of available assists. In the second phase, the user picks a
31 /// particular assist and it gets applied.
32 ///
33 /// There are two peculiarities here:
34 ///
35 /// * first, we ideally avoid computing more things then necessary to answer "is
36 ///   assist applicable" in the first phase.
37 /// * second, when we are applying assist, we don't have a guarantee that there
38 ///   weren't any changes between the point when user asked for assists and when
39 ///   they applied a particular assist. So, when applying assist, we need to do
40 ///   all the checks from scratch.
41 ///
42 /// To avoid repeating the same code twice for both "check" and "apply"
43 /// functions, we use an approach reminiscent of that of Django's function based
44 /// views dealing with forms. Each assist receives a runtime parameter,
45 /// `resolve`. It first check if an edit is applicable (potentially computing
46 /// info required to compute the actual edit). If it is applicable, and
47 /// `resolve` is `true`, it then computes the actual edit.
48 ///
49 /// So, to implement the original assists workflow, we can first apply each edit
50 /// with `resolve = false`, and then applying the selected edit again, with
51 /// `resolve = true` this time.
52 ///
53 /// Note, however, that we don't actually use such two-phase logic at the
54 /// moment, because the LSP API is pretty awkward in this place, and it's much
55 /// easier to just compute the edit eagerly :-)
56 pub(crate) struct AssistContext<'a> {
57     pub(crate) config: &'a AssistConfig,
58     pub(crate) sema: Semantics<'a, RootDatabase>,
59     frange: FileRange,
60     trimmed_range: TextRange,
61     source_file: SourceFile,
62 }
63 
64 impl<'a> AssistContext<'a> {
new( sema: Semantics<'a, RootDatabase>, config: &'a AssistConfig, frange: FileRange, ) -> AssistContext<'a>65     pub(crate) fn new(
66         sema: Semantics<'a, RootDatabase>,
67         config: &'a AssistConfig,
68         frange: FileRange,
69     ) -> AssistContext<'a> {
70         let source_file = sema.parse(frange.file_id);
71 
72         let start = frange.range.start();
73         let end = frange.range.end();
74         let left = source_file.syntax().token_at_offset(start);
75         let right = source_file.syntax().token_at_offset(end);
76         let left =
77             left.right_biased().and_then(|t| algo::skip_whitespace_token(t, Direction::Next));
78         let right =
79             right.left_biased().and_then(|t| algo::skip_whitespace_token(t, Direction::Prev));
80         let left = left.map(|t| t.text_range().start().clamp(start, end));
81         let right = right.map(|t| t.text_range().end().clamp(start, end));
82 
83         let trimmed_range = match (left, right) {
84             (Some(left), Some(right)) if left <= right => TextRange::new(left, right),
85             // Selection solely consists of whitespace so just fall back to the original
86             _ => frange.range,
87         };
88 
89         AssistContext { config, sema, frange, source_file, trimmed_range }
90     }
91 
db(&self) -> &RootDatabase92     pub(crate) fn db(&self) -> &RootDatabase {
93         self.sema.db
94     }
95 
96     // NB, this ignores active selection.
offset(&self) -> TextSize97     pub(crate) fn offset(&self) -> TextSize {
98         self.frange.range.start()
99     }
100 
file_id(&self) -> FileId101     pub(crate) fn file_id(&self) -> FileId {
102         self.frange.file_id
103     }
104 
has_empty_selection(&self) -> bool105     pub(crate) fn has_empty_selection(&self) -> bool {
106         self.trimmed_range.is_empty()
107     }
108 
109     /// Returns the selected range trimmed for whitespace tokens, that is the range will be snapped
110     /// to the nearest enclosed token.
selection_trimmed(&self) -> TextRange111     pub(crate) fn selection_trimmed(&self) -> TextRange {
112         self.trimmed_range
113     }
114 
token_at_offset(&self) -> TokenAtOffset<SyntaxToken>115     pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
116         self.source_file.syntax().token_at_offset(self.offset())
117     }
find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken>118     pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
119         self.token_at_offset().find(|it| it.kind() == kind)
120     }
find_token_at_offset<T: AstToken>(&self) -> Option<T>121     pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
122         self.token_at_offset().find_map(T::cast)
123     }
find_node_at_offset<N: AstNode>(&self) -> Option<N>124     pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
125         find_node_at_offset(self.source_file.syntax(), self.offset())
126     }
find_node_at_range<N: AstNode>(&self) -> Option<N>127     pub(crate) fn find_node_at_range<N: AstNode>(&self) -> Option<N> {
128         find_node_at_range(self.source_file.syntax(), self.trimmed_range)
129     }
find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N>130     pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
131         self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset())
132     }
133     /// Returns the element covered by the selection range, this excludes trailing whitespace in the selection.
covering_element(&self) -> SyntaxElement134     pub(crate) fn covering_element(&self) -> SyntaxElement {
135         self.source_file.syntax().covering_element(self.selection_trimmed())
136     }
137 }
138 
139 pub(crate) struct Assists {
140     file: FileId,
141     resolve: AssistResolveStrategy,
142     buf: Vec<Assist>,
143     allowed: Option<Vec<AssistKind>>,
144 }
145 
146 impl Assists {
new(ctx: &AssistContext, resolve: AssistResolveStrategy) -> Assists147     pub(crate) fn new(ctx: &AssistContext, resolve: AssistResolveStrategy) -> Assists {
148         Assists {
149             resolve,
150             file: ctx.frange.file_id,
151             buf: Vec::new(),
152             allowed: ctx.config.allowed.clone(),
153         }
154     }
155 
finish(mut self) -> Vec<Assist>156     pub(crate) fn finish(mut self) -> Vec<Assist> {
157         self.buf.sort_by_key(|assist| assist.target.len());
158         self.buf
159     }
160 
add( &mut self, id: AssistId, label: impl Into<String>, target: TextRange, f: impl FnOnce(&mut AssistBuilder), ) -> Option<()>161     pub(crate) fn add(
162         &mut self,
163         id: AssistId,
164         label: impl Into<String>,
165         target: TextRange,
166         f: impl FnOnce(&mut AssistBuilder),
167     ) -> Option<()> {
168         let mut f = Some(f);
169         self.add_impl(None, id, label.into(), target, &mut |it| f.take().unwrap()(it))
170     }
171 
add_group( &mut self, group: &GroupLabel, id: AssistId, label: impl Into<String>, target: TextRange, f: impl FnOnce(&mut AssistBuilder), ) -> Option<()>172     pub(crate) fn add_group(
173         &mut self,
174         group: &GroupLabel,
175         id: AssistId,
176         label: impl Into<String>,
177         target: TextRange,
178         f: impl FnOnce(&mut AssistBuilder),
179     ) -> Option<()> {
180         let mut f = Some(f);
181         self.add_impl(Some(group), id, label.into(), target, &mut |it| f.take().unwrap()(it))
182     }
183 
add_impl( &mut self, group: Option<&GroupLabel>, id: AssistId, label: String, target: TextRange, f: &mut dyn FnMut(&mut AssistBuilder), ) -> Option<()>184     fn add_impl(
185         &mut self,
186         group: Option<&GroupLabel>,
187         id: AssistId,
188         label: String,
189         target: TextRange,
190         f: &mut dyn FnMut(&mut AssistBuilder),
191     ) -> Option<()> {
192         if !self.is_allowed(&id) {
193             return None;
194         }
195 
196         let source_change = if self.resolve.should_resolve(&id) {
197             let mut builder = AssistBuilder::new(self.file);
198             f(&mut builder);
199             Some(builder.finish())
200         } else {
201             None
202         };
203 
204         let label = Label::new(label);
205         let group = group.cloned();
206         self.buf.push(Assist { id, label, group, target, source_change });
207         Some(())
208     }
209 
is_allowed(&self, id: &AssistId) -> bool210     fn is_allowed(&self, id: &AssistId) -> bool {
211         match &self.allowed {
212             Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
213             None => true,
214         }
215     }
216 }
217 
218 pub(crate) struct AssistBuilder {
219     edit: TextEditBuilder,
220     file_id: FileId,
221     source_change: SourceChange,
222 
223     /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
224     mutated_tree: Option<TreeMutator>,
225 }
226 
227 pub(crate) struct TreeMutator {
228     immutable: SyntaxNode,
229     mutable_clone: SyntaxNode,
230 }
231 
232 impl TreeMutator {
new(immutable: &SyntaxNode) -> TreeMutator233     pub(crate) fn new(immutable: &SyntaxNode) -> TreeMutator {
234         let immutable = immutable.ancestors().last().unwrap();
235         let mutable_clone = immutable.clone_for_update();
236         TreeMutator { immutable, mutable_clone }
237     }
238 
make_mut<N: AstNode>(&self, node: &N) -> N239     pub(crate) fn make_mut<N: AstNode>(&self, node: &N) -> N {
240         N::cast(self.make_syntax_mut(node.syntax())).unwrap()
241     }
242 
make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode243     pub(crate) fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
244         let ptr = SyntaxNodePtr::new(node);
245         ptr.to_node(&self.mutable_clone)
246     }
247 }
248 
249 impl AssistBuilder {
new(file_id: FileId) -> AssistBuilder250     pub(crate) fn new(file_id: FileId) -> AssistBuilder {
251         AssistBuilder {
252             edit: TextEdit::builder(),
253             file_id,
254             source_change: SourceChange::default(),
255             mutated_tree: None,
256         }
257     }
258 
edit_file(&mut self, file_id: FileId)259     pub(crate) fn edit_file(&mut self, file_id: FileId) {
260         self.commit();
261         self.file_id = file_id;
262     }
263 
commit(&mut self)264     fn commit(&mut self) {
265         if let Some(tm) = self.mutated_tree.take() {
266             algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
267         }
268 
269         let edit = mem::take(&mut self.edit).finish();
270         if !edit.is_empty() {
271             self.source_change.insert_source_edit(self.file_id, edit);
272         }
273     }
274 
make_mut<N: AstNode>(&mut self, node: N) -> N275     pub(crate) fn make_mut<N: AstNode>(&mut self, node: N) -> N {
276         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
277     }
278     /// Returns a copy of the `node`, suitable for mutation.
279     ///
280     /// Syntax trees in rust-analyzer are typically immutable, and mutating
281     /// operations panic at runtime. However, it is possible to make a copy of
282     /// the tree and mutate the copy freely. Mutation is based on interior
283     /// mutability, and different nodes in the same tree see the same mutations.
284     ///
285     /// The typical pattern for an assist is to find specific nodes in the read
286     /// phase, and then get their mutable couterparts using `make_mut` in the
287     /// mutable state.
make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode288     pub(crate) fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
289         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
290     }
291 
292     /// Remove specified `range` of text.
delete(&mut self, range: TextRange)293     pub(crate) fn delete(&mut self, range: TextRange) {
294         self.edit.delete(range)
295     }
296     /// Append specified `text` at the given `offset`
insert(&mut self, offset: TextSize, text: impl Into<String>)297     pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
298         self.edit.insert(offset, text.into())
299     }
300     /// Append specified `snippet` at the given `offset`
insert_snippet( &mut self, _cap: SnippetCap, offset: TextSize, snippet: impl Into<String>, )301     pub(crate) fn insert_snippet(
302         &mut self,
303         _cap: SnippetCap,
304         offset: TextSize,
305         snippet: impl Into<String>,
306     ) {
307         self.source_change.is_snippet = true;
308         self.insert(offset, snippet);
309     }
310     /// Replaces specified `range` of text with a given string.
replace(&mut self, range: TextRange, replace_with: impl Into<String>)311     pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
312         self.edit.replace(range, replace_with.into())
313     }
314     /// Replaces specified `range` of text with a given `snippet`.
replace_snippet( &mut self, _cap: SnippetCap, range: TextRange, snippet: impl Into<String>, )315     pub(crate) fn replace_snippet(
316         &mut self,
317         _cap: SnippetCap,
318         range: TextRange,
319         snippet: impl Into<String>,
320     ) {
321         self.source_change.is_snippet = true;
322         self.replace(range, snippet);
323     }
replace_ast<N: AstNode>(&mut self, old: N, new: N)324     pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
325         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
326     }
create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>)327     pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
328         let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
329         self.source_change.push_file_system_edit(file_system_edit);
330     }
move_file(&mut self, src: FileId, dst: AnchoredPathBuf)331     pub(crate) fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
332         let file_system_edit = FileSystemEdit::MoveFile { src, dst };
333         self.source_change.push_file_system_edit(file_system_edit);
334     }
335 
finish(mut self) -> SourceChange336     fn finish(mut self) -> SourceChange {
337         self.commit();
338         mem::take(&mut self.source_change)
339     }
340 }
341