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, Direction, 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>,
60 trimmed_range: TextRange,
61 source_file: SourceFile,
64 impl<'a> AssistContext<'a> {
66 sema: Semantics<'a, RootDatabase>,
67 config: &'a AssistConfig,
69 ) -> AssistContext<'a> {
70 let source_file = sema.parse(frange.file_id);
72 let start = frange.range.start();
73 let end = frange.range.end();
74 let left = source_file.syntax().token_at_offset(start);
75 let right = source_file.syntax().token_at_offset(end);
77 left.right_biased().and_then(|t| algo::skip_whitespace_token(t, Direction::Next));
79 right.left_biased().and_then(|t| algo::skip_whitespace_token(t, Direction::Prev));
80 let left = left.map(|t| t.text_range().start().clamp(start, end));
81 let right = right.map(|t| t.text_range().end().clamp(start, end));
83 let trimmed_range = match (left, right) {
84 (Some(left), Some(right)) if left <= right => TextRange::new(left, right),
85 // Selection solely consists of whitespace so just fall back to the original
89 AssistContext { config, sema, frange, source_file, trimmed_range }
92 pub(crate) fn db(&self) -> &RootDatabase {
96 // NB, this ignores active selection.
97 pub(crate) fn offset(&self) -> TextSize {
98 self.frange.range.start()
101 pub(crate) fn file_id(&self) -> FileId {
105 pub(crate) fn has_empty_selection(&self) -> bool {
106 self.trimmed_range.is_empty()
109 /// Returns the selected range trimmed for whitespace tokens, that is the range will be snapped
110 /// to the nearest enclosed token.
111 pub(crate) fn selection_trimmed(&self) -> TextRange {
115 pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
116 self.source_file.syntax().token_at_offset(self.offset())
118 pub(crate) fn find_token_syntax_at_offset(&self, kind: SyntaxKind) -> Option<SyntaxToken> {
119 self.token_at_offset().find(|it| it.kind() == kind)
121 pub(crate) fn find_token_at_offset<T: AstToken>(&self) -> Option<T> {
122 self.token_at_offset().find_map(T::cast)
124 pub(crate) fn find_node_at_offset<N: AstNode>(&self) -> Option<N> {
125 find_node_at_offset(self.source_file.syntax(), self.offset())
127 pub(crate) fn find_node_at_range<N: AstNode>(&self) -> Option<N> {
128 find_node_at_range(self.source_file.syntax(), self.trimmed_range)
130 pub(crate) fn find_node_at_offset_with_descend<N: AstNode>(&self) -> Option<N> {
131 self.sema.find_node_at_offset_with_descend(self.source_file.syntax(), self.offset())
133 /// Returns the element covered by the selection range, this excludes trailing whitespace in the selection.
134 pub(crate) fn covering_element(&self) -> SyntaxElement {
135 self.source_file.syntax().covering_element(self.selection_trimmed())
139 pub(crate) struct Assists {
141 resolve: AssistResolveStrategy,
143 allowed: Option<Vec<AssistKind>>,
147 pub(crate) fn new(ctx: &AssistContext, resolve: AssistResolveStrategy) -> Assists {
150 file: ctx.frange.file_id,
152 allowed: ctx.config.allowed.clone(),
156 pub(crate) fn finish(mut self) -> Vec<Assist> {
157 self.buf.sort_by_key(|assist| assist.target.len());
164 label: impl Into<String>,
166 f: impl FnOnce(&mut AssistBuilder),
169 self.add_impl(None, id, label.into(), target, &mut |it| f.take().unwrap()(it))
172 pub(crate) fn add_group(
176 label: impl Into<String>,
178 f: impl FnOnce(&mut AssistBuilder),
181 self.add_impl(Some(group), id, label.into(), target, &mut |it| f.take().unwrap()(it))
186 group: Option<&GroupLabel>,
190 f: &mut dyn FnMut(&mut AssistBuilder),
192 if !self.is_allowed(&id) {
196 let source_change = if self.resolve.should_resolve(&id) {
197 let mut builder = AssistBuilder::new(self.file);
199 Some(builder.finish())
204 let label = Label::new(label);
205 let group = group.cloned();
206 self.buf.push(Assist { id, label, group, target, source_change });
210 fn is_allowed(&self, id: &AssistId) -> bool {
211 match &self.allowed {
212 Some(allowed) => allowed.iter().any(|kind| kind.contains(id.1)),
218 pub(crate) struct AssistBuilder {
219 edit: TextEditBuilder,
221 source_change: SourceChange,
223 /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
224 mutated_tree: Option<TreeMutator>,
227 pub(crate) struct TreeMutator {
228 immutable: SyntaxNode,
229 mutable_clone: SyntaxNode,
233 pub(crate) fn new(immutable: &SyntaxNode) -> TreeMutator {
234 let immutable = immutable.ancestors().last().unwrap();
235 let mutable_clone = immutable.clone_for_update();
236 TreeMutator { immutable, mutable_clone }
239 pub(crate) fn make_mut<N: AstNode>(&self, node: &N) -> N {
240 N::cast(self.make_syntax_mut(node.syntax())).unwrap()
243 pub(crate) fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
244 let ptr = SyntaxNodePtr::new(node);
245 ptr.to_node(&self.mutable_clone)
250 pub(crate) fn new(file_id: FileId) -> AssistBuilder {
252 edit: TextEdit::builder(),
254 source_change: SourceChange::default(),
259 pub(crate) fn edit_file(&mut self, file_id: FileId) {
261 self.file_id = file_id;
264 fn commit(&mut self) {
265 if let Some(tm) = self.mutated_tree.take() {
266 algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
269 let edit = mem::take(&mut self.edit).finish();
270 if !edit.is_empty() {
271 self.source_change.insert_source_edit(self.file_id, edit);
275 pub(crate) fn make_mut<N: AstNode>(&mut self, node: N) -> N {
276 self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
278 /// Returns a copy of the `node`, suitable for mutation.
280 /// Syntax trees in rust-analyzer are typically immutable, and mutating
281 /// operations panic at runtime. However, it is possible to make a copy of
282 /// the tree and mutate the copy freely. Mutation is based on interior
283 /// mutability, and different nodes in the same tree see the same mutations.
285 /// The typical pattern for an assist is to find specific nodes in the read
286 /// phase, and then get their mutable couterparts using `make_mut` in the
288 pub(crate) fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
289 self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
292 /// Remove specified `range` of text.
293 pub(crate) fn delete(&mut self, range: TextRange) {
294 self.edit.delete(range)
296 /// Append specified `text` at the given `offset`
297 pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
298 self.edit.insert(offset, text.into())
300 /// Append specified `snippet` at the given `offset`
301 pub(crate) fn insert_snippet(
305 snippet: impl Into<String>,
307 self.source_change.is_snippet = true;
308 self.insert(offset, snippet);
310 /// Replaces specified `range` of text with a given string.
311 pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
312 self.edit.replace(range, replace_with.into())
314 /// Replaces specified `range` of text with a given `snippet`.
315 pub(crate) fn replace_snippet(
319 snippet: impl Into<String>,
321 self.source_change.is_snippet = true;
322 self.replace(range, snippet);
324 pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
325 algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
327 pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
328 let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
329 self.source_change.push_file_system_edit(file_system_edit);
331 pub(crate) fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
332 let file_system_edit = FileSystemEdit::MoveFile { src, dst };
333 self.source_change.push_file_system_edit(file_system_edit);
336 fn finish(mut self) -> SourceChange {
338 mem::take(&mut self.source_change)