ide_db/
source_change.rs

1//! This modules defines type to represent changes to the source code, that flow
2//! from the server to the client.
3//!
4//! It can be viewed as a dual for `Change`.
5
6use std::{collections::hash_map::Entry, fmt, iter, mem};
7
8use crate::imports::insert_use::{ImportScope, ImportScopeKind};
9use crate::text_edit::{TextEdit, TextEditBuilder};
10use crate::{SnippetCap, assists::Command, syntax_helpers::tree_diff::diff};
11use base_db::AnchoredPathBuf;
12use itertools::Itertools;
13use nohash_hasher::IntMap;
14use rustc_hash::FxHashMap;
15use span::FileId;
16use stdx::never;
17use syntax::{
18    AstNode, SyntaxElement, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextSize,
19    syntax_editor::{SyntaxAnnotation, SyntaxEditor},
20};
21
22/// An annotation ID associated with an indel, to describe changes.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub struct ChangeAnnotationId(u32);
25
26impl fmt::Display for ChangeAnnotationId {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        fmt::Display::fmt(&self.0, f)
29    }
30}
31
32#[derive(Debug, Clone)]
33pub struct ChangeAnnotation {
34    pub label: String,
35    pub needs_confirmation: bool,
36    pub description: Option<String>,
37}
38
39#[derive(Default, Debug, Clone)]
40pub struct SourceChange {
41    pub source_file_edits: IntMap<FileId, (TextEdit, Option<SnippetEdit>)>,
42    pub file_system_edits: Vec<FileSystemEdit>,
43    pub is_snippet: bool,
44    pub annotations: FxHashMap<ChangeAnnotationId, ChangeAnnotation>,
45    next_annotation_id: u32,
46}
47
48impl SourceChange {
49    pub fn from_text_edit(file_id: impl Into<FileId>, edit: TextEdit) -> Self {
50        SourceChange {
51            source_file_edits: iter::once((file_id.into(), (edit, None))).collect(),
52            ..Default::default()
53        }
54    }
55
56    pub fn insert_annotation(&mut self, annotation: ChangeAnnotation) -> ChangeAnnotationId {
57        let id = ChangeAnnotationId(self.next_annotation_id);
58        self.next_annotation_id += 1;
59        self.annotations.insert(id, annotation);
60        id
61    }
62
63    /// Inserts a [`TextEdit`] for the given [`FileId`]. This properly handles merging existing
64    /// edits for a file if some already exist.
65    pub fn insert_source_edit(&mut self, file_id: impl Into<FileId>, edit: TextEdit) {
66        self.insert_source_and_snippet_edit(file_id.into(), edit, None)
67    }
68
69    /// Inserts a [`TextEdit`] and potentially a [`SnippetEdit`] for the given [`FileId`].
70    /// This properly handles merging existing edits for a file if some already exist.
71    pub fn insert_source_and_snippet_edit(
72        &mut self,
73        file_id: impl Into<FileId>,
74        edit: TextEdit,
75        snippet_edit: Option<SnippetEdit>,
76    ) {
77        match self.source_file_edits.entry(file_id.into()) {
78            Entry::Occupied(mut entry) => {
79                let value = entry.get_mut();
80                never!(value.0.union(edit).is_err(), "overlapping edits for same file");
81                never!(
82                    value.1.is_some() && snippet_edit.is_some(),
83                    "overlapping snippet edits for same file"
84                );
85                if value.1.is_none() {
86                    value.1 = snippet_edit;
87                }
88            }
89            Entry::Vacant(entry) => {
90                entry.insert((edit, snippet_edit));
91            }
92        }
93    }
94
95    pub fn push_file_system_edit(&mut self, edit: FileSystemEdit) {
96        self.file_system_edits.push(edit);
97    }
98
99    pub fn get_source_and_snippet_edit(
100        &self,
101        file_id: FileId,
102    ) -> Option<&(TextEdit, Option<SnippetEdit>)> {
103        self.source_file_edits.get(&file_id)
104    }
105
106    pub fn merge(mut self, other: SourceChange) -> SourceChange {
107        self.extend(other.source_file_edits);
108        self.extend(other.file_system_edits);
109        self.is_snippet |= other.is_snippet;
110        self
111    }
112}
113
114impl Extend<(FileId, TextEdit)> for SourceChange {
115    fn extend<T: IntoIterator<Item = (FileId, TextEdit)>>(&mut self, iter: T) {
116        self.extend(iter.into_iter().map(|(file_id, edit)| (file_id, (edit, None))))
117    }
118}
119
120impl Extend<(FileId, (TextEdit, Option<SnippetEdit>))> for SourceChange {
121    fn extend<T: IntoIterator<Item = (FileId, (TextEdit, Option<SnippetEdit>))>>(
122        &mut self,
123        iter: T,
124    ) {
125        iter.into_iter().for_each(|(file_id, (edit, snippet_edit))| {
126            self.insert_source_and_snippet_edit(file_id, edit, snippet_edit)
127        });
128    }
129}
130
131impl Extend<FileSystemEdit> for SourceChange {
132    fn extend<T: IntoIterator<Item = FileSystemEdit>>(&mut self, iter: T) {
133        iter.into_iter().for_each(|edit| self.push_file_system_edit(edit));
134    }
135}
136
137impl From<IntMap<FileId, TextEdit>> for SourceChange {
138    fn from(source_file_edits: IntMap<FileId, TextEdit>) -> SourceChange {
139        let source_file_edits =
140            source_file_edits.into_iter().map(|(file_id, edit)| (file_id, (edit, None))).collect();
141        SourceChange {
142            source_file_edits,
143            file_system_edits: Vec::new(),
144            is_snippet: false,
145            ..SourceChange::default()
146        }
147    }
148}
149
150impl FromIterator<(FileId, TextEdit)> for SourceChange {
151    fn from_iter<T: IntoIterator<Item = (FileId, TextEdit)>>(iter: T) -> Self {
152        let mut this = SourceChange::default();
153        this.extend(iter);
154        this
155    }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct SnippetEdit(Vec<(u32, TextRange)>);
160
161impl SnippetEdit {
162    pub fn new(snippets: Vec<Snippet>) -> Self {
163        let mut snippet_ranges = snippets
164            .into_iter()
165            .zip(1..)
166            .with_position()
167            .flat_map(|pos| {
168                let (snippet, index) = match pos {
169                    (itertools::Position::First, it) | (itertools::Position::Middle, it) => it,
170                    // last/only snippet gets index 0
171                    (itertools::Position::Last, (snippet, _))
172                    | (itertools::Position::Only, (snippet, _)) => (snippet, 0),
173                };
174
175                match snippet {
176                    Snippet::Tabstop(pos) => vec![(index, TextRange::empty(pos))],
177                    Snippet::Placeholder(range) => vec![(index, range)],
178                    Snippet::PlaceholderGroup(ranges) => {
179                        ranges.into_iter().map(|range| (index, range)).collect()
180                    }
181                }
182            })
183            .collect_vec();
184
185        snippet_ranges.sort_by_key(|(_, range)| range.start());
186
187        // Ensure that none of the ranges overlap
188        let disjoint_ranges = snippet_ranges
189            .iter()
190            .zip(snippet_ranges.iter().skip(1))
191            .all(|((_, left), (_, right))| left.end() <= right.start() || left == right);
192        stdx::always!(disjoint_ranges);
193
194        SnippetEdit(snippet_ranges)
195    }
196
197    /// Inserts all of the snippets into the given text.
198    pub fn apply(&self, text: &mut String) {
199        // Start from the back so that we don't have to adjust ranges
200        for (index, range) in self.0.iter().rev() {
201            if range.is_empty() {
202                // is a tabstop
203                text.insert_str(range.start().into(), &format!("${index}"));
204            } else {
205                // is a placeholder
206                text.insert(range.end().into(), '}');
207                text.insert_str(range.start().into(), &format!("${{{index}:"));
208            }
209        }
210    }
211
212    /// Gets the underlying snippet index + text range
213    /// Tabstops are represented by an empty range, and placeholders use the range that they were given
214    pub fn into_edit_ranges(self) -> Vec<(u32, TextRange)> {
215        self.0
216    }
217}
218
219pub struct SourceChangeBuilder {
220    pub edit: TextEditBuilder,
221    pub file_id: FileId,
222    pub source_change: SourceChange,
223    pub command: Option<Command>,
224
225    /// Keeps track of all edits performed on each file
226    pub file_editors: FxHashMap<FileId, SyntaxEditor>,
227    /// Keeps track of which annotations correspond to which snippets
228    pub snippet_annotations: Vec<(AnnotationSnippet, SyntaxAnnotation)>,
229
230    /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
231    pub mutated_tree: Option<TreeMutator>,
232    /// Keeps track of where to place snippets
233    pub snippet_builder: Option<SnippetBuilder>,
234}
235
236pub struct TreeMutator {
237    immutable: SyntaxNode,
238    mutable_clone: SyntaxNode,
239}
240
241#[derive(Default)]
242pub struct SnippetBuilder {
243    /// Where to place snippets at
244    places: Vec<PlaceSnippet>,
245}
246
247impl TreeMutator {
248    pub fn new(immutable: &SyntaxNode) -> TreeMutator {
249        let immutable = immutable.ancestors().last().unwrap();
250        let mutable_clone = immutable.clone_for_update();
251        TreeMutator { immutable, mutable_clone }
252    }
253
254    pub fn make_mut<N: AstNode>(&self, node: &N) -> N {
255        N::cast(self.make_syntax_mut(node.syntax())).unwrap()
256    }
257
258    pub fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
259        let ptr = SyntaxNodePtr::new(node);
260        ptr.to_node(&self.mutable_clone)
261    }
262}
263
264impl SourceChangeBuilder {
265    pub fn new(file_id: impl Into<FileId>) -> SourceChangeBuilder {
266        SourceChangeBuilder {
267            edit: TextEdit::builder(),
268            file_id: file_id.into(),
269            source_change: SourceChange::default(),
270            command: None,
271            file_editors: FxHashMap::default(),
272            snippet_annotations: vec![],
273            mutated_tree: None,
274            snippet_builder: None,
275        }
276    }
277
278    pub fn edit_file(&mut self, file_id: impl Into<FileId>) {
279        self.commit();
280        self.file_id = file_id.into();
281    }
282
283    pub fn make_editor(&self, node: &SyntaxNode) -> SyntaxEditor {
284        SyntaxEditor::new(node.ancestors().last().unwrap_or_else(|| node.clone()))
285    }
286
287    pub fn add_file_edits(&mut self, file_id: impl Into<FileId>, edit: SyntaxEditor) {
288        match self.file_editors.entry(file_id.into()) {
289            Entry::Occupied(mut entry) => entry.get_mut().merge(edit),
290            Entry::Vacant(entry) => {
291                entry.insert(edit);
292            }
293        }
294    }
295
296    pub fn make_placeholder_snippet(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
297        self.add_snippet_annotation(AnnotationSnippet::Over)
298    }
299
300    pub fn make_tabstop_before(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
301        self.add_snippet_annotation(AnnotationSnippet::Before)
302    }
303
304    pub fn make_tabstop_after(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
305        self.add_snippet_annotation(AnnotationSnippet::After)
306    }
307
308    fn commit(&mut self) {
309        // Apply syntax editor edits
310        for (file_id, editor) in mem::take(&mut self.file_editors) {
311            let edit_result = editor.finish();
312            let mut snippet_edit = vec![];
313
314            // Find snippet edits
315            for (kind, annotation) in &self.snippet_annotations {
316                let elements = edit_result.find_annotation(*annotation);
317
318                let snippet = match (kind, elements) {
319                    (AnnotationSnippet::Before, [element]) => {
320                        Snippet::Tabstop(element.text_range().start())
321                    }
322                    (AnnotationSnippet::After, [element]) => {
323                        Snippet::Tabstop(element.text_range().end())
324                    }
325                    (AnnotationSnippet::Over, [element]) => {
326                        Snippet::Placeholder(element.text_range())
327                    }
328                    (AnnotationSnippet::Over, elements) if !elements.is_empty() => {
329                        Snippet::PlaceholderGroup(
330                            elements.iter().map(|it| it.text_range()).collect(),
331                        )
332                    }
333                    _ => continue,
334                };
335
336                snippet_edit.push(snippet);
337            }
338
339            let mut edit = TextEdit::builder();
340            diff(edit_result.old_root(), edit_result.new_root()).into_text_edit(&mut edit);
341            let edit = edit.finish();
342
343            let snippet_edit =
344                if !snippet_edit.is_empty() { Some(SnippetEdit::new(snippet_edit)) } else { None };
345
346            if !edit.is_empty() || snippet_edit.is_some() {
347                self.source_change.insert_source_and_snippet_edit(file_id, edit, snippet_edit);
348            }
349        }
350
351        // Apply mutable edits
352        let snippet_edit = self.snippet_builder.take().map(|builder| {
353            SnippetEdit::new(
354                builder.places.into_iter().flat_map(PlaceSnippet::finalize_position).collect(),
355            )
356        });
357
358        if let Some(tm) = self.mutated_tree.take() {
359            diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit);
360        }
361
362        let edit = mem::take(&mut self.edit).finish();
363        if !edit.is_empty() || snippet_edit.is_some() {
364            self.source_change.insert_source_and_snippet_edit(self.file_id, edit, snippet_edit);
365        }
366    }
367
368    pub fn make_mut<N: AstNode>(&mut self, node: N) -> N {
369        self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
370    }
371
372    pub fn make_import_scope_mut(&mut self, scope: ImportScope) -> ImportScope {
373        ImportScope {
374            kind: match scope.kind.clone() {
375                ImportScopeKind::File(it) => ImportScopeKind::File(self.make_mut(it)),
376                ImportScopeKind::Module(it) => ImportScopeKind::Module(self.make_mut(it)),
377                ImportScopeKind::Block(it) => ImportScopeKind::Block(self.make_mut(it)),
378            },
379            required_cfgs: scope.required_cfgs.iter().map(|it| self.make_mut(it.clone())).collect(),
380        }
381    }
382    /// Returns a copy of the `node`, suitable for mutation.
383    ///
384    /// Syntax trees in rust-analyzer are typically immutable, and mutating
385    /// operations panic at runtime. However, it is possible to make a copy of
386    /// the tree and mutate the copy freely. Mutation is based on interior
387    /// mutability, and different nodes in the same tree see the same mutations.
388    ///
389    /// The typical pattern for an assist is to find specific nodes in the read
390    /// phase, and then get their mutable counterparts using `make_mut` in the
391    /// mutable state.
392    pub fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
393        self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
394    }
395
396    /// Remove specified `range` of text.
397    pub fn delete(&mut self, range: TextRange) {
398        self.edit.delete(range)
399    }
400    /// Append specified `text` at the given `offset`
401    pub fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
402        self.edit.insert(offset, text.into())
403    }
404    /// Replaces specified `range` of text with a given string.
405    pub fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
406        self.edit.replace(range, replace_with.into())
407    }
408    pub fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
409        diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
410    }
411    pub fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
412        let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
413        self.source_change.push_file_system_edit(file_system_edit);
414    }
415    pub fn move_file(&mut self, src: impl Into<FileId>, dst: AnchoredPathBuf) {
416        let file_system_edit = FileSystemEdit::MoveFile { src: src.into(), dst };
417        self.source_change.push_file_system_edit(file_system_edit);
418    }
419
420    /// Triggers the parameter hint popup after the assist is applied
421    pub fn trigger_parameter_hints(&mut self) {
422        self.command = Some(Command::TriggerParameterHints);
423    }
424
425    /// Renames the item at the cursor position after the assist is applied
426    pub fn rename(&mut self) {
427        self.command = Some(Command::Rename);
428    }
429
430    /// Adds a tabstop snippet to place the cursor before `node`
431    pub fn add_tabstop_before(&mut self, _cap: SnippetCap, node: impl AstNode) {
432        assert!(node.syntax().parent().is_some());
433        self.add_snippet(PlaceSnippet::Before(node.syntax().clone().into()));
434    }
435
436    /// Adds a tabstop snippet to place the cursor after `node`
437    pub fn add_tabstop_after(&mut self, _cap: SnippetCap, node: impl AstNode) {
438        assert!(node.syntax().parent().is_some());
439        self.add_snippet(PlaceSnippet::After(node.syntax().clone().into()));
440    }
441
442    /// Adds a tabstop snippet to place the cursor before `token`
443    pub fn add_tabstop_before_token(&mut self, _cap: SnippetCap, token: SyntaxToken) {
444        assert!(token.parent().is_some());
445        self.add_snippet(PlaceSnippet::Before(token.into()));
446    }
447
448    /// Adds a tabstop snippet to place the cursor after `token`
449    pub fn add_tabstop_after_token(&mut self, _cap: SnippetCap, token: SyntaxToken) {
450        assert!(token.parent().is_some());
451        self.add_snippet(PlaceSnippet::After(token.into()));
452    }
453
454    /// Adds a snippet to move the cursor selected over `node`
455    pub fn add_placeholder_snippet(&mut self, _cap: SnippetCap, node: impl AstNode) {
456        assert!(node.syntax().parent().is_some());
457        self.add_snippet(PlaceSnippet::Over(node.syntax().clone().into()))
458    }
459
460    /// Adds a snippet to move the cursor selected over `token`
461    pub fn add_placeholder_snippet_token(&mut self, _cap: SnippetCap, token: SyntaxToken) {
462        assert!(token.parent().is_some());
463        self.add_snippet(PlaceSnippet::Over(token.into()))
464    }
465
466    /// Adds a snippet to move the cursor selected over `nodes`
467    ///
468    /// This allows for renaming newly generated items without having to go
469    /// through a separate rename step.
470    pub fn add_placeholder_snippet_group(&mut self, _cap: SnippetCap, nodes: Vec<SyntaxNode>) {
471        assert!(nodes.iter().all(|node| node.parent().is_some()));
472        self.add_snippet(PlaceSnippet::OverGroup(
473            nodes.into_iter().map(|node| node.into()).collect(),
474        ))
475    }
476
477    fn add_snippet(&mut self, snippet: PlaceSnippet) {
478        let snippet_builder = self.snippet_builder.get_or_insert(SnippetBuilder { places: vec![] });
479        snippet_builder.places.push(snippet);
480        self.source_change.is_snippet = true;
481    }
482
483    fn add_snippet_annotation(&mut self, kind: AnnotationSnippet) -> SyntaxAnnotation {
484        let annotation = SyntaxAnnotation::default();
485        self.snippet_annotations.push((kind, annotation));
486        self.source_change.is_snippet = true;
487        annotation
488    }
489
490    pub fn finish(mut self) -> SourceChange {
491        self.commit();
492
493        // Only one file can have snippet edits
494        stdx::never!(
495            self.source_change
496                .source_file_edits
497                .iter()
498                .filter(|(_, (_, snippet_edit))| snippet_edit.is_some())
499                .at_most_one()
500                .is_err()
501        );
502
503        mem::take(&mut self.source_change)
504    }
505}
506
507#[derive(Debug, Clone)]
508pub enum FileSystemEdit {
509    CreateFile { dst: AnchoredPathBuf, initial_contents: String },
510    MoveFile { src: FileId, dst: AnchoredPathBuf },
511    MoveDir { src: AnchoredPathBuf, src_id: FileId, dst: AnchoredPathBuf },
512}
513
514impl From<FileSystemEdit> for SourceChange {
515    fn from(edit: FileSystemEdit) -> SourceChange {
516        SourceChange {
517            source_file_edits: Default::default(),
518            file_system_edits: vec![edit],
519            is_snippet: false,
520            ..SourceChange::default()
521        }
522    }
523}
524
525pub enum Snippet {
526    /// A tabstop snippet (e.g. `$0`).
527    Tabstop(TextSize),
528    /// A placeholder snippet (e.g. `${0:placeholder}`).
529    Placeholder(TextRange),
530    /// A group of placeholder snippets, e.g.
531    ///
532    /// ```ignore
533    /// let ${0:new_var} = 4;
534    /// fun(1, 2, 3, ${0:new_var});
535    /// ```
536    PlaceholderGroup(Vec<TextRange>),
537}
538
539pub enum AnnotationSnippet {
540    /// Place a tabstop before an element
541    Before,
542    /// Place a tabstop before an element
543    After,
544    /// Place a placeholder snippet in place of the element(s)
545    Over,
546}
547
548enum PlaceSnippet {
549    /// Place a tabstop before an element
550    Before(SyntaxElement),
551    /// Place a tabstop before an element
552    After(SyntaxElement),
553    /// Place a placeholder snippet in place of the element
554    Over(SyntaxElement),
555    /// Place a group of placeholder snippets which are linked together
556    /// in place of the elements
557    OverGroup(Vec<SyntaxElement>),
558}
559
560impl PlaceSnippet {
561    fn finalize_position(self) -> Vec<Snippet> {
562        match self {
563            PlaceSnippet::Before(it) => vec![Snippet::Tabstop(it.text_range().start())],
564            PlaceSnippet::After(it) => vec![Snippet::Tabstop(it.text_range().end())],
565            PlaceSnippet::Over(it) => vec![Snippet::Placeholder(it.text_range())],
566            PlaceSnippet::OverGroup(it) => {
567                vec![Snippet::PlaceholderGroup(it.into_iter().map(|it| it.text_range()).collect())]
568            }
569        }
570    }
571}