]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/assist_context.rs
Merge iter_for_each_to_for and for_to_iter_for_each assists modules
[rust.git] / 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     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, 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     pub(crate) frange: FileRange,
60     source_file: SourceFile,
61 }
62
63 impl<'a> AssistContext<'a> {
64     pub(crate) fn new(
65         sema: Semantics<'a, RootDatabase>,
66         config: &'a AssistConfig,
67         frange: FileRange,
68     ) -> AssistContext<'a> {
69         let source_file = sema.parse(frange.file_id);
70         AssistContext { config, sema, frange, source_file }
71     }
72
73     pub(crate) fn db(&self) -> &RootDatabase {
74         self.sema.db
75     }
76
77     // NB, this ignores active selection.
78     pub(crate) fn offset(&self) -> TextSize {
79         self.frange.range.start()
80     }
81
82     pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
83         self.source_file.syntax().token_at_offset(self.offset())
84     }
85     pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
86         self.token_at_offset().find(|it| it.kind() == kind)
87     }
88     pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
89         self.token_at_offset().find_map(T::cast)
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_range<N: AstNode>(&self) -> Option<N> {
95         find_node_at_range(self.source_file.syntax(), self.frange.range)
96     }
97     pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
98         self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset())
99     }
100     pub(crate) fn covering_element(&self) -> SyntaxElement {
101         self.source_file.syntax().covering_element(self.frange.range)
102     }
103 }
104
105 pub(crate) struct Assists {
106     file: FileId,
107     resolve: AssistResolveStrategy,
108     buf: Vec<Assist>,
109     allowed: Option<Vec<AssistKind>>,
110 }
111
112 impl Assists {
113     pub(crate) fn new(ctx: &AssistContext, resolve: AssistResolveStrategy) -> Assists {
114         Assists {
115             resolve,
116             file: ctx.frange.file_id,
117             buf: Vec::new(),
118             allowed: ctx.config.allowed.clone(),
119         }
120     }
121
122     pub(crate) fn finish(mut self) -> Vec<Assist> {
123         self.buf.sort_by_key(|assist| assist.target.len());
124         self.buf
125     }
126
127     pub(crate) fn add(
128         &mut self,
129         id: AssistId,
130         label: impl Into<String>,
131         target: TextRange,
132         f: impl FnOnce(&mut AssistBuilder),
133     ) -> Option<()> {
134         let mut f = Some(f);
135         self.add_impl(None, id, label.into(), target, &mut |it| f.take().unwrap()(it))
136     }
137
138     pub(crate) fn add_group(
139         &mut self,
140         group: &GroupLabel,
141         id: AssistId,
142         label: impl Into<String>,
143         target: TextRange,
144         f: impl FnOnce(&mut AssistBuilder),
145     ) -> Option<()> {
146         let mut f = Some(f);
147         self.add_impl(Some(group), id, label.into(), target, &mut |it| f.take().unwrap()(it))
148     }
149
150     fn add_impl(
151         &mut self,
152         group: Option<&GroupLabel>,
153         id: AssistId,
154         label: String,
155         target: TextRange,
156         f: &mut dyn FnMut(&mut AssistBuilder),
157     ) -> Option<()> {
158         if !self.is_allowed(&id) {
159             return None;
160         }
161
162         let source_change = if self.resolve.should_resolve(&id) {
163             let mut builder = AssistBuilder::new(self.file);
164             f(&mut builder);
165             Some(builder.finish())
166         } else {
167             None
168         };
169
170         let label = Label::new(label);
171         let group = group.cloned();
172         self.buf.push(Assist { id, label, group, target, source_change });
173         Some(())
174     }
175
176     fn is_allowed(&self, id: &AssistId) -> bool {
177         match &self.allowed {
178             Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
179             None => true,
180         }
181     }
182 }
183
184 pub(crate) struct AssistBuilder {
185     edit: TextEditBuilder,
186     file_id: FileId,
187     source_change: SourceChange,
188
189     /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
190     mutated_tree: Option<TreeMutator>,
191 }
192
193 pub(crate) struct TreeMutator {
194     immutable: SyntaxNode,
195     mutable_clone: SyntaxNode,
196 }
197
198 impl TreeMutator {
199     pub(crate) fn new(immutable: &SyntaxNode) -> TreeMutator {
200         let immutable = immutable.ancestors().last().unwrap();
201         let mutable_clone = immutable.clone_for_update();
202         TreeMutator { immutable, mutable_clone }
203     }
204
205     pub(crate) fn make_mut<N: AstNode>(&self, node: &N) -> N {
206         N::cast(self.make_syntax_mut(node.syntax())).unwrap()
207     }
208
209     pub(crate) fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
210         let ptr = SyntaxNodePtr::new(node);
211         ptr.to_node(&self.mutable_clone)
212     }
213 }
214
215 impl AssistBuilder {
216     pub(crate) fn new(file_id: FileId) -> AssistBuilder {
217         AssistBuilder {
218             edit: TextEdit::builder(),
219             file_id,
220             source_change: SourceChange::default(),
221             mutated_tree: None,
222         }
223     }
224
225     pub(crate) fn edit_file(&mut self, file_id: FileId) {
226         self.commit();
227         self.file_id = file_id;
228     }
229
230     fn commit(&mut self) {
231         if let Some(tm) = self.mutated_tree.take() {
232             algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
233         }
234
235         let edit = mem::take(&mut self.edit).finish();
236         if !edit.is_empty() {
237             self.source_change.insert_source_edit(self.file_id, edit);
238         }
239     }
240
241     pub(crate) fn make_mut<N: AstNode>(&mut self, node: N) -> N {
242         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
243     }
244     /// Returns a copy of the `node`, suitable for mutation.
245     ///
246     /// Syntax trees in rust-analyzer are typically immutable, and mutating
247     /// operations panic at runtime. However, it is possible to make a copy of
248     /// the tree and mutate the copy freely. Mutation is based on interior
249     /// mutability, and different nodes in the same tree see the same mutations.
250     ///
251     /// The typical pattern for an assist is to find specific nodes in the read
252     /// phase, and then get their mutable couterparts using `make_mut` in the
253     /// mutable state.
254     pub(crate) fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
255         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
256     }
257
258     /// Remove specified `range` of text.
259     pub(crate) fn delete(&mut self, range: TextRange) {
260         self.edit.delete(range)
261     }
262     /// Append specified `text` at the given `offset`
263     pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
264         self.edit.insert(offset, text.into())
265     }
266     /// Append specified `snippet` at the given `offset`
267     pub(crate) fn insert_snippet(
268         &mut self,
269         _cap: SnippetCap,
270         offset: TextSize,
271         snippet: impl Into<String>,
272     ) {
273         self.source_change.is_snippet = true;
274         self.insert(offset, snippet);
275     }
276     /// Replaces specified `range` of text with a given string.
277     pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
278         self.edit.replace(range, replace_with.into())
279     }
280     /// Replaces specified `range` of text with a given `snippet`.
281     pub(crate) fn replace_snippet(
282         &mut self,
283         _cap: SnippetCap,
284         range: TextRange,
285         snippet: impl Into<String>,
286     ) {
287         self.source_change.is_snippet = true;
288         self.replace(range, snippet);
289     }
290     pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
291         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
292     }
293     pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
294         let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
295         self.source_change.push_file_system_edit(file_system_edit);
296     }
297
298     fn finish(mut self) -> SourceChange {
299         self.commit();
300         mem::take(&mut self.source_change)
301     }
302 }