]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/assist_context.rs
Add a way to resolve certain assists
[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, SyntaxRewriter},
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     // FIXME: remove
104     pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
105         self.source_file.syntax().covering_element(range)
106     }
107 }
108
109 pub(crate) struct Assists {
110     file: FileId,
111     resolve: AssistResolveStrategy,
112     buf: Vec<Assist>,
113     allowed: Option<Vec<AssistKind>>,
114 }
115
116 impl Assists {
117     pub(crate) fn new(ctx: &AssistContext, resolve: AssistResolveStrategy) -> Assists {
118         Assists {
119             resolve,
120             file: ctx.frange.file_id,
121             buf: Vec::new(),
122             allowed: ctx.config.allowed.clone(),
123         }
124     }
125
126     pub(crate) fn finish(mut self) -> Vec<Assist> {
127         self.buf.sort_by_key(|assist| assist.target.len());
128         self.buf
129     }
130
131     pub(crate) fn add(
132         &mut self,
133         id: AssistId,
134         label: impl Into<String>,
135         target: TextRange,
136         f: impl FnOnce(&mut AssistBuilder),
137     ) -> Option<()> {
138         if !self.is_allowed(&id) {
139             return None;
140         }
141         let label = Label::new(label.into());
142         let assist = Assist { id, label, group: None, target, source_change: None };
143         self.add_impl(assist, f)
144     }
145
146     pub(crate) fn add_group(
147         &mut self,
148         group: &GroupLabel,
149         id: AssistId,
150         label: impl Into<String>,
151         target: TextRange,
152         f: impl FnOnce(&mut AssistBuilder),
153     ) -> Option<()> {
154         if !self.is_allowed(&id) {
155             return None;
156         }
157         let label = Label::new(label.into());
158         let assist = Assist { id, label, group: Some(group.clone()), target, source_change: None };
159         self.add_impl(assist, f)
160     }
161
162     fn add_impl(&mut self, mut assist: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> {
163         let source_change = if self.resolve.should_resolve(&assist.id) {
164             let mut builder = AssistBuilder::new(self.file);
165             f(&mut builder);
166             Some(builder.finish())
167         } else {
168             None
169         };
170         assist.source_change = source_change;
171
172         self.buf.push(assist);
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<(SyntaxNode, SyntaxNode)>,
191 }
192
193 impl AssistBuilder {
194     pub(crate) fn new(file_id: FileId) -> AssistBuilder {
195         AssistBuilder {
196             edit: TextEdit::builder(),
197             file_id,
198             source_change: SourceChange::default(),
199             mutated_tree: None,
200         }
201     }
202
203     pub(crate) fn edit_file(&mut self, file_id: FileId) {
204         self.commit();
205         self.file_id = file_id;
206     }
207
208     fn commit(&mut self) {
209         if let Some((old, new)) = self.mutated_tree.take() {
210             algo::diff(&old, &new).into_text_edit(&mut self.edit)
211         }
212
213         let edit = mem::take(&mut self.edit).finish();
214         if !edit.is_empty() {
215             self.source_change.insert_source_edit(self.file_id, edit);
216         }
217     }
218
219     pub(crate) fn make_ast_mut<N: AstNode>(&mut self, node: N) -> N {
220         N::cast(self.make_mut(node.syntax().clone())).unwrap()
221     }
222     /// Returns a copy of the `node`, suitable for mutation.
223     ///
224     /// Syntax trees in rust-analyzer are typically immutable, and mutating
225     /// operations panic at runtime. However, it is possible to make a copy of
226     /// the tree and mutate the copy freely. Mutation is based on interior
227     /// mutability, and different nodes in the same tree see the same mutations.
228     ///
229     /// The typical pattern for an assist is to find specific nodes in the read
230     /// phase, and then get their mutable couterparts using `make_mut` in the
231     /// mutable state.
232     pub(crate) fn make_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
233         let root = &self
234             .mutated_tree
235             .get_or_insert_with(|| {
236                 let immutable = node.ancestors().last().unwrap();
237                 let mutable = immutable.clone_for_update();
238                 (immutable, mutable)
239             })
240             .1;
241         let ptr = SyntaxNodePtr::new(&&node);
242         ptr.to_node(root)
243     }
244
245     /// Remove specified `range` of text.
246     pub(crate) fn delete(&mut self, range: TextRange) {
247         self.edit.delete(range)
248     }
249     /// Append specified `text` at the given `offset`
250     pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
251         self.edit.insert(offset, text.into())
252     }
253     /// Append specified `snippet` at the given `offset`
254     pub(crate) fn insert_snippet(
255         &mut self,
256         _cap: SnippetCap,
257         offset: TextSize,
258         snippet: impl Into<String>,
259     ) {
260         self.source_change.is_snippet = true;
261         self.insert(offset, snippet);
262     }
263     /// Replaces specified `range` of text with a given string.
264     pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
265         self.edit.replace(range, replace_with.into())
266     }
267     /// Replaces specified `range` of text with a given `snippet`.
268     pub(crate) fn replace_snippet(
269         &mut self,
270         _cap: SnippetCap,
271         range: TextRange,
272         snippet: impl Into<String>,
273     ) {
274         self.source_change.is_snippet = true;
275         self.replace(range, snippet);
276     }
277     pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
278         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
279     }
280     pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
281         if let Some(node) = rewriter.rewrite_root() {
282             let new = rewriter.rewrite(&node);
283             algo::diff(&node, &new).into_text_edit(&mut self.edit);
284         }
285     }
286     pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
287         let file_system_edit =
288             FileSystemEdit::CreateFile { dst: dst, initial_contents: content.into() };
289         self.source_change.push_file_system_edit(file_system_edit);
290     }
291
292     fn finish(mut self) -> SourceChange {
293         self.commit();
294         mem::take(&mut self.source_change)
295     }
296 }