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(|(position, (snippet, index))| {
168                // The last/only snippet gets index 0.
169                let index = if position.is_last { 0 } else { index };
170
171                match snippet {
172                    Snippet::Tabstop(pos) => vec![(index, TextRange::empty(pos))],
173                    Snippet::Placeholder(range) => vec![(index, range)],
174                    Snippet::PlaceholderGroup(ranges) => {
175                        ranges.into_iter().map(|range| (index, range)).collect()
176                    }
177                }
178            })
179            .collect_vec();
180
181        snippet_ranges.sort_by_key(|(_, range)| range.start());
182
183        // Ensure that none of the ranges overlap
184        let disjoint_ranges = snippet_ranges
185            .iter()
186            .zip(snippet_ranges.iter().skip(1))
187            .all(|((_, left), (_, right))| left.end() <= right.start() || left == right);
188        stdx::always!(disjoint_ranges);
189
190        SnippetEdit(snippet_ranges)
191    }
192
193    /// Inserts all of the snippets into the given text.
194    pub fn apply(&self, text: &mut String) {
195        // Start from the back so that we don't have to adjust ranges
196        for (index, range) in self.0.iter().rev() {
197            if range.is_empty() {
198                // is a tabstop
199                text.insert_str(range.start().into(), &format!("${index}"));
200            } else {
201                // is a placeholder
202                text.insert(range.end().into(), '}');
203                text.insert_str(range.start().into(), &format!("${{{index}:"));
204            }
205        }
206    }
207
208    /// Gets the underlying snippet index + text range
209    /// Tabstops are represented by an empty range, and placeholders use the range that they were given
210    pub fn into_edit_ranges(self) -> Vec<(u32, TextRange)> {
211        self.0
212    }
213
214    /// Escapes `\` and `$` so that they don't get interpreted as snippet-specific constructs.
215    ///
216    /// Note that we don't need to escape the other characters that can be escaped,
217    /// because they wouldn't be treated as snippet-specific constructs without '$'.
218    pub fn escape_snippet_bits(text: &mut String) {
219        stdx::replace(text, '\\', "\\\\");
220        stdx::replace(text, '$', "\\$");
221    }
222}
223
224pub struct SourceChangeBuilder {
225    pub edit: TextEditBuilder,
226    pub file_id: FileId,
227    pub source_change: SourceChange,
228    pub command: Option<Command>,
229
230    /// Keeps track of all edits performed on each file
231    pub file_editors: FxHashMap<FileId, SyntaxEditor>,
232    /// Keeps track of which annotations correspond to which snippets
233    pub snippet_annotations: Vec<(AnnotationSnippet, SyntaxAnnotation)>,
234
235    /// Keeps track of where to place snippets
236    pub snippet_builder: Option<SnippetBuilder>,
237}
238
239#[derive(Default)]
240pub struct SnippetBuilder {
241    /// Where to place snippets at
242    places: Vec<PlaceSnippet>,
243}
244
245impl SourceChangeBuilder {
246    pub fn new(file_id: impl Into<FileId>) -> SourceChangeBuilder {
247        SourceChangeBuilder {
248            edit: TextEdit::builder(),
249            file_id: file_id.into(),
250            source_change: SourceChange::default(),
251            command: None,
252            file_editors: FxHashMap::default(),
253            snippet_annotations: vec![],
254            snippet_builder: None,
255        }
256    }
257
258    pub fn edit_file(&mut self, file_id: impl Into<FileId>) {
259        self.commit();
260        self.file_id = file_id.into();
261    }
262
263    pub fn make_editor(&self, node: &SyntaxNode) -> SyntaxEditor {
264        SyntaxEditor::new(node.tree_top()).0
265    }
266
267    pub fn add_file_edits(&mut self, file_id: impl Into<FileId>, editor: SyntaxEditor) {
268        match self.file_editors.entry(file_id.into()) {
269            Entry::Occupied(mut entry) => entry.get_mut().merge(editor),
270            Entry::Vacant(entry) => {
271                entry.insert(editor);
272            }
273        }
274    }
275
276    pub fn make_placeholder_snippet(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
277        self.add_snippet_annotation(AnnotationSnippet::Over)
278    }
279
280    pub fn make_tabstop_before(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
281        self.add_snippet_annotation(AnnotationSnippet::Before)
282    }
283
284    pub fn make_tabstop_after(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
285        self.add_snippet_annotation(AnnotationSnippet::After)
286    }
287
288    fn commit(&mut self) {
289        // Apply syntax editor edits
290        for (file_id, editor) in mem::take(&mut self.file_editors) {
291            let edit_result = editor.finish();
292            let mut snippet_edit = vec![];
293
294            // Find snippet edits
295            for (kind, annotation) in &self.snippet_annotations {
296                let elements = edit_result.find_annotation(*annotation);
297
298                let snippet = match (kind, elements) {
299                    (AnnotationSnippet::Before, [element]) => {
300                        Snippet::Tabstop(element.text_range().start())
301                    }
302                    (AnnotationSnippet::After, [element]) => {
303                        Snippet::Tabstop(element.text_range().end())
304                    }
305                    (AnnotationSnippet::Over, [element]) => {
306                        Snippet::Placeholder(element.text_range())
307                    }
308                    (AnnotationSnippet::Over, elements) if !elements.is_empty() => {
309                        Snippet::PlaceholderGroup(
310                            elements.iter().map(|it| it.text_range()).collect(),
311                        )
312                    }
313                    _ => continue,
314                };
315
316                snippet_edit.push(snippet);
317            }
318
319            let mut edit = TextEdit::builder();
320            diff(edit_result.old_root(), edit_result.new_root()).into_text_edit(&mut edit);
321            let edit = edit.finish();
322
323            let snippet_edit =
324                if !snippet_edit.is_empty() { Some(SnippetEdit::new(snippet_edit)) } else { None };
325
326            if !edit.is_empty() || snippet_edit.is_some() {
327                self.source_change.insert_source_and_snippet_edit(file_id, edit, snippet_edit);
328            }
329        }
330
331        // Apply mutable edits
332        let snippet_edit = self.snippet_builder.take().map(|builder| {
333            SnippetEdit::new(
334                builder.places.into_iter().flat_map(PlaceSnippet::finalize_position).collect(),
335            )
336        });
337
338        let edit = mem::take(&mut self.edit).finish();
339        if !edit.is_empty() || snippet_edit.is_some() {
340            self.source_change.insert_source_and_snippet_edit(self.file_id, edit, snippet_edit);
341        }
342    }
343
344    /// Remove specified `range` of text.
345    pub fn delete(&mut self, range: TextRange) {
346        self.edit.delete(range)
347    }
348    /// Append specified `text` at the given `offset`
349    pub fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
350        self.edit.insert(offset, text.into())
351    }
352    /// Replaces specified `range` of text with a given string.
353    pub fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
354        self.edit.replace(range, replace_with.into())
355    }
356    pub fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
357        diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
358    }
359    pub fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
360        let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
361        self.source_change.push_file_system_edit(file_system_edit);
362    }
363    pub fn move_file(&mut self, src: impl Into<FileId>, dst: AnchoredPathBuf) {
364        let file_system_edit = FileSystemEdit::MoveFile { src: src.into(), dst };
365        self.source_change.push_file_system_edit(file_system_edit);
366    }
367
368    /// Triggers the parameter hint popup after the assist is applied
369    pub fn trigger_parameter_hints(&mut self) {
370        self.command = Some(Command::TriggerParameterHints);
371    }
372
373    /// Renames the item at the cursor position after the assist is applied
374    pub fn rename(&mut self) {
375        self.command = Some(Command::Rename);
376    }
377
378    /// Adds a tabstop snippet to place the cursor before `node`
379    pub fn add_tabstop_before(&mut self, _cap: SnippetCap, node: impl AstNode) {
380        assert!(node.syntax().parent().is_some());
381        self.add_snippet(PlaceSnippet::Before(node.syntax().clone().into()));
382    }
383
384    /// Adds a tabstop snippet to place the cursor before `token`
385    pub fn add_tabstop_before_token(&mut self, _cap: SnippetCap, token: SyntaxToken) {
386        assert!(token.parent().is_some());
387        self.add_snippet(PlaceSnippet::Before(token.into()));
388    }
389
390    /// Adds a tabstop snippet to place the cursor after `token`
391    pub fn add_tabstop_after_token(&mut self, _cap: SnippetCap, token: SyntaxToken) {
392        assert!(token.parent().is_some());
393        self.add_snippet(PlaceSnippet::After(token.into()));
394    }
395
396    /// Adds a snippet to move the cursor selected over `node`
397    pub fn add_placeholder_snippet(&mut self, _cap: SnippetCap, node: impl AstNode) {
398        assert!(node.syntax().parent().is_some());
399        self.add_snippet(PlaceSnippet::Over(node.syntax().clone().into()))
400    }
401
402    fn add_snippet(&mut self, snippet: PlaceSnippet) {
403        let snippet_builder = self.snippet_builder.get_or_insert(SnippetBuilder { places: vec![] });
404        snippet_builder.places.push(snippet);
405        self.source_change.is_snippet = true;
406    }
407
408    fn add_snippet_annotation(&mut self, kind: AnnotationSnippet) -> SyntaxAnnotation {
409        let annotation = SyntaxAnnotation::default();
410        self.snippet_annotations.push((kind, annotation));
411        self.source_change.is_snippet = true;
412        annotation
413    }
414
415    pub fn finish(mut self) -> SourceChange {
416        self.commit();
417
418        // Only one file can have snippet edits
419        stdx::never!(
420            self.source_change
421                .source_file_edits
422                .iter()
423                .filter(|(_, (_, snippet_edit))| snippet_edit.is_some())
424                .at_most_one()
425                .is_err()
426        );
427
428        mem::take(&mut self.source_change)
429    }
430}
431
432#[derive(Debug, Clone)]
433pub enum FileSystemEdit {
434    CreateFile { dst: AnchoredPathBuf, initial_contents: String },
435    MoveFile { src: FileId, dst: AnchoredPathBuf },
436    MoveDir { src: AnchoredPathBuf, src_id: FileId, dst: AnchoredPathBuf },
437}
438
439impl From<FileSystemEdit> for SourceChange {
440    fn from(edit: FileSystemEdit) -> SourceChange {
441        SourceChange {
442            source_file_edits: Default::default(),
443            file_system_edits: vec![edit],
444            is_snippet: false,
445            ..SourceChange::default()
446        }
447    }
448}
449
450pub enum Snippet {
451    /// A tabstop snippet (e.g. `$0`).
452    Tabstop(TextSize),
453    /// A placeholder snippet (e.g. `${0:placeholder}`).
454    Placeholder(TextRange),
455    /// A group of placeholder snippets, e.g.
456    ///
457    /// ```ignore
458    /// let ${0:new_var} = 4;
459    /// fun(1, 2, 3, ${0:new_var});
460    /// ```
461    PlaceholderGroup(Vec<TextRange>),
462}
463
464pub enum AnnotationSnippet {
465    /// Place a tabstop before an element
466    Before,
467    /// Place a tabstop before an element
468    After,
469    /// Place a placeholder snippet in place of the element(s)
470    Over,
471}
472
473enum PlaceSnippet {
474    /// Place a tabstop before an element
475    Before(SyntaxElement),
476    /// Place a tabstop before an element
477    After(SyntaxElement),
478    /// Place a placeholder snippet in place of the element
479    Over(SyntaxElement),
480}
481
482impl PlaceSnippet {
483    fn finalize_position(self) -> Vec<Snippet> {
484        match self {
485            PlaceSnippet::Before(it) => vec![Snippet::Tabstop(it.text_range().start())],
486            PlaceSnippet::After(it) => vec![Snippet::Tabstop(it.text_range().end())],
487            PlaceSnippet::Over(it) => vec![Snippet::Placeholder(it.text_range())],
488        }
489    }
490}