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, SyntaxRewriter},
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)
104 pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
105 self.source_file.syntax().covering_element(range)
109 pub(crate) struct Assists {
111 resolve: AssistResolveStrategy,
113 allowed: Option<Vec<AssistKind>>,
117 pub(crate) fn new(ctx: &AssistContext, resolve: AssistResolveStrategy) -> Assists {
120 file: ctx.frange.file_id,
122 allowed: ctx.config.allowed.clone(),
126 pub(crate) fn finish(mut self) -> Vec<Assist> {
127 self.buf.sort_by_key(|assist| assist.target.len());
134 label: impl Into<String>,
136 f: impl FnOnce(&mut AssistBuilder),
138 if !self.is_allowed(&id) {
141 let label = Label::new(label.into());
142 let assist = Assist { id, label, group: None, target, source_change: None };
143 self.add_impl(assist, f)
146 pub(crate) fn add_group(
150 label: impl Into<String>,
152 f: impl FnOnce(&mut AssistBuilder),
154 if !self.is_allowed(&id) {
157 let label = Label::new(label.into());
158 let assist = Assist { id, label, group: Some(group.clone()), target, source_change: None };
159 self.add_impl(assist, f)
162 fn add_impl(&mut self, mut assist: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> {
163 let source_change = if self.resolve.should_resolve(&assist.id) {
164 let mut builder = AssistBuilder::new(self.file);
166 Some(builder.finish())
170 assist.source_change = source_change;
172 self.buf.push(assist);
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<(SyntaxNode, SyntaxNode)>,
194 pub(crate) fn new(file_id: FileId) -> AssistBuilder {
196 edit: TextEdit::builder(),
198 source_change: SourceChange::default(),
203 pub(crate) fn edit_file(&mut self, file_id: FileId) {
205 self.file_id = file_id;
208 fn commit(&mut self) {
209 if let Some((old, new)) = self.mutated_tree.take() {
210 algo::diff(&old, &new).into_text_edit(&mut self.edit)
213 let edit = mem::take(&mut self.edit).finish();
214 if !edit.is_empty() {
215 self.source_change.insert_source_edit(self.file_id, edit);
219 pub(crate) fn make_ast_mut<N: AstNode>(&mut self, node: N) -> N {
220 N::cast(self.make_mut(node.syntax().clone())).unwrap()
222 /// Returns a copy of the `node`, suitable for mutation.
224 /// Syntax trees in rust-analyzer are typically immutable, and mutating
225 /// operations panic at runtime. However, it is possible to make a copy of
226 /// the tree and mutate the copy freely. Mutation is based on interior
227 /// mutability, and different nodes in the same tree see the same mutations.
229 /// The typical pattern for an assist is to find specific nodes in the read
230 /// phase, and then get their mutable couterparts using `make_mut` in the
232 pub(crate) fn make_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
235 .get_or_insert_with(|| {
236 let immutable = node.ancestors().last().unwrap();
237 let mutable = immutable.clone_for_update();
241 let ptr = SyntaxNodePtr::new(&&node);
245 /// Remove specified `range` of text.
246 pub(crate) fn delete(&mut self, range: TextRange) {
247 self.edit.delete(range)
249 /// Append specified `text` at the given `offset`
250 pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
251 self.edit.insert(offset, text.into())
253 /// Append specified `snippet` at the given `offset`
254 pub(crate) fn insert_snippet(
258 snippet: impl Into<String>,
260 self.source_change.is_snippet = true;
261 self.insert(offset, snippet);
263 /// Replaces specified `range` of text with a given string.
264 pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
265 self.edit.replace(range, replace_with.into())
267 /// Replaces specified `range` of text with a given `snippet`.
268 pub(crate) fn replace_snippet(
272 snippet: impl Into<String>,
274 self.source_change.is_snippet = true;
275 self.replace(range, snippet);
277 pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
278 algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
280 pub(crate) fn rewrite(&mut self, rewriter: SyntaxRewriter) {
281 if let Some(node) = rewriter.rewrite_root() {
282 let new = rewriter.rewrite(&node);
283 algo::diff(&node, &new).into_text_edit(&mut self.edit);
286 pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
287 let file_system_edit =
288 FileSystemEdit::CreateFile { dst: dst, initial_contents: content.into() };
289 self.source_change.push_file_system_edit(file_system_edit);
292 fn finish(mut self) -> SourceChange {
294 mem::take(&mut self.source_change)