]> git.lizzy.rs Git - rust.git/blob - crates/assists/src/assist_context.rs
Align config's API with usage
[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, SourceFileEdit},
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     is_snippet: bool,
184     source_file_edits: Vec<SourceFileEdit>,
185     file_system_edits: Vec<FileSystemEdit>,
186 }
187
188 impl AssistBuilder {
189     pub(crate) fn new(file_id: FileId) -> AssistBuilder {
190         AssistBuilder {
191             edit: TextEdit::builder(),
192             file_id,
193             is_snippet: false,
194             source_file_edits: Vec::default(),
195             file_system_edits: Vec::default(),
196         }
197     }
198
199     pub(crate) fn edit_file(&mut self, file_id: FileId) {
200         self.commit();
201         self.file_id = file_id;
202     }
203
204     fn commit(&mut self) {
205         let edit = mem::take(&mut self.edit).finish();
206         if !edit.is_empty() {
207             match self.source_file_edits.binary_search_by_key(&self.file_id, |edit| edit.file_id) {
208                 Ok(idx) => self.source_file_edits[idx]
209                     .edit
210                     .union(edit)
211                     .expect("overlapping edits for same file"),
212                 Err(idx) => self
213                     .source_file_edits
214                     .insert(idx, SourceFileEdit { file_id: self.file_id, edit }),
215             }
216         }
217     }
218
219     /// Remove specified `range` of text.
220     pub(crate) fn delete(&mut self, range: TextRange) {
221         self.edit.delete(range)
222     }
223     /// Append specified `text` at the given `offset`
224     pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
225         self.edit.insert(offset, text.into())
226     }
227     /// Append specified `snippet` at the given `offset`
228     pub(crate) fn insert_snippet(
229         &mut self,
230         _cap: SnippetCap,
231         offset: TextSize,
232         snippet: impl Into<String>,
233     ) {
234         self.is_snippet = true;
235         self.insert(offset, snippet);
236     }
237     /// Replaces specified `range` of text with a given string.
238     pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
239         self.edit.replace(range, replace_with.into())
240     }
241     /// Replaces specified `range` of text with a given `snippet`.
242     pub(crate) fn replace_snippet(
243         &mut self,
244         _cap: SnippetCap,
245         range: TextRange,
246         snippet: impl Into<String>,
247     ) {
248         self.is_snippet = true;
249         self.replace(range, snippet);
250     }
251     pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
252         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
253     }
254     pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
255         if let Some(node) = rewriter.rewrite_root() {
256             let new = rewriter.rewrite(&node);
257             algo::diff(&node, &new).into_text_edit(&mut self.edit);
258         }
259     }
260     pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
261         let file_system_edit =
262             FileSystemEdit::CreateFile { dst: dst.clone(), initial_contents: content.into() };
263         self.file_system_edits.push(file_system_edit);
264     }
265
266     fn finish(mut self) -> SourceChange {
267         self.commit();
268         SourceChange {
269             source_file_edits: mem::take(&mut self.source_file_edits),
270             file_system_edits: mem::take(&mut self.file_system_edits),
271             is_snippet: self.is_snippet,
272         }
273     }
274 }