]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide-assists/src/assist_context.rs
Rollup merge of #98796 - compiler-errors:no-semi-if-comma, r=estebank
[rust.git] / src / tools / rust-analyzer / crates / ide-assists / src / assist_context.rs
1 //! See [`AssistContext`].
2
3 use std::mem;
4
5 use hir::Semantics;
6 use ide_db::{
7     base_db::{AnchoredPathBuf, FileId, FileRange},
8     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> {
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
92     pub(crate) fn db(&self) -> &RootDatabase {
93         self.sema.db
94     }
95
96     // NB, this ignores active selection.
97     pub(crate) fn offset(&self) -> TextSize {
98         self.frange.range.start()
99     }
100
101     pub(crate) fn file_id(&self) -> FileId {
102         self.frange.file_id
103     }
104
105     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.
111     pub(crate) fn selection_trimmed(&self) -> TextRange {
112         self.trimmed_range
113     }
114
115     pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
116         self.source_file.syntax().token_at_offset(self.offset())
117     }
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     }
121     pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
122         self.token_at_offset().find_map(T::cast)
123     }
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     }
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     }
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.
134     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 {
147     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
156     pub(crate) fn finish(mut self) -> Vec<Assist> {
157         self.buf.sort_by_key(|assist| assist.target.len());
158         self.buf
159     }
160
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
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
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 mut trigger_signature_help = false;
197         let source_change = if self.resolve.should_resolve(&id) {
198             let mut builder = AssistBuilder::new(self.file);
199             f(&mut builder);
200             trigger_signature_help = builder.trigger_signature_help;
201             Some(builder.finish())
202         } else {
203             None
204         };
205
206         let label = Label::new(label);
207         let group = group.cloned();
208         self.buf.push(Assist { id, label, group, target, source_change, trigger_signature_help });
209         Some(())
210     }
211
212     fn is_allowed(&self, id: &AssistId) -> bool {
213         match &self.allowed {
214             Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
215             None => true,
216         }
217     }
218 }
219
220 pub(crate) struct AssistBuilder {
221     edit: TextEditBuilder,
222     file_id: FileId,
223     source_change: SourceChange,
224     trigger_signature_help: bool,
225
226     /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
227     mutated_tree: Option<TreeMutator>,
228 }
229
230 pub(crate) struct TreeMutator {
231     immutable: SyntaxNode,
232     mutable_clone: SyntaxNode,
233 }
234
235 impl TreeMutator {
236     pub(crate) fn new(immutable: &SyntaxNode) -> TreeMutator {
237         let immutable = immutable.ancestors().last().unwrap();
238         let mutable_clone = immutable.clone_for_update();
239         TreeMutator { immutable, mutable_clone }
240     }
241
242     pub(crate) fn make_mut<N: AstNode>(&self, node: &N) -> N {
243         N::cast(self.make_syntax_mut(node.syntax())).unwrap()
244     }
245
246     pub(crate) fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
247         let ptr = SyntaxNodePtr::new(node);
248         ptr.to_node(&self.mutable_clone)
249     }
250 }
251
252 impl AssistBuilder {
253     pub(crate) fn new(file_id: FileId) -> AssistBuilder {
254         AssistBuilder {
255             edit: TextEdit::builder(),
256             file_id,
257             source_change: SourceChange::default(),
258             trigger_signature_help: false,
259             mutated_tree: None,
260         }
261     }
262
263     pub(crate) fn edit_file(&mut self, file_id: FileId) {
264         self.commit();
265         self.file_id = file_id;
266     }
267
268     fn commit(&mut self) {
269         if let Some(tm) = self.mutated_tree.take() {
270             algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
271         }
272
273         let edit = mem::take(&mut self.edit).finish();
274         if !edit.is_empty() {
275             self.source_change.insert_source_edit(self.file_id, edit);
276         }
277     }
278
279     pub(crate) fn make_mut<N: AstNode>(&mut self, node: N) -> N {
280         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
281     }
282     /// Returns a copy of the `node`, suitable for mutation.
283     ///
284     /// Syntax trees in rust-analyzer are typically immutable, and mutating
285     /// operations panic at runtime. However, it is possible to make a copy of
286     /// the tree and mutate the copy freely. Mutation is based on interior
287     /// mutability, and different nodes in the same tree see the same mutations.
288     ///
289     /// The typical pattern for an assist is to find specific nodes in the read
290     /// phase, and then get their mutable couterparts using `make_mut` in the
291     /// mutable state.
292     pub(crate) fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
293         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
294     }
295
296     /// Remove specified `range` of text.
297     pub(crate) fn delete(&mut self, range: TextRange) {
298         self.edit.delete(range)
299     }
300     /// Append specified `text` at the given `offset`
301     pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
302         self.edit.insert(offset, text.into())
303     }
304     /// Append specified `snippet` at the given `offset`
305     pub(crate) fn insert_snippet(
306         &mut self,
307         _cap: SnippetCap,
308         offset: TextSize,
309         snippet: impl Into<String>,
310     ) {
311         self.source_change.is_snippet = true;
312         self.insert(offset, snippet);
313     }
314     /// Replaces specified `range` of text with a given string.
315     pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
316         self.edit.replace(range, replace_with.into())
317     }
318     /// Replaces specified `range` of text with a given `snippet`.
319     pub(crate) fn replace_snippet(
320         &mut self,
321         _cap: SnippetCap,
322         range: TextRange,
323         snippet: impl Into<String>,
324     ) {
325         self.source_change.is_snippet = true;
326         self.replace(range, snippet);
327     }
328     pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
329         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
330     }
331     pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
332         let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
333         self.source_change.push_file_system_edit(file_system_edit);
334     }
335     pub(crate) fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
336         let file_system_edit = FileSystemEdit::MoveFile { src, dst };
337         self.source_change.push_file_system_edit(file_system_edit);
338     }
339     pub(crate) fn trigger_signature_help(&mut self) {
340         self.trigger_signature_help = true;
341     }
342
343     fn finish(mut self) -> SourceChange {
344         self.commit();
345         mem::take(&mut self.source_change)
346     }
347 }