Skip to main content

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`][vfs::Change].
5
6use std::{collections::hash_map::Entry, fmt, iter, mem};
7
8use crate::text_edit::{TextEdit, TextEditBuilder};
9use crate::{SnippetCap, assists::Command, syntax_helpers::tree_diff::diff};
10use base_db::AnchoredPathBuf;
11use itertools::Itertools;
12use macros::UpmapFromRaFixture;
13use nohash_hasher::IntMap;
14use rustc_hash::FxHashMap;
15use span::FileId;
16use stdx::never;
17use syntax::{
18    AstNode, SyntaxElement, SyntaxNode, 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, UpmapFromRaFixture)]
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    mutated_tree: Option<TreeMutator>,
232    /// Keeps track of where to place snippets
233    pub snippet_builder: Option<SnippetBuilder>,
234}
235
236struct 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 SourceChangeBuilder {
248    pub fn new(file_id: impl Into<FileId>) -> SourceChangeBuilder {
249        SourceChangeBuilder {
250            edit: TextEdit::builder(),
251            file_id: file_id.into(),
252            source_change: SourceChange::default(),
253            command: None,
254            file_editors: FxHashMap::default(),
255            snippet_annotations: vec![],
256            mutated_tree: None,
257            snippet_builder: None,
258        }
259    }
260
261    pub fn edit_file(&mut self, file_id: impl Into<FileId>) {
262        self.commit();
263        self.file_id = file_id.into();
264    }
265
266    pub fn make_editor(&self, node: &SyntaxNode) -> SyntaxEditor {
267        SyntaxEditor::new(node.ancestors().last().unwrap_or_else(|| node.clone())).0
268    }
269
270    pub fn add_file_edits(&mut self, file_id: impl Into<FileId>, editor: SyntaxEditor) {
271        match self.file_editors.entry(file_id.into()) {
272            Entry::Occupied(mut entry) => entry.get_mut().merge(editor),
273            Entry::Vacant(entry) => {
274                entry.insert(editor);
275            }
276        }
277    }
278
279    pub fn make_placeholder_snippet(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
280        self.add_snippet_annotation(AnnotationSnippet::Over)
281    }
282
283    pub fn make_tabstop_before(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
284        self.add_snippet_annotation(AnnotationSnippet::Before)
285    }
286
287    pub fn make_tabstop_after(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
288        self.add_snippet_annotation(AnnotationSnippet::After)
289    }
290
291    fn commit(&mut self) {
292        // Apply syntax editor edits
293        for (file_id, editor) in mem::take(&mut self.file_editors) {
294            let edit_result = editor.finish();
295            let mut snippet_edit = vec![];
296
297            // Find snippet edits
298            for (kind, annotation) in &self.snippet_annotations {
299                let elements = edit_result.find_annotation(*annotation);
300
301                let snippet = match (kind, elements) {
302                    (AnnotationSnippet::Before, [element]) => {
303                        Snippet::Tabstop(element.text_range().start())
304                    }
305                    (AnnotationSnippet::After, [element]) => {
306                        Snippet::Tabstop(element.text_range().end())
307                    }
308                    (AnnotationSnippet::Over, [element]) => {
309                        Snippet::Placeholder(element.text_range())
310                    }
311                    (AnnotationSnippet::Over, elements) if !elements.is_empty() => {
312                        Snippet::PlaceholderGroup(
313                            elements.iter().map(|it| it.text_range()).collect(),
314                        )
315                    }
316                    _ => continue,
317                };
318
319                snippet_edit.push(snippet);
320            }
321
322            let mut edit = TextEdit::builder();
323            diff(edit_result.old_root(), edit_result.new_root()).into_text_edit(&mut edit);
324            let edit = edit.finish();
325
326            let snippet_edit =
327                if !snippet_edit.is_empty() { Some(SnippetEdit::new(snippet_edit)) } else { None };
328
329            if !edit.is_empty() || snippet_edit.is_some() {
330                self.source_change.insert_source_and_snippet_edit(file_id, edit, snippet_edit);
331            }
332        }
333
334        // Apply mutable edits
335        let snippet_edit = self.snippet_builder.take().map(|builder| {
336            SnippetEdit::new(
337                builder.places.into_iter().flat_map(PlaceSnippet::finalize_position).collect(),
338            )
339        });
340
341        if let Some(tm) = self.mutated_tree.take() {
342            diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit);
343        }
344
345        let edit = mem::take(&mut self.edit).finish();
346        if !edit.is_empty() || snippet_edit.is_some() {
347            self.source_change.insert_source_and_snippet_edit(self.file_id, edit, snippet_edit);
348        }
349    }
350
351    /// Remove specified `range` of text.
352    pub fn delete(&mut self, range: TextRange) {
353        self.edit.delete(range)
354    }
355    /// Append specified `text` at the given `offset`
356    pub fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
357        self.edit.insert(offset, text.into())
358    }
359    /// Replaces specified `range` of text with a given string.
360    pub fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
361        self.edit.replace(range, replace_with.into())
362    }
363    pub fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
364        diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
365    }
366    pub fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
367        let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
368        self.source_change.push_file_system_edit(file_system_edit);
369    }
370    pub fn move_file(&mut self, src: impl Into<FileId>, dst: AnchoredPathBuf) {
371        let file_system_edit = FileSystemEdit::MoveFile { src: src.into(), dst };
372        self.source_change.push_file_system_edit(file_system_edit);
373    }
374
375    /// Triggers the parameter hint popup after the assist is applied
376    pub fn trigger_parameter_hints(&mut self) {
377        self.command = Some(Command::TriggerParameterHints);
378    }
379
380    /// Renames the item at the cursor position after the assist is applied
381    pub fn rename(&mut self) {
382        self.command = Some(Command::Rename);
383    }
384
385    /// Adds a tabstop snippet to place the cursor before `node`
386    pub fn add_tabstop_before(&mut self, _cap: SnippetCap, node: impl AstNode) {
387        assert!(node.syntax().parent().is_some());
388        self.add_snippet(PlaceSnippet::Before(node.syntax().clone().into()));
389    }
390
391    /// Adds a tabstop snippet to place the cursor before `token`
392    pub fn add_tabstop_before_token(&mut self, _cap: SnippetCap, token: SyntaxToken) {
393        assert!(token.parent().is_some());
394        self.add_snippet(PlaceSnippet::Before(token.into()));
395    }
396
397    /// Adds a tabstop snippet to place the cursor after `token`
398    pub fn add_tabstop_after_token(&mut self, _cap: SnippetCap, token: SyntaxToken) {
399        assert!(token.parent().is_some());
400        self.add_snippet(PlaceSnippet::After(token.into()));
401    }
402
403    /// Adds a snippet to move the cursor selected over `node`
404    pub fn add_placeholder_snippet(&mut self, _cap: SnippetCap, node: impl AstNode) {
405        assert!(node.syntax().parent().is_some());
406        self.add_snippet(PlaceSnippet::Over(node.syntax().clone().into()))
407    }
408
409    fn add_snippet(&mut self, snippet: PlaceSnippet) {
410        let snippet_builder = self.snippet_builder.get_or_insert(SnippetBuilder { places: vec![] });
411        snippet_builder.places.push(snippet);
412        self.source_change.is_snippet = true;
413    }
414
415    fn add_snippet_annotation(&mut self, kind: AnnotationSnippet) -> SyntaxAnnotation {
416        let annotation = SyntaxAnnotation::default();
417        self.snippet_annotations.push((kind, annotation));
418        self.source_change.is_snippet = true;
419        annotation
420    }
421
422    pub fn finish(mut self) -> SourceChange {
423        self.commit();
424
425        // Only one file can have snippet edits
426        stdx::never!(
427            self.source_change
428                .source_file_edits
429                .iter()
430                .filter(|(_, (_, snippet_edit))| snippet_edit.is_some())
431                .at_most_one()
432                .is_err()
433        );
434
435        mem::take(&mut self.source_change)
436    }
437}
438
439#[derive(Debug, Clone)]
440pub enum FileSystemEdit {
441    CreateFile { dst: AnchoredPathBuf, initial_contents: String },
442    MoveFile { src: FileId, dst: AnchoredPathBuf },
443    MoveDir { src: AnchoredPathBuf, src_id: FileId, dst: AnchoredPathBuf },
444}
445
446impl From<FileSystemEdit> for SourceChange {
447    fn from(edit: FileSystemEdit) -> SourceChange {
448        SourceChange {
449            source_file_edits: Default::default(),
450            file_system_edits: vec![edit],
451            is_snippet: false,
452            ..SourceChange::default()
453        }
454    }
455}
456
457pub enum Snippet {
458    /// A tabstop snippet (e.g. `$0`).
459    Tabstop(TextSize),
460    /// A placeholder snippet (e.g. `${0:placeholder}`).
461    Placeholder(TextRange),
462    /// A group of placeholder snippets, e.g.
463    ///
464    /// ```ignore
465    /// let ${0:new_var} = 4;
466    /// fun(1, 2, 3, ${0:new_var});
467    /// ```
468    PlaceholderGroup(Vec<TextRange>),
469}
470
471pub enum AnnotationSnippet {
472    /// Place a tabstop before an element
473    Before,
474    /// Place a tabstop before an element
475    After,
476    /// Place a placeholder snippet in place of the element(s)
477    Over,
478}
479
480enum PlaceSnippet {
481    /// Place a tabstop before an element
482    Before(SyntaxElement),
483    /// Place a tabstop before an element
484    After(SyntaxElement),
485    /// Place a placeholder snippet in place of the element
486    Over(SyntaxElement),
487}
488
489impl PlaceSnippet {
490    fn finalize_position(self) -> Vec<Snippet> {
491        match self {
492            PlaceSnippet::Before(it) => vec![Snippet::Tabstop(it.text_range().start())],
493            PlaceSnippet::After(it) => vec![Snippet::Tabstop(it.text_range().end())],
494            PlaceSnippet::Over(it) => vec![Snippet::Placeholder(it.text_range())],
495        }
496    }
497}