]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/assist_ctx.rs
Merge #4359
[rust.git] / crates / ra_assists / src / assist_ctx.rs
1 //! This module defines `AssistCtx` -- the API surface that is exposed to assists.
2 use hir::Semantics;
3 use ra_db::{FileId, FileRange};
4 use ra_fmt::{leading_indent, reindent};
5 use ra_ide_db::{
6     source_change::{SingleFileChange, SourceChange},
7     RootDatabase,
8 };
9 use ra_syntax::{
10     algo::{self, find_covering_element, find_node_at_offset, SyntaxRewriter},
11     AstNode, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize,
12     TokenAtOffset,
13 };
14 use ra_text_edit::TextEditBuilder;
15
16 use crate::{AssistId, AssistLabel, GroupLabel, ResolvedAssist};
17
18 #[derive(Clone, Debug)]
19 pub(crate) struct Assist(pub(crate) Vec<AssistInfo>);
20
21 #[derive(Clone, Debug)]
22 pub(crate) struct AssistInfo {
23     pub(crate) label: AssistLabel,
24     pub(crate) group_label: Option<GroupLabel>,
25     pub(crate) source_change: Option<SourceChange>,
26 }
27
28 impl AssistInfo {
29     fn new(label: AssistLabel) -> AssistInfo {
30         AssistInfo { label, group_label: None, source_change: None }
31     }
32
33     fn resolved(self, source_change: SourceChange) -> AssistInfo {
34         AssistInfo { source_change: Some(source_change), ..self }
35     }
36
37     fn with_group(self, group_label: GroupLabel) -> AssistInfo {
38         AssistInfo { group_label: Some(group_label), ..self }
39     }
40
41     pub(crate) fn into_resolved(self) -> Option<ResolvedAssist> {
42         let label = self.label;
43         self.source_change.map(|source_change| ResolvedAssist { label, source_change })
44     }
45 }
46
47 /// `AssistCtx` allows to apply an assist or check if it could be applied.
48 ///
49 /// Assists use a somewhat over-engineered approach, given the current needs. The
50 /// assists workflow consists of two phases. In the first phase, a user asks for
51 /// the list of available assists. In the second phase, the user picks a
52 /// particular assist and it gets applied.
53 ///
54 /// There are two peculiarities here:
55 ///
56 /// * first, we ideally avoid computing more things then necessary to answer
57 ///   "is assist applicable" in the first phase.
58 /// * second, when we are applying assist, we don't have a guarantee that there
59 ///   weren't any changes between the point when user asked for assists and when
60 ///   they applied a particular assist. So, when applying assist, we need to do
61 ///   all the checks from scratch.
62 ///
63 /// To avoid repeating the same code twice for both "check" and "apply"
64 /// functions, we use an approach reminiscent of that of Django's function based
65 /// views dealing with forms. Each assist receives a runtime parameter,
66 /// `should_compute_edit`. It first check if an edit is applicable (potentially
67 /// computing info required to compute the actual edit). If it is applicable,
68 /// and `should_compute_edit` is `true`, it then computes the actual edit.
69 ///
70 /// So, to implement the original assists workflow, we can first apply each edit
71 /// with `should_compute_edit = false`, and then applying the selected edit
72 /// again, with `should_compute_edit = true` this time.
73 ///
74 /// Note, however, that we don't actually use such two-phase logic at the
75 /// moment, because the LSP API is pretty awkward in this place, and it's much
76 /// easier to just compute the edit eagerly :-)
77 #[derive(Clone)]
78 pub(crate) struct AssistCtx<'a> {
79     pub(crate) sema: &'a Semantics<'a, RootDatabase>,
80     pub(crate) db: &'a RootDatabase,
81     pub(crate) frange: FileRange,
82     source_file: SourceFile,
83     should_compute_edit: bool,
84 }
85
86 impl<'a> AssistCtx<'a> {
87     pub fn new(
88         sema: &'a Semantics<'a, RootDatabase>,
89         frange: FileRange,
90         should_compute_edit: bool,
91     ) -> AssistCtx<'a> {
92         let source_file = sema.parse(frange.file_id);
93         AssistCtx { sema, db: sema.db, frange, source_file, should_compute_edit }
94     }
95
96     pub(crate) fn add_assist(
97         self,
98         id: AssistId,
99         label: impl Into<String>,
100         target: TextRange,
101         f: impl FnOnce(&mut ActionBuilder),
102     ) -> Option<Assist> {
103         let label = AssistLabel::new(id, label.into(), None, target);
104         let change_label = label.label.clone();
105         let mut info = AssistInfo::new(label);
106         if self.should_compute_edit {
107             let source_change = {
108                 let mut edit = ActionBuilder::new(&self);
109                 f(&mut edit);
110                 edit.build(change_label)
111             };
112             info = info.resolved(source_change)
113         };
114
115         Some(Assist(vec![info]))
116     }
117
118     pub(crate) fn add_assist_group(self, group_name: impl Into<String>) -> AssistGroup<'a> {
119         let group = GroupLabel(group_name.into());
120         AssistGroup { ctx: self, group, assists: Vec::new() }
121     }
122
123     pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
124         self.source_file.syntax().token_at_offset(self.frange.range.start())
125     }
126
127     pub(crate) fn find_token_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
128         self.token_at_offset().find(|it| it.kind() == kind)
129     }
130
131     pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
132         find_node_at_offset(self.source_file.syntax(), self.frange.range.start())
133     }
134
135     pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
136         self.sema
137             .find_node_at_offset_with_descend(self.source_file.syntax(), self.frange.range.start())
138     }
139
140     pub(crate) fn covering_element(&self) -> SyntaxElement {
141         find_covering_element(self.source_file.syntax(), self.frange.range)
142     }
143     pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
144         find_covering_element(self.source_file.syntax(), range)
145     }
146 }
147
148 pub(crate) struct AssistGroup<'a> {
149     ctx: AssistCtx<'a>,
150     group: GroupLabel,
151     assists: Vec<AssistInfo>,
152 }
153
154 impl<'a> AssistGroup<'a> {
155     pub(crate) fn add_assist(
156         &mut self,
157         id: AssistId,
158         label: impl Into<String>,
159         target: TextRange,
160         f: impl FnOnce(&mut ActionBuilder),
161     ) {
162         let label = AssistLabel::new(id, label.into(), Some(self.group.clone()), target);
163         let change_label = label.label.clone();
164         let mut info = AssistInfo::new(label).with_group(self.group.clone());
165         if self.ctx.should_compute_edit {
166             let source_change = {
167                 let mut edit = ActionBuilder::new(&self.ctx);
168                 f(&mut edit);
169                 edit.build(change_label)
170             };
171             info = info.resolved(source_change)
172         };
173
174         self.assists.push(info)
175     }
176
177     pub(crate) fn finish(self) -> Option<Assist> {
178         if self.assists.is_empty() {
179             None
180         } else {
181             Some(Assist(self.assists))
182         }
183     }
184 }
185
186 pub(crate) struct ActionBuilder<'a, 'b> {
187     edit: TextEditBuilder,
188     cursor_position: Option<TextSize>,
189     file: FileId,
190     ctx: &'a AssistCtx<'b>,
191 }
192
193 impl<'a, 'b> ActionBuilder<'a, 'b> {
194     fn new(ctx: &'a AssistCtx<'b>) -> Self {
195         Self {
196             edit: TextEditBuilder::default(),
197             cursor_position: None,
198             file: ctx.frange.file_id,
199             ctx,
200         }
201     }
202
203     pub(crate) fn ctx(&self) -> &AssistCtx<'b> {
204         &self.ctx
205     }
206
207     /// Replaces specified `range` of text with a given string.
208     pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
209         self.edit.replace(range, replace_with.into())
210     }
211
212     /// Replaces specified `node` of text with a given string, reindenting the
213     /// string to maintain `node`'s existing indent.
214     // FIXME: remove in favor of ra_syntax::edit::IndentLevel::increase_indent
215     pub(crate) fn replace_node_and_indent(
216         &mut self,
217         node: &SyntaxNode,
218         replace_with: impl Into<String>,
219     ) {
220         let mut replace_with = replace_with.into();
221         if let Some(indent) = leading_indent(node) {
222             replace_with = reindent(&replace_with, &indent)
223         }
224         self.replace(node.text_range(), replace_with)
225     }
226
227     /// Remove specified `range` of text.
228     #[allow(unused)]
229     pub(crate) fn delete(&mut self, range: TextRange) {
230         self.edit.delete(range)
231     }
232
233     /// Append specified `text` at the given `offset`
234     pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
235         self.edit.insert(offset, text.into())
236     }
237
238     /// Specify desired position of the cursor after the assist is applied.
239     pub(crate) fn set_cursor(&mut self, offset: TextSize) {
240         self.cursor_position = Some(offset)
241     }
242
243     /// Get access to the raw `TextEditBuilder`.
244     pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder {
245         &mut self.edit
246     }
247
248     pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
249         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
250     }
251     pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
252         let node = rewriter.rewrite_root().unwrap();
253         let new = rewriter.rewrite(&node);
254         algo::diff(&node, &new).into_text_edit(&mut self.edit)
255     }
256
257     pub(crate) fn set_file(&mut self, assist_file: FileId) {
258         self.file = assist_file;
259     }
260
261     fn build(self, change_label: String) -> SourceChange {
262         let edit = self.edit.finish();
263         if edit.is_empty() && self.cursor_position.is_none() {
264             panic!("Only call `add_assist` if the assist can be applied")
265         }
266         SingleFileChange { label: change_label, edit, cursor_position: self.cursor_position }
267             .into_source_change(self.file)
268     }
269 }