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