1 //! See [`AssistContext`].
7 base_db::{AnchoredPathBuf, FileId, FileRange},
12 source_change::{FileSystemEdit, SourceChange},
16 algo::{self, find_node_at_offset, find_node_at_range},
17 AstNode, AstToken, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxNodePtr,
18 SyntaxToken, TextRange, TextSize, TokenAtOffset,
20 use text_edit::{TextEdit, TextEditBuilder};
23 assist_config::AssistConfig, Assist, AssistId, AssistKind, AssistResolveStrategy, GroupLabel,
26 /// `AssistContext` allows to apply an assist or check if it could be applied.
28 /// Assists use a somewhat over-engineered approach, given the current needs.
29 /// The assists workflow consists of two phases. In the first phase, a user asks
30 /// for the list of available assists. In the second phase, the user picks a
31 /// particular assist and it gets applied.
33 /// There are two peculiarities here:
35 /// * first, we ideally avoid computing more things then necessary to answer "is
36 /// assist applicable" in the first phase.
37 /// * second, when we are applying assist, we don't have a guarantee that there
38 /// weren't any changes between the point when user asked for assists and when
39 /// they applied a particular assist. So, when applying assist, we need to do
40 /// all the checks from scratch.
42 /// To avoid repeating the same code twice for both "check" and "apply"
43 /// functions, we use an approach reminiscent of that of Django's function based
44 /// views dealing with forms. Each assist receives a runtime parameter,
45 /// `resolve`. It first check if an edit is applicable (potentially computing
46 /// info required to compute the actual edit). If it is applicable, and
47 /// `resolve` is `true`, it then computes the actual edit.
49 /// So, to implement the original assists workflow, we can first apply each edit
50 /// with `resolve = false`, and then applying the selected edit again, with
51 /// `resolve = true` this time.
53 /// Note, however, that we don't actually use such two-phase logic at the
54 /// moment, because the LSP API is pretty awkward in this place, and it's much
55 /// easier to just compute the edit eagerly :-)
56 pub(crate) struct AssistContext<'a> {
57 pub(crate) config: &'a AssistConfig,
58 pub(crate) sema: Semantics<'a, RootDatabase>,
59 pub(crate) frange: FileRange,
60 source_file: SourceFile,
63 impl<'a> AssistContext<'a> {
65 sema: Semantics<'a, RootDatabase>,
66 config: &'a AssistConfig,
68 ) -> AssistContext<'a> {
69 let source_file = sema.parse(frange.file_id);
70 AssistContext { config, sema, frange, source_file }
73 pub(crate) fn db(&self) -> &RootDatabase {
77 // NB, this ignores active selection.
78 pub(crate) fn offset(&self) -> TextSize {
79 self.frange.range.start()
82 pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
83 self.source_file.syntax().token_at_offset(self.offset())
85 pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
86 self.token_at_offset().find(|it| it.kind() == kind)
88 pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
89 self.token_at_offset().find_map(T::cast)
91 pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
92 find_node_at_offset(self.source_file.syntax(), self.offset())
94 pub(crate) fn find_node_at_range<N: AstNode>(&self) -> Option<N> {
95 find_node_at_range(self.source_file.syntax(), self.frange.range)
97 pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
98 self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset())
100 pub(crate) fn covering_element(&self) -> SyntaxElement {
101 self.source_file.syntax().covering_element(self.frange.range)
105 pub(crate) struct Assists {
107 resolve: AssistResolveStrategy,
109 allowed: Option<Vec<AssistKind>>,
113 pub(crate) fn new(ctx: &AssistContext, resolve: AssistResolveStrategy) -> 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),
135 self.add_impl(None, id, label.into(), target, &mut |it| f.take().unwrap()(it))
138 pub(crate) fn add_group(
142 label: impl Into<String>,
144 f: impl FnOnce(&mut AssistBuilder),
147 self.add_impl(Some(group), id, label.into(), target, &mut |it| f.take().unwrap()(it))
152 group: Option<&GroupLabel>,
156 f: &mut dyn FnMut(&mut AssistBuilder),
158 if !self.is_allowed(&id) {
162 let source_change = if self.resolve.should_resolve(&id) {
163 let mut builder = AssistBuilder::new(self.file);
165 Some(builder.finish())
170 let label = Label::new(label);
171 let group = group.cloned();
172 self.buf.push(Assist { id, label, group, target, source_change });
176 fn is_allowed(&self, id: &AssistId) -> bool {
177 match &self.allowed {
178 Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
184 pub(crate) struct AssistBuilder {
185 edit: TextEditBuilder,
187 source_change: SourceChange,
189 /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
190 mutated_tree: Option<TreeMutator>,
193 pub(crate) struct TreeMutator {
194 immutable: SyntaxNode,
195 mutable_clone: SyntaxNode,
199 pub(crate) fn new(immutable: &SyntaxNode) -> TreeMutator {
200 let immutable = immutable.ancestors().last().unwrap();
201 let mutable_clone = immutable.clone_for_update();
202 TreeMutator { immutable, mutable_clone }
205 pub(crate) fn make_mut<N: AstNode>(&self, node: &N) -> N {
206 N::cast(self.make_syntax_mut(node.syntax())).unwrap()
209 pub(crate) fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
210 let ptr = SyntaxNodePtr::new(node);
211 ptr.to_node(&self.mutable_clone)
216 pub(crate) fn new(file_id: FileId) -> AssistBuilder {
218 edit: TextEdit::builder(),
220 source_change: SourceChange::default(),
225 pub(crate) fn edit_file(&mut self, file_id: FileId) {
227 self.file_id = file_id;
230 fn commit(&mut self) {
231 if let Some(tm) = self.mutated_tree.take() {
232 algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
235 let edit = mem::take(&mut self.edit).finish();
236 if !edit.is_empty() {
237 self.source_change.insert_source_edit(self.file_id, edit);
241 pub(crate) fn make_mut<N: AstNode>(&mut self, node: N) -> N {
242 self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
244 /// Returns a copy of the `node`, suitable for mutation.
246 /// Syntax trees in rust-analyzer are typically immutable, and mutating
247 /// operations panic at runtime. However, it is possible to make a copy of
248 /// the tree and mutate the copy freely. Mutation is based on interior
249 /// mutability, and different nodes in the same tree see the same mutations.
251 /// The typical pattern for an assist is to find specific nodes in the read
252 /// phase, and then get their mutable couterparts using `make_mut` in the
254 pub(crate) fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
255 self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
258 /// Remove specified `range` of text.
259 pub(crate) fn delete(&mut self, range: TextRange) {
260 self.edit.delete(range)
262 /// Append specified `text` at the given `offset`
263 pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
264 self.edit.insert(offset, text.into())
266 /// Append specified `snippet` at the given `offset`
267 pub(crate) fn insert_snippet(
271 snippet: impl Into<String>,
273 self.source_change.is_snippet = true;
274 self.insert(offset, snippet);
276 /// Replaces specified `range` of text with a given string.
277 pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
278 self.edit.replace(range, replace_with.into())
280 /// Replaces specified `range` of text with a given `snippet`.
281 pub(crate) fn replace_snippet(
285 snippet: impl Into<String>,
287 self.source_change.is_snippet = true;
288 self.replace(range, snippet);
290 pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
291 algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
293 pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
294 let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
295 self.source_change.push_file_system_edit(file_system_edit);
298 fn finish(mut self) -> SourceChange {
300 mem::take(&mut self.source_change)