1 //! See `AssistContext`
7 base_db::{AnchoredPathBuf, FileId, FileRange},
12 source_change::{FileSystemEdit, SourceChange},
16 algo::{self, find_node_at_offset, SyntaxRewriter},
17 AstNode, AstToken, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange, TextSize,
20 use text_edit::{TextEdit, TextEditBuilder};
22 use crate::{assist_config::AssistConfig, Assist, AssistId, AssistKind, GroupLabel};
24 /// `AssistContext` allows to apply an assist or check if it could be applied.
26 /// Assists use a somewhat over-engineered approach, given the current needs.
27 /// The assists workflow consists of two phases. In the first phase, a user asks
28 /// for the list of available assists. In the second phase, the user picks a
29 /// particular assist and it gets applied.
31 /// There are two peculiarities here:
33 /// * first, we ideally avoid computing more things then necessary to answer "is
34 /// assist applicable" in the first phase.
35 /// * second, when we are applying assist, we don't have a guarantee that there
36 /// weren't any changes between the point when user asked for assists and when
37 /// they applied a particular assist. So, when applying assist, we need to do
38 /// all the checks from scratch.
40 /// To avoid repeating the same code twice for both "check" and "apply"
41 /// functions, we use an approach reminiscent of that of Django's function based
42 /// views dealing with forms. Each assist receives a runtime parameter,
43 /// `resolve`. It first check if an edit is applicable (potentially computing
44 /// info required to compute the actual edit). If it is applicable, and
45 /// `resolve` is `true`, it then computes the actual edit.
47 /// So, to implement the original assists workflow, we can first apply each edit
48 /// with `resolve = false`, and then applying the selected edit again, with
49 /// `resolve = true` this time.
51 /// Note, however, that we don't actually use such two-phase logic at the
52 /// moment, because the LSP API is pretty awkward in this place, and it's much
53 /// easier to just compute the edit eagerly :-)
54 pub(crate) struct AssistContext<'a> {
55 pub(crate) config: &'a AssistConfig,
56 pub(crate) sema: Semantics<'a, RootDatabase>,
57 pub(crate) frange: FileRange,
58 source_file: SourceFile,
61 impl<'a> AssistContext<'a> {
63 sema: Semantics<'a, RootDatabase>,
64 config: &'a AssistConfig,
66 ) -> AssistContext<'a> {
67 let source_file = sema.parse(frange.file_id);
68 AssistContext { config, sema, frange, source_file }
71 pub(crate) fn db(&self) -> &RootDatabase {
75 // NB, this ignores active selection.
76 pub(crate) fn offset(&self) -> TextSize {
77 self.frange.range.start()
80 pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
81 self.source_file.syntax().token_at_offset(self.offset())
83 pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
84 self.token_at_offset().find(|it| it.kind() == kind)
86 pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
87 self.token_at_offset().find_map(T::cast)
89 pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
90 find_node_at_offset(self.source_file.syntax(), self.offset())
92 pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
93 self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset())
95 pub(crate) fn covering_element(&self) -> SyntaxElement {
96 self.source_file.syntax().covering_element(self.frange.range)
99 pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
100 self.source_file.syntax().covering_element(range)
104 pub(crate) struct Assists {
108 allowed: Option<Vec<AssistKind>>,
112 pub(crate) fn new(ctx: &AssistContext, resolve: bool) -> Assists {
115 file: ctx.frange.file_id,
117 allowed: ctx.config.allowed.clone(),
121 pub(crate) fn finish(mut self) -> Vec<Assist> {
122 self.buf.sort_by_key(|assist| assist.target.len());
129 label: impl Into<String>,
131 f: impl FnOnce(&mut AssistBuilder),
133 if !self.is_allowed(&id) {
136 let label = Label::new(label.into());
137 let assist = Assist { id, label, group: None, target, source_change: None };
138 self.add_impl(assist, f)
141 pub(crate) fn add_group(
145 label: impl Into<String>,
147 f: impl FnOnce(&mut AssistBuilder),
149 if !self.is_allowed(&id) {
152 let label = Label::new(label.into());
153 let assist = Assist { id, label, group: Some(group.clone()), target, source_change: None };
154 self.add_impl(assist, f)
157 fn add_impl(&mut self, mut assist: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> {
158 let source_change = if self.resolve {
159 let mut builder = AssistBuilder::new(self.file);
161 Some(builder.finish())
165 assist.source_change = source_change.clone();
167 self.buf.push(assist);
171 fn is_allowed(&self, id: &AssistId) -> bool {
172 match &self.allowed {
173 Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
179 pub(crate) struct AssistBuilder {
180 edit: TextEditBuilder,
182 source_change: SourceChange,
186 pub(crate) fn new(file_id: FileId) -> AssistBuilder {
187 AssistBuilder { edit: TextEdit::builder(), file_id, source_change: SourceChange::default() }
190 pub(crate) fn edit_file(&mut self, file_id: FileId) {
192 self.file_id = file_id;
195 fn commit(&mut self) {
196 let edit = mem::take(&mut self.edit).finish();
197 if !edit.is_empty() {
198 self.source_change.insert_source_edit(self.file_id, edit);
202 /// Remove specified `range` of text.
203 pub(crate) fn delete(&mut self, range: TextRange) {
204 self.edit.delete(range)
206 /// Append specified `text` at the given `offset`
207 pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
208 self.edit.insert(offset, text.into())
210 /// Append specified `snippet` at the given `offset`
211 pub(crate) fn insert_snippet(
215 snippet: impl Into<String>,
217 self.source_change.is_snippet = true;
218 self.insert(offset, snippet);
220 /// Replaces specified `range` of text with a given string.
221 pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
222 self.edit.replace(range, replace_with.into())
224 /// Replaces specified `range` of text with a given `snippet`.
225 pub(crate) fn replace_snippet(
229 snippet: impl Into<String>,
231 self.source_change.is_snippet = true;
232 self.replace(range, snippet);
234 pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
235 algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
237 pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
238 if let Some(node) = rewriter.rewrite_root() {
239 let new = rewriter.rewrite(&node);
240 algo::diff(&node, &new).into_text_edit(&mut self.edit);
243 pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
244 let file_system_edit =
245 FileSystemEdit::CreateFile { dst: dst.clone(), initial_contents: content.into() };
246 self.source_change.push_file_system_edit(file_system_edit);
249 fn finish(mut self) -> SourceChange {
251 mem::take(&mut self.source_change)