1 //! This modules defines type to represent changes to the source code, that flow
2 //! from the server to the client.
4 //! It can be viewed as a dual for `Change`.
6 use std::{collections::hash_map::Entry, iter, mem};
8 use base_db::{AnchoredPathBuf, FileId};
9 use rustc_hash::FxHashMap;
11 use syntax::{algo, AstNode, SyntaxNode, SyntaxNodePtr, TextRange, TextSize};
12 use text_edit::{TextEdit, TextEditBuilder};
14 use crate::SnippetCap;
16 #[derive(Default, Debug, Clone)]
17 pub struct SourceChange {
18 pub source_file_edits: FxHashMap<FileId, TextEdit>,
19 pub file_system_edits: Vec<FileSystemEdit>,
24 /// Creates a new SourceChange with the given label
27 source_file_edits: FxHashMap<FileId, TextEdit>,
28 file_system_edits: Vec<FileSystemEdit>,
30 SourceChange { source_file_edits, file_system_edits, is_snippet: false }
33 pub fn from_text_edit(file_id: FileId, edit: TextEdit) -> Self {
35 source_file_edits: iter::once((file_id, edit)).collect(),
40 /// Inserts a [`TextEdit`] for the given [`FileId`]. This properly handles merging existing
41 /// edits for a file if some already exist.
42 pub fn insert_source_edit(&mut self, file_id: FileId, edit: TextEdit) {
43 match self.source_file_edits.entry(file_id) {
44 Entry::Occupied(mut entry) => {
45 never!(entry.get_mut().union(edit).is_err(), "overlapping edits for same file");
47 Entry::Vacant(entry) => {
53 pub fn push_file_system_edit(&mut self, edit: FileSystemEdit) {
54 self.file_system_edits.push(edit);
57 pub fn get_source_edit(&self, file_id: FileId) -> Option<&TextEdit> {
58 self.source_file_edits.get(&file_id)
61 pub fn merge(mut self, other: SourceChange) -> SourceChange {
62 self.extend(other.source_file_edits);
63 self.extend(other.file_system_edits);
64 self.is_snippet |= other.is_snippet;
69 impl Extend<(FileId, TextEdit)> for SourceChange {
70 fn extend<T: IntoIterator<Item = (FileId, TextEdit)>>(&mut self, iter: T) {
71 iter.into_iter().for_each(|(file_id, edit)| self.insert_source_edit(file_id, edit));
75 impl Extend<FileSystemEdit> for SourceChange {
76 fn extend<T: IntoIterator<Item = FileSystemEdit>>(&mut self, iter: T) {
77 iter.into_iter().for_each(|edit| self.push_file_system_edit(edit));
81 impl From<FxHashMap<FileId, TextEdit>> for SourceChange {
82 fn from(source_file_edits: FxHashMap<FileId, TextEdit>) -> SourceChange {
83 SourceChange { source_file_edits, file_system_edits: Vec::new(), is_snippet: false }
87 pub struct SourceChangeBuilder {
88 pub edit: TextEditBuilder,
90 pub source_change: SourceChange,
91 pub trigger_signature_help: bool,
93 /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
94 pub mutated_tree: Option<TreeMutator>,
97 pub struct TreeMutator {
98 immutable: SyntaxNode,
99 mutable_clone: SyntaxNode,
103 pub fn new(immutable: &SyntaxNode) -> TreeMutator {
104 let immutable = immutable.ancestors().last().unwrap();
105 let mutable_clone = immutable.clone_for_update();
106 TreeMutator { immutable, mutable_clone }
109 pub fn make_mut<N: AstNode>(&self, node: &N) -> N {
110 N::cast(self.make_syntax_mut(node.syntax())).unwrap()
113 pub fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
114 let ptr = SyntaxNodePtr::new(node);
115 ptr.to_node(&self.mutable_clone)
119 impl SourceChangeBuilder {
120 pub fn new(file_id: FileId) -> SourceChangeBuilder {
121 SourceChangeBuilder {
122 edit: TextEdit::builder(),
124 source_change: SourceChange::default(),
125 trigger_signature_help: false,
130 pub fn edit_file(&mut self, file_id: FileId) {
132 self.file_id = file_id;
135 fn commit(&mut self) {
136 if let Some(tm) = self.mutated_tree.take() {
137 algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
140 let edit = mem::take(&mut self.edit).finish();
141 if !edit.is_empty() {
142 self.source_change.insert_source_edit(self.file_id, edit);
146 pub fn make_mut<N: AstNode>(&mut self, node: N) -> N {
147 self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
149 /// Returns a copy of the `node`, suitable for mutation.
151 /// Syntax trees in rust-analyzer are typically immutable, and mutating
152 /// operations panic at runtime. However, it is possible to make a copy of
153 /// the tree and mutate the copy freely. Mutation is based on interior
154 /// mutability, and different nodes in the same tree see the same mutations.
156 /// The typical pattern for an assist is to find specific nodes in the read
157 /// phase, and then get their mutable couterparts using `make_mut` in the
159 pub fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
160 self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
163 /// Remove specified `range` of text.
164 pub fn delete(&mut self, range: TextRange) {
165 self.edit.delete(range)
167 /// Append specified `text` at the given `offset`
168 pub fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
169 self.edit.insert(offset, text.into())
171 /// Append specified `snippet` at the given `offset`
172 pub fn insert_snippet(
176 snippet: impl Into<String>,
178 self.source_change.is_snippet = true;
179 self.insert(offset, snippet);
181 /// Replaces specified `range` of text with a given string.
182 pub fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
183 self.edit.replace(range, replace_with.into())
185 /// Replaces specified `range` of text with a given `snippet`.
186 pub fn replace_snippet(
190 snippet: impl Into<String>,
192 self.source_change.is_snippet = true;
193 self.replace(range, snippet);
195 pub fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
196 algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
198 pub fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
199 let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
200 self.source_change.push_file_system_edit(file_system_edit);
202 pub fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
203 let file_system_edit = FileSystemEdit::MoveFile { src, dst };
204 self.source_change.push_file_system_edit(file_system_edit);
206 pub fn trigger_signature_help(&mut self) {
207 self.trigger_signature_help = true;
210 pub fn finish(mut self) -> SourceChange {
212 mem::take(&mut self.source_change)
216 #[derive(Debug, Clone)]
217 pub enum FileSystemEdit {
218 CreateFile { dst: AnchoredPathBuf, initial_contents: String },
219 MoveFile { src: FileId, dst: AnchoredPathBuf },
220 MoveDir { src: AnchoredPathBuf, src_id: FileId, dst: AnchoredPathBuf },
223 impl From<FileSystemEdit> for SourceChange {
224 fn from(edit: FileSystemEdit) -> SourceChange {
226 source_file_edits: Default::default(),
227 file_system_edits: vec![edit],