]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/assist_context.rs
Merge #7677
[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, SyntaxRewriter},
17     AstNode, AstToken, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange, TextSize,
18     TokenAtOffset,
19 };
20 use text_edit::{TextEdit, TextEditBuilder};
21
22 use crate::{assist_config::AssistConfig, Assist, AssistId, AssistKind, GroupLabel};
23
24 /// `AssistContext` allows to apply an assist or check if it could be applied.
25 ///
26 /// Assists use a somewhat over-engineered approach, given the current needs.
27 /// The assists workflow consists of two phases. In the first phase, a user asks
28 /// for the list of available assists. In the second phase, the user picks a
29 /// particular assist and it gets applied.
30 ///
31 /// There are two peculiarities here:
32 ///
33 /// * first, we ideally avoid computing more things then necessary to answer "is
34 ///   assist applicable" in the first phase.
35 /// * second, when we are applying assist, we don't have a guarantee that there
36 ///   weren't any changes between the point when user asked for assists and when
37 ///   they applied a particular assist. So, when applying assist, we need to do
38 ///   all the checks from scratch.
39 ///
40 /// To avoid repeating the same code twice for both "check" and "apply"
41 /// functions, we use an approach reminiscent of that of Django's function based
42 /// views dealing with forms. Each assist receives a runtime parameter,
43 /// `resolve`. It first check if an edit is applicable (potentially computing
44 /// info required to compute the actual edit). If it is applicable, and
45 /// `resolve` is `true`, it then computes the actual edit.
46 ///
47 /// So, to implement the original assists workflow, we can first apply each edit
48 /// with `resolve = false`, and then applying the selected edit again, with
49 /// `resolve = true` this time.
50 ///
51 /// Note, however, that we don't actually use such two-phase logic at the
52 /// moment, because the LSP API is pretty awkward in this place, and it's much
53 /// easier to just compute the edit eagerly :-)
54 pub(crate) struct AssistContext<'a> {
55     pub(crate) config: &'a AssistConfig,
56     pub(crate) sema: Semantics<'a, RootDatabase>,
57     pub(crate) frange: FileRange,
58     source_file: SourceFile,
59 }
60
61 impl<'a> AssistContext<'a> {
62     pub(crate) fn new(
63         sema: Semantics<'a, RootDatabase>,
64         config: &'a AssistConfig,
65         frange: FileRange,
66     ) -> AssistContext<'a> {
67         let source_file = sema.parse(frange.file_id);
68         AssistContext { config, sema, frange, source_file }
69     }
70
71     pub(crate) fn db(&self) -> &RootDatabase {
72         self.sema.db
73     }
74
75     // NB, this ignores active selection.
76     pub(crate) fn offset(&self) -> TextSize {
77         self.frange.range.start()
78     }
79
80     pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
81         self.source_file.syntax().token_at_offset(self.offset())
82     }
83     pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
84         self.token_at_offset().find(|it| it.kind() == kind)
85     }
86     pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
87         self.token_at_offset().find_map(T::cast)
88     }
89     pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
90         find_node_at_offset(self.source_file.syntax(), self.offset())
91     }
92     pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
93         self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset())
94     }
95     pub(crate) fn covering_element(&self) -> SyntaxElement {
96         self.source_file.syntax().covering_element(self.frange.range)
97     }
98     // FIXME: remove
99     pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
100         self.source_file.syntax().covering_element(range)
101     }
102 }
103
104 pub(crate) struct Assists {
105     resolve: bool,
106     file: FileId,
107     buf: Vec<Assist>,
108     allowed: Option<Vec<AssistKind>>,
109 }
110
111 impl Assists {
112     pub(crate) fn new(ctx: &AssistContext, resolve: bool) -> Assists {
113         Assists {
114             resolve,
115             file: ctx.frange.file_id,
116             buf: Vec::new(),
117             allowed: ctx.config.allowed.clone(),
118         }
119     }
120
121     pub(crate) fn finish(mut self) -> Vec<Assist> {
122         self.buf.sort_by_key(|assist| assist.target.len());
123         self.buf
124     }
125
126     pub(crate) fn add(
127         &mut self,
128         id: AssistId,
129         label: impl Into<String>,
130         target: TextRange,
131         f: impl FnOnce(&mut AssistBuilder),
132     ) -> Option<()> {
133         if !self.is_allowed(&id) {
134             return None;
135         }
136         let label = Label::new(label.into());
137         let assist = Assist { id, label, group: None, target, source_change: None };
138         self.add_impl(assist, f)
139     }
140
141     pub(crate) fn add_group(
142         &mut self,
143         group: &GroupLabel,
144         id: AssistId,
145         label: impl Into<String>,
146         target: TextRange,
147         f: impl FnOnce(&mut AssistBuilder),
148     ) -> Option<()> {
149         if !self.is_allowed(&id) {
150             return None;
151         }
152         let label = Label::new(label.into());
153         let assist = Assist { id, label, group: Some(group.clone()), target, source_change: None };
154         self.add_impl(assist, f)
155     }
156
157     fn add_impl(&mut self, mut assist: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> {
158         let source_change = if self.resolve {
159             let mut builder = AssistBuilder::new(self.file);
160             f(&mut builder);
161             Some(builder.finish())
162         } else {
163             None
164         };
165         assist.source_change = source_change;
166
167         self.buf.push(assist);
168         Some(())
169     }
170
171     fn is_allowed(&self, id: &AssistId) -> bool {
172         match &self.allowed {
173             Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
174             None => true,
175         }
176     }
177 }
178
179 pub(crate) struct AssistBuilder {
180     edit: TextEditBuilder,
181     file_id: FileId,
182     source_change: SourceChange,
183 }
184
185 impl AssistBuilder {
186     pub(crate) fn new(file_id: FileId) -> AssistBuilder {
187         AssistBuilder { edit: TextEdit::builder(), file_id, source_change: SourceChange::default() }
188     }
189
190     pub(crate) fn edit_file(&mut self, file_id: FileId) {
191         self.commit();
192         self.file_id = file_id;
193     }
194
195     fn commit(&mut self) {
196         let edit = mem::take(&mut self.edit).finish();
197         if !edit.is_empty() {
198             self.source_change.insert_source_edit(self.file_id, edit);
199         }
200     }
201
202     /// Remove specified `range` of text.
203     pub(crate) fn delete(&mut self, range: TextRange) {
204         self.edit.delete(range)
205     }
206     /// Append specified `text` at the given `offset`
207     pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
208         self.edit.insert(offset, text.into())
209     }
210     /// Append specified `snippet` at the given `offset`
211     pub(crate) fn insert_snippet(
212         &mut self,
213         _cap: SnippetCap,
214         offset: TextSize,
215         snippet: impl Into<String>,
216     ) {
217         self.source_change.is_snippet = true;
218         self.insert(offset, snippet);
219     }
220     /// Replaces specified `range` of text with a given string.
221     pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
222         self.edit.replace(range, replace_with.into())
223     }
224     /// Replaces specified `range` of text with a given `snippet`.
225     pub(crate) fn replace_snippet(
226         &mut self,
227         _cap: SnippetCap,
228         range: TextRange,
229         snippet: impl Into<String>,
230     ) {
231         self.source_change.is_snippet = true;
232         self.replace(range, snippet);
233     }
234     pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
235         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
236     }
237     pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
238         if let Some(node) = rewriter.rewrite_root() {
239             let new = rewriter.rewrite(&node);
240             algo::diff(&node, &new).into_text_edit(&mut self.edit);
241         }
242     }
243     pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
244         let file_system_edit =
245             FileSystemEdit::CreateFile { dst: dst, initial_contents: content.into() };
246         self.source_change.push_file_system_edit(file_system_edit);
247     }
248
249     fn finish(mut self) -> SourceChange {
250         self.commit();
251         mem::take(&mut self.source_change)
252     }
253 }