1 //! See `AssistContext`
5 use algo::find_covering_element;
8 base_db::{AnchoredPathBuf, FileId, FileRange},
13 source_change::{FileSystemEdit, SourceChange},
17 algo::{self, find_node_at_offset, SyntaxRewriter},
18 AstNode, AstToken, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange, TextSize,
21 use text_edit::{TextEdit, TextEditBuilder};
23 use crate::{assist_config::AssistConfig, Assist, AssistId, AssistKind, GroupLabel};
25 /// `AssistContext` allows to apply an assist or check if it could be applied.
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.
32 /// There are two peculiarities here:
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.
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.
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.
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,
62 impl<'a> AssistContext<'a> {
64 sema: Semantics<'a, RootDatabase>,
65 config: &'a AssistConfig,
67 ) -> AssistContext<'a> {
68 let source_file = sema.parse(frange.file_id);
69 AssistContext { config, sema, frange, source_file }
72 pub(crate) fn db(&self) -> &RootDatabase {
76 // NB, this ignores active selection.
77 pub(crate) fn offset(&self) -> TextSize {
78 self.frange.range.start()
81 pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
82 self.source_file.syntax().token_at_offset(self.offset())
84 pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
85 self.token_at_offset().find(|it| it.kind() == kind)
87 pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
88 self.token_at_offset().find_map(T::cast)
90 pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
91 find_node_at_offset(self.source_file.syntax(), self.offset())
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())
96 pub(crate) fn covering_element(&self) -> SyntaxElement {
97 find_covering_element(self.source_file.syntax(), self.frange.range)
100 pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
101 find_covering_element(self.source_file.syntax(), range)
105 pub(crate) struct Assists {
109 allowed: Option<Vec<AssistKind>>,
113 pub(crate) fn new(ctx: &AssistContext, resolve: bool) -> Assists {
116 file: ctx.frange.file_id,
118 allowed: ctx.config.allowed.clone(),
122 pub(crate) fn finish(mut self) -> Vec<Assist> {
123 self.buf.sort_by_key(|assist| assist.target.len());
130 label: impl Into<String>,
132 f: impl FnOnce(&mut AssistBuilder),
134 if !self.is_allowed(&id) {
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)
142 pub(crate) fn add_group(
146 label: impl Into<String>,
148 f: impl FnOnce(&mut AssistBuilder),
150 if !self.is_allowed(&id) {
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)
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);
162 Some(builder.finish())
166 assist.source_change = source_change.clone();
168 self.buf.push(assist);
172 fn is_allowed(&self, id: &AssistId) -> bool {
173 match &self.allowed {
174 Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
180 pub(crate) struct AssistBuilder {
181 edit: TextEditBuilder,
183 source_change: SourceChange,
187 pub(crate) fn new(file_id: FileId) -> AssistBuilder {
188 AssistBuilder { edit: TextEdit::builder(), file_id, source_change: SourceChange::default() }
191 pub(crate) fn edit_file(&mut self, file_id: FileId) {
193 self.file_id = file_id;
196 fn commit(&mut self) {
197 let edit = mem::take(&mut self.edit).finish();
198 if !edit.is_empty() {
199 self.source_change.insert_source_edit(self.file_id, edit);
203 /// Remove specified `range` of text.
204 pub(crate) fn delete(&mut self, range: TextRange) {
205 self.edit.delete(range)
207 /// Append specified `text` at the given `offset`
208 pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
209 self.edit.insert(offset, text.into())
211 /// Append specified `snippet` at the given `offset`
212 pub(crate) fn insert_snippet(
216 snippet: impl Into<String>,
218 self.source_change.is_snippet = true;
219 self.insert(offset, snippet);
221 /// Replaces specified `range` of text with a given string.
222 pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
223 self.edit.replace(range, replace_with.into())
225 /// Replaces specified `range` of text with a given `snippet`.
226 pub(crate) fn replace_snippet(
230 snippet: impl Into<String>,
232 self.source_change.is_snippet = true;
233 self.replace(range, snippet);
235 pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
236 algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
238 pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
239 if let Some(node) = rewriter.rewrite_root() {
240 let new = rewriter.rewrite(&node);
241 algo::diff(&node, &new).into_text_edit(&mut self.edit);
244 pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
245 let file_system_edit =
246 FileSystemEdit::CreateFile { dst: dst.clone(), initial_contents: content.into() };
247 self.source_change.push_file_system_edit(file_system_edit);
250 fn finish(mut self) -> SourceChange {
252 mem::take(&mut self.source_change)