]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide-db/src/source_change.rs
Rollup merge of #100092 - compiler-errors:issue-100075, r=oli-obk
[rust.git] / src / tools / rust-analyzer / crates / ide-db / src / 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
6 use std::{collections::hash_map::Entry, iter, mem};
7
8 use base_db::{AnchoredPathBuf, FileId};
9 use rustc_hash::FxHashMap;
10 use stdx::never;
11 use syntax::{algo, AstNode, SyntaxNode, SyntaxNodePtr, TextRange, TextSize};
12 use text_edit::{TextEdit, TextEditBuilder};
13
14 use crate::SnippetCap;
15
16 #[derive(Default, Debug, Clone)]
17 pub struct SourceChange {
18     pub source_file_edits: FxHashMap<FileId, TextEdit>,
19     pub file_system_edits: Vec<FileSystemEdit>,
20     pub is_snippet: bool,
21 }
22
23 impl SourceChange {
24     /// Creates a new SourceChange with the given label
25     /// from the edits.
26     pub fn from_edits(
27         source_file_edits: FxHashMap<FileId, TextEdit>,
28         file_system_edits: Vec<FileSystemEdit>,
29     ) -> Self {
30         SourceChange { source_file_edits, file_system_edits, is_snippet: false }
31     }
32
33     pub fn from_text_edit(file_id: FileId, edit: TextEdit) -> Self {
34         SourceChange {
35             source_file_edits: iter::once((file_id, edit)).collect(),
36             ..Default::default()
37         }
38     }
39
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");
46             }
47             Entry::Vacant(entry) => {
48                 entry.insert(edit);
49             }
50         }
51     }
52
53     pub fn push_file_system_edit(&mut self, edit: FileSystemEdit) {
54         self.file_system_edits.push(edit);
55     }
56
57     pub fn get_source_edit(&self, file_id: FileId) -> Option<&TextEdit> {
58         self.source_file_edits.get(&file_id)
59     }
60
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;
65         self
66     }
67 }
68
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));
72     }
73 }
74
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));
78     }
79 }
80
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 }
84     }
85 }
86
87 pub struct SourceChangeBuilder {
88     pub edit: TextEditBuilder,
89     pub file_id: FileId,
90     pub source_change: SourceChange,
91     pub trigger_signature_help: bool,
92
93     /// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
94     pub mutated_tree: Option<TreeMutator>,
95 }
96
97 pub struct TreeMutator {
98     immutable: SyntaxNode,
99     mutable_clone: SyntaxNode,
100 }
101
102 impl TreeMutator {
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 }
107     }
108
109     pub fn make_mut<N: AstNode>(&self, node: &N) -> N {
110         N::cast(self.make_syntax_mut(node.syntax())).unwrap()
111     }
112
113     pub fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
114         let ptr = SyntaxNodePtr::new(node);
115         ptr.to_node(&self.mutable_clone)
116     }
117 }
118
119 impl SourceChangeBuilder {
120     pub fn new(file_id: FileId) -> SourceChangeBuilder {
121         SourceChangeBuilder {
122             edit: TextEdit::builder(),
123             file_id,
124             source_change: SourceChange::default(),
125             trigger_signature_help: false,
126             mutated_tree: None,
127         }
128     }
129
130     pub fn edit_file(&mut self, file_id: FileId) {
131         self.commit();
132         self.file_id = file_id;
133     }
134
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)
138         }
139
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);
143         }
144     }
145
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)
148     }
149     /// Returns a copy of the `node`, suitable for mutation.
150     ///
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.
155     ///
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
158     /// mutable state.
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)
161     }
162
163     /// Remove specified `range` of text.
164     pub fn delete(&mut self, range: TextRange) {
165         self.edit.delete(range)
166     }
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())
170     }
171     /// Append specified `snippet` at the given `offset`
172     pub fn insert_snippet(
173         &mut self,
174         _cap: SnippetCap,
175         offset: TextSize,
176         snippet: impl Into<String>,
177     ) {
178         self.source_change.is_snippet = true;
179         self.insert(offset, snippet);
180     }
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())
184     }
185     /// Replaces specified `range` of text with a given `snippet`.
186     pub fn replace_snippet(
187         &mut self,
188         _cap: SnippetCap,
189         range: TextRange,
190         snippet: impl Into<String>,
191     ) {
192         self.source_change.is_snippet = true;
193         self.replace(range, snippet);
194     }
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)
197     }
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);
201     }
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);
205     }
206     pub fn trigger_signature_help(&mut self) {
207         self.trigger_signature_help = true;
208     }
209
210     pub fn finish(mut self) -> SourceChange {
211         self.commit();
212         mem::take(&mut self.source_change)
213     }
214 }
215
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 },
221 }
222
223 impl From<FileSystemEdit> for SourceChange {
224     fn from(edit: FileSystemEdit) -> SourceChange {
225         SourceChange {
226             source_file_edits: Default::default(),
227             file_system_edits: vec![edit],
228             is_snippet: false,
229         }
230     }
231 }