• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
6 use std::{collections::hash_map::Entry, iter, mem};
7 
8 use crate::SnippetCap;
9 use base_db::{AnchoredPathBuf, FileId};
10 use nohash_hasher::IntMap;
11 use stdx::never;
12 use syntax::{algo, ast, ted, AstNode, SyntaxNode, SyntaxNodePtr, TextRange, TextSize};
13 use text_edit::{TextEdit, TextEditBuilder};
14 
15 #[derive(Default, Debug, Clone)]
16 pub struct SourceChange {
17     pub source_file_edits: IntMap<FileId, TextEdit>,
18     pub file_system_edits: Vec<FileSystemEdit>,
19     pub is_snippet: bool,
20 }
21 
22 impl SourceChange {
23     /// Creates a new SourceChange with the given label
24     /// from the edits.
from_edits( source_file_edits: IntMap<FileId, TextEdit>, file_system_edits: Vec<FileSystemEdit>, ) -> Self25     pub fn from_edits(
26         source_file_edits: IntMap<FileId, TextEdit>,
27         file_system_edits: Vec<FileSystemEdit>,
28     ) -> Self {
29         SourceChange { source_file_edits, file_system_edits, is_snippet: false }
30     }
31 
from_text_edit(file_id: FileId, edit: TextEdit) -> Self32     pub fn from_text_edit(file_id: FileId, edit: TextEdit) -> Self {
33         SourceChange {
34             source_file_edits: iter::once((file_id, edit)).collect(),
35             ..Default::default()
36         }
37     }
38 
39     /// Inserts a [`TextEdit`] for the given [`FileId`]. This properly handles merging existing
40     /// edits for a file if some already exist.
insert_source_edit(&mut self, file_id: FileId, edit: TextEdit)41     pub fn insert_source_edit(&mut self, file_id: FileId, edit: TextEdit) {
42         match self.source_file_edits.entry(file_id) {
43             Entry::Occupied(mut entry) => {
44                 never!(entry.get_mut().union(edit).is_err(), "overlapping edits for same file");
45             }
46             Entry::Vacant(entry) => {
47                 entry.insert(edit);
48             }
49         }
50     }
51 
push_file_system_edit(&mut self, edit: FileSystemEdit)52     pub fn push_file_system_edit(&mut self, edit: FileSystemEdit) {
53         self.file_system_edits.push(edit);
54     }
55 
get_source_edit(&self, file_id: FileId) -> Option<&TextEdit>56     pub fn get_source_edit(&self, file_id: FileId) -> Option<&TextEdit> {
57         self.source_file_edits.get(&file_id)
58     }
59 
merge(mut self, other: SourceChange) -> SourceChange60     pub fn merge(mut self, other: SourceChange) -> SourceChange {
61         self.extend(other.source_file_edits);
62         self.extend(other.file_system_edits);
63         self.is_snippet |= other.is_snippet;
64         self
65     }
66 }
67 
68 impl Extend<(FileId, TextEdit)> for SourceChange {
extend<T: IntoIterator<Item = (FileId, TextEdit)>>(&mut self, iter: T)69     fn extend<T: IntoIterator<Item = (FileId, TextEdit)>>(&mut self, iter: T) {
70         iter.into_iter().for_each(|(file_id, edit)| self.insert_source_edit(file_id, edit));
71     }
72 }
73 
74 impl Extend<FileSystemEdit> for SourceChange {
extend<T: IntoIterator<Item = FileSystemEdit>>(&mut self, iter: T)75     fn extend<T: IntoIterator<Item = FileSystemEdit>>(&mut self, iter: T) {
76         iter.into_iter().for_each(|edit| self.push_file_system_edit(edit));
77     }
78 }
79 
80 impl From<IntMap<FileId, TextEdit>> for SourceChange {
from(source_file_edits: IntMap<FileId, TextEdit>) -> SourceChange81     fn from(source_file_edits: IntMap<FileId, TextEdit>) -> SourceChange {
82         SourceChange { source_file_edits, file_system_edits: Vec::new(), is_snippet: false }
83     }
84 }
85 
86 impl FromIterator<(FileId, TextEdit)> for SourceChange {
from_iter<T: IntoIterator<Item = (FileId, TextEdit)>>(iter: T) -> Self87     fn from_iter<T: IntoIterator<Item = (FileId, TextEdit)>>(iter: T) -> Self {
88         let mut this = SourceChange::default();
89         this.extend(iter);
90         this
91     }
92 }
93 
94 pub struct SourceChangeBuilder {
95     pub edit: TextEditBuilder,
96     pub file_id: FileId,
97     pub source_change: SourceChange,
98     pub trigger_signature_help: bool,
99 
100     /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
101     pub mutated_tree: Option<TreeMutator>,
102     /// Keeps track of where to place snippets
103     pub snippet_builder: Option<SnippetBuilder>,
104 }
105 
106 pub struct TreeMutator {
107     immutable: SyntaxNode,
108     mutable_clone: SyntaxNode,
109 }
110 
111 #[derive(Default)]
112 pub struct SnippetBuilder {
113     /// Where to place snippets at
114     places: Vec<PlaceSnippet>,
115 }
116 
117 impl TreeMutator {
new(immutable: &SyntaxNode) -> TreeMutator118     pub fn new(immutable: &SyntaxNode) -> TreeMutator {
119         let immutable = immutable.ancestors().last().unwrap();
120         let mutable_clone = immutable.clone_for_update();
121         TreeMutator { immutable, mutable_clone }
122     }
123 
make_mut<N: AstNode>(&self, node: &N) -> N124     pub fn make_mut<N: AstNode>(&self, node: &N) -> N {
125         N::cast(self.make_syntax_mut(node.syntax())).unwrap()
126     }
127 
make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode128     pub fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
129         let ptr = SyntaxNodePtr::new(node);
130         ptr.to_node(&self.mutable_clone)
131     }
132 }
133 
134 impl SourceChangeBuilder {
new(file_id: FileId) -> SourceChangeBuilder135     pub fn new(file_id: FileId) -> SourceChangeBuilder {
136         SourceChangeBuilder {
137             edit: TextEdit::builder(),
138             file_id,
139             source_change: SourceChange::default(),
140             trigger_signature_help: false,
141             mutated_tree: None,
142             snippet_builder: None,
143         }
144     }
145 
edit_file(&mut self, file_id: FileId)146     pub fn edit_file(&mut self, file_id: FileId) {
147         self.commit();
148         self.file_id = file_id;
149     }
150 
commit(&mut self)151     fn commit(&mut self) {
152         // Render snippets first so that they get bundled into the tree diff
153         if let Some(mut snippets) = self.snippet_builder.take() {
154             // Last snippet always has stop index 0
155             let last_stop = snippets.places.pop().unwrap();
156             last_stop.place(0);
157 
158             for (index, stop) in snippets.places.into_iter().enumerate() {
159                 stop.place(index + 1)
160             }
161         }
162 
163         if let Some(tm) = self.mutated_tree.take() {
164             algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
165         }
166 
167         let edit = mem::take(&mut self.edit).finish();
168         if !edit.is_empty() {
169             self.source_change.insert_source_edit(self.file_id, edit);
170         }
171     }
172 
make_mut<N: AstNode>(&mut self, node: N) -> N173     pub fn make_mut<N: AstNode>(&mut self, node: N) -> N {
174         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
175     }
176     /// Returns a copy of the `node`, suitable for mutation.
177     ///
178     /// Syntax trees in rust-analyzer are typically immutable, and mutating
179     /// operations panic at runtime. However, it is possible to make a copy of
180     /// the tree and mutate the copy freely. Mutation is based on interior
181     /// mutability, and different nodes in the same tree see the same mutations.
182     ///
183     /// The typical pattern for an assist is to find specific nodes in the read
184     /// phase, and then get their mutable counterparts using `make_mut` in the
185     /// mutable state.
make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode186     pub fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
187         self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
188     }
189 
190     /// Remove specified `range` of text.
delete(&mut self, range: TextRange)191     pub fn delete(&mut self, range: TextRange) {
192         self.edit.delete(range)
193     }
194     /// Append specified `text` at the given `offset`
insert(&mut self, offset: TextSize, text: impl Into<String>)195     pub fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
196         self.edit.insert(offset, text.into())
197     }
198     /// Append specified `snippet` at the given `offset`
insert_snippet( &mut self, _cap: SnippetCap, offset: TextSize, snippet: impl Into<String>, )199     pub fn insert_snippet(
200         &mut self,
201         _cap: SnippetCap,
202         offset: TextSize,
203         snippet: impl Into<String>,
204     ) {
205         self.source_change.is_snippet = true;
206         self.insert(offset, snippet);
207     }
208     /// Replaces specified `range` of text with a given string.
replace(&mut self, range: TextRange, replace_with: impl Into<String>)209     pub fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
210         self.edit.replace(range, replace_with.into())
211     }
212     /// Replaces specified `range` of text with a given `snippet`.
replace_snippet( &mut self, _cap: SnippetCap, range: TextRange, snippet: impl Into<String>, )213     pub fn replace_snippet(
214         &mut self,
215         _cap: SnippetCap,
216         range: TextRange,
217         snippet: impl Into<String>,
218     ) {
219         self.source_change.is_snippet = true;
220         self.replace(range, snippet);
221     }
replace_ast<N: AstNode>(&mut self, old: N, new: N)222     pub fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
223         algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
224     }
create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>)225     pub fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
226         let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
227         self.source_change.push_file_system_edit(file_system_edit);
228     }
move_file(&mut self, src: FileId, dst: AnchoredPathBuf)229     pub fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
230         let file_system_edit = FileSystemEdit::MoveFile { src, dst };
231         self.source_change.push_file_system_edit(file_system_edit);
232     }
trigger_signature_help(&mut self)233     pub fn trigger_signature_help(&mut self) {
234         self.trigger_signature_help = true;
235     }
236 
237     /// Adds a tabstop snippet to place the cursor before `node`
add_tabstop_before(&mut self, _cap: SnippetCap, node: impl AstNode)238     pub fn add_tabstop_before(&mut self, _cap: SnippetCap, node: impl AstNode) {
239         assert!(node.syntax().parent().is_some());
240         self.add_snippet(PlaceSnippet::Before(node.syntax().clone()));
241     }
242 
243     /// Adds a tabstop snippet to place the cursor after `node`
add_tabstop_after(&mut self, _cap: SnippetCap, node: impl AstNode)244     pub fn add_tabstop_after(&mut self, _cap: SnippetCap, node: impl AstNode) {
245         assert!(node.syntax().parent().is_some());
246         self.add_snippet(PlaceSnippet::After(node.syntax().clone()));
247     }
248 
249     /// Adds a snippet to move the cursor selected over `node`
add_placeholder_snippet(&mut self, _cap: SnippetCap, node: impl AstNode)250     pub fn add_placeholder_snippet(&mut self, _cap: SnippetCap, node: impl AstNode) {
251         assert!(node.syntax().parent().is_some());
252         self.add_snippet(PlaceSnippet::Over(node.syntax().clone()))
253     }
254 
add_snippet(&mut self, snippet: PlaceSnippet)255     fn add_snippet(&mut self, snippet: PlaceSnippet) {
256         let snippet_builder = self.snippet_builder.get_or_insert(SnippetBuilder { places: vec![] });
257         snippet_builder.places.push(snippet);
258         self.source_change.is_snippet = true;
259     }
260 
finish(mut self) -> SourceChange261     pub fn finish(mut self) -> SourceChange {
262         self.commit();
263         mem::take(&mut self.source_change)
264     }
265 }
266 
267 #[derive(Debug, Clone)]
268 pub enum FileSystemEdit {
269     CreateFile { dst: AnchoredPathBuf, initial_contents: String },
270     MoveFile { src: FileId, dst: AnchoredPathBuf },
271     MoveDir { src: AnchoredPathBuf, src_id: FileId, dst: AnchoredPathBuf },
272 }
273 
274 impl From<FileSystemEdit> for SourceChange {
from(edit: FileSystemEdit) -> SourceChange275     fn from(edit: FileSystemEdit) -> SourceChange {
276         SourceChange {
277             source_file_edits: Default::default(),
278             file_system_edits: vec![edit],
279             is_snippet: false,
280         }
281     }
282 }
283 
284 enum PlaceSnippet {
285     /// Place a tabstop before a node
286     Before(SyntaxNode),
287     /// Place a tabstop before a node
288     After(SyntaxNode),
289     /// Place a placeholder snippet in place of the node
290     Over(SyntaxNode),
291 }
292 
293 impl PlaceSnippet {
294     /// Places the snippet before or over a node with the given tab stop index
place(self, order: usize)295     fn place(self, order: usize) {
296         // ensure the target node is still attached
297         match &self {
298             PlaceSnippet::Before(node) | PlaceSnippet::After(node) | PlaceSnippet::Over(node) => {
299                 // node should still be in the tree, but if it isn't
300                 // then it's okay to just ignore this place
301                 if stdx::never!(node.parent().is_none()) {
302                     return;
303                 }
304             }
305         }
306 
307         match self {
308             PlaceSnippet::Before(node) => {
309                 ted::insert_raw(ted::Position::before(&node), Self::make_tab_stop(order));
310             }
311             PlaceSnippet::After(node) => {
312                 ted::insert_raw(ted::Position::after(&node), Self::make_tab_stop(order));
313             }
314             PlaceSnippet::Over(node) => {
315                 let position = ted::Position::before(&node);
316                 node.detach();
317 
318                 let snippet = ast::SourceFile::parse(&format!("${{{order}:_}}"))
319                     .syntax_node()
320                     .clone_for_update();
321 
322                 let placeholder =
323                     snippet.descendants().find_map(ast::UnderscoreExpr::cast).unwrap();
324                 ted::replace(placeholder.syntax(), node);
325 
326                 ted::insert_raw(position, snippet);
327             }
328         }
329     }
330 
make_tab_stop(order: usize) -> SyntaxNode331     fn make_tab_stop(order: usize) -> SyntaxNode {
332         let stop = ast::SourceFile::parse(&format!("stop!(${order})"))
333             .syntax_node()
334             .descendants()
335             .find_map(ast::TokenTree::cast)
336             .unwrap()
337             .syntax()
338             .clone_for_update();
339 
340         stop.first_token().unwrap().detach();
341         stop.last_token().unwrap().detach();
342 
343         stop
344     }
345 }
346