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