1 //! This module defines `AssistCtx` -- the API surface that is exposed to assists.
3 use ra_db::{FileId, FileRange};
4 use ra_fmt::{leading_indent, reindent};
6 source_change::{SingleFileChange, SourceChange},
10 algo::{self, find_covering_element, find_node_at_offset, SyntaxRewriter},
11 AstNode, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize,
14 use ra_text_edit::TextEditBuilder;
16 use crate::{AssistId, AssistLabel, GroupLabel, ResolvedAssist};
18 #[derive(Clone, Debug)]
19 pub(crate) struct Assist(pub(crate) Vec<AssistInfo>);
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>,
29 fn new(label: AssistLabel) -> AssistInfo {
30 AssistInfo { label, group_label: None, source_change: None }
33 fn resolved(self, source_change: SourceChange) -> AssistInfo {
34 AssistInfo { source_change: Some(source_change), ..self }
37 fn with_group(self, group_label: GroupLabel) -> AssistInfo {
38 AssistInfo { group_label: Some(group_label), ..self }
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 })
47 /// `AssistCtx` allows to apply an assist or check if it could be applied.
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.
54 /// There are two peculiarities here:
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.
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.
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.
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 :-)
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,
86 impl<'a> AssistCtx<'a> {
88 sema: &'a Semantics<'a, RootDatabase>,
90 should_compute_edit: bool,
92 let source_file = sema.parse(frange.file_id);
93 AssistCtx { sema, db: sema.db, frange, source_file, should_compute_edit }
96 pub(crate) fn add_assist(
99 label: impl Into<String>,
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);
110 edit.build(change_label)
112 info = info.resolved(source_change)
115 Some(Assist(vec![info]))
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() }
123 pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
124 self.source_file.syntax().token_at_offset(self.frange.range.start())
127 pub(crate) fn find_token_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
128 self.token_at_offset().find(|it| it.kind() == kind)
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())
135 pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
137 .find_node_at_offset_with_descend(self.source_file.syntax(), self.frange.range.start())
140 pub(crate) fn covering_element(&self) -> SyntaxElement {
141 find_covering_element(self.source_file.syntax(), self.frange.range)
143 pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
144 find_covering_element(self.source_file.syntax(), range)
148 pub(crate) struct AssistGroup<'a> {
151 assists: Vec<AssistInfo>,
154 impl<'a> AssistGroup<'a> {
155 pub(crate) fn add_assist(
158 label: impl Into<String>,
160 f: impl FnOnce(&mut ActionBuilder),
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);
169 edit.build(change_label)
171 info = info.resolved(source_change)
174 self.assists.push(info)
177 pub(crate) fn finish(self) -> Option<Assist> {
178 if self.assists.is_empty() {
181 Some(Assist(self.assists))
186 pub(crate) struct ActionBuilder<'a, 'b> {
187 edit: TextEditBuilder,
188 cursor_position: Option<TextSize>,
190 ctx: &'a AssistCtx<'b>,
193 impl<'a, 'b> ActionBuilder<'a, 'b> {
194 fn new(ctx: &'a AssistCtx<'b>) -> Self {
196 edit: TextEditBuilder::default(),
197 cursor_position: None,
198 file: ctx.frange.file_id,
203 pub(crate) fn ctx(&self) -> &AssistCtx<'b> {
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())
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(
218 replace_with: impl Into<String>,
220 let mut replace_with = replace_with.into();
221 if let Some(indent) = leading_indent(node) {
222 replace_with = reindent(&replace_with, &indent)
224 self.replace(node.text_range(), replace_with)
227 /// Remove specified `range` of text.
229 pub(crate) fn delete(&mut self, range: TextRange) {
230 self.edit.delete(range)
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())
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)
243 /// Get access to the raw `TextEditBuilder`.
244 pub(crate) fn text_edit_builder(&mut self) -> &mut TextEditBuilder {
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)
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)
257 pub(crate) fn set_file(&mut self, assist_file: FileId) {
258 self.file = assist_file;
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")
266 SingleFileChange { label: change_label, edit, cursor_position: self.cursor_position }
267 .into_source_change(self.file)