1use 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, SyntaxNode, TextRange, TextSize,
19 syntax_editor::{SyntaxAnnotation, SyntaxEditor},
20};
21
22#[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 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 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.file_system_edits.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 FromIterator<(FileId, TextEdit)> for SourceChange {
132 fn from_iter<T: IntoIterator<Item = (FileId, TextEdit)>>(iter: T) -> Self {
133 let mut this = SourceChange::default();
134 this.extend(iter);
135 this
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct SnippetEdit(Vec<(u32, TextRange)>);
141
142impl SnippetEdit {
143 pub fn new(snippets: Vec<Snippet>) -> Self {
144 let mut snippet_ranges = snippets
145 .into_iter()
146 .zip(1..)
147 .with_position()
148 .flat_map(|(position, (snippet, index))| {
149 let index = if position.is_last { 0 } else { index };
151
152 match snippet {
153 Snippet::Tabstop(pos) => vec![(index, TextRange::empty(pos))],
154 Snippet::Placeholder(range) => vec![(index, range)],
155 Snippet::PlaceholderGroup(ranges) => {
156 ranges.into_iter().map(|range| (index, range)).collect()
157 }
158 }
159 })
160 .collect_vec();
161
162 snippet_ranges.sort_by_key(|(_, range)| range.start());
163
164 let disjoint_ranges = snippet_ranges
166 .iter()
167 .zip(snippet_ranges.iter().skip(1))
168 .all(|((_, left), (_, right))| left.end() <= right.start() || left == right);
169 stdx::always!(disjoint_ranges);
170
171 SnippetEdit(snippet_ranges)
172 }
173
174 pub fn apply(&self, text: &mut String) {
176 for (index, range) in self.0.iter().rev() {
178 if range.is_empty() {
179 text.insert_str(range.start().into(), &format!("${index}"));
181 } else {
182 text.insert(range.end().into(), '}');
184 text.insert_str(range.start().into(), &format!("${{{index}:"));
185 }
186 }
187 }
188
189 pub fn into_edit_ranges(self) -> Vec<(u32, TextRange)> {
192 self.0
193 }
194
195 pub fn escape_snippet_bits(text: &mut String) {
200 stdx::replace(text, '\\', "\\\\");
201 stdx::replace(text, '$', "\\$");
202 }
203}
204
205pub struct SourceChangeBuilder {
206 edit: TextEditBuilder,
207 pub file_id: FileId,
208 pub source_change: SourceChange,
209 pub command: Option<Command>,
210
211 file_editors: FxHashMap<FileId, SyntaxEditor>,
213 snippet_annotations: Vec<(AnnotationSnippet, SyntaxAnnotation)>,
215}
216
217impl SourceChangeBuilder {
218 pub fn new(file_id: impl Into<FileId>) -> SourceChangeBuilder {
219 SourceChangeBuilder {
220 edit: TextEdit::builder(),
221 file_id: file_id.into(),
222 source_change: SourceChange::default(),
223 command: None,
224 file_editors: FxHashMap::default(),
225 snippet_annotations: vec![],
226 }
227 }
228
229 pub fn edit_file(&mut self, file_id: impl Into<FileId>) {
230 self.commit();
231 self.file_id = file_id.into();
232 }
233
234 pub fn make_editor(&self, node: &SyntaxNode) -> SyntaxEditor {
235 SyntaxEditor::new(node.tree_top()).0
236 }
237
238 pub fn add_file_edits(&mut self, file_id: impl Into<FileId>, editor: SyntaxEditor) {
239 match self.file_editors.entry(file_id.into()) {
240 Entry::Occupied(mut entry) => entry.get_mut().merge(editor),
241 Entry::Vacant(entry) => {
242 entry.insert(editor);
243 }
244 }
245 }
246
247 pub fn make_placeholder_snippet(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
248 self.add_snippet_annotation(AnnotationSnippet::Over)
249 }
250
251 pub fn make_tabstop_before(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
252 self.add_snippet_annotation(AnnotationSnippet::Before)
253 }
254
255 pub fn make_tabstop_after(&mut self, _cap: SnippetCap) -> SyntaxAnnotation {
256 self.add_snippet_annotation(AnnotationSnippet::After)
257 }
258
259 fn commit(&mut self) {
260 for (file_id, editor) in mem::take(&mut self.file_editors) {
262 let edit_result = editor.finish();
263 let mut snippet_edit = vec![];
264
265 for (kind, annotation) in &self.snippet_annotations {
267 let elements = edit_result.find_annotation(*annotation);
268
269 let snippet = match (kind, elements) {
270 (AnnotationSnippet::Before, [element]) => {
271 Snippet::Tabstop(element.text_range().start())
272 }
273 (AnnotationSnippet::After, [element]) => {
274 Snippet::Tabstop(element.text_range().end())
275 }
276 (AnnotationSnippet::Over, [element]) => {
277 Snippet::Placeholder(element.text_range())
278 }
279 (AnnotationSnippet::Over, elements) if !elements.is_empty() => {
280 Snippet::PlaceholderGroup(
281 elements.iter().map(|it| it.text_range()).collect(),
282 )
283 }
284 _ => continue,
285 };
286
287 snippet_edit.push(snippet);
288 }
289
290 let mut edit = TextEdit::builder();
291 diff(edit_result.old_root(), edit_result.new_root()).into_text_edit(&mut edit);
292 let edit = edit.finish();
293
294 let snippet_edit =
295 if !snippet_edit.is_empty() { Some(SnippetEdit::new(snippet_edit)) } else { None };
296
297 if !edit.is_empty() || snippet_edit.is_some() {
298 self.source_change.insert_source_and_snippet_edit(file_id, edit, snippet_edit);
299 }
300 }
301
302 let edit = mem::take(&mut self.edit).finish();
304 if !edit.is_empty() {
305 self.source_change.insert_source_edit(self.file_id, edit);
306 }
307 }
308
309 pub fn delete(&mut self, range: TextRange) {
311 self.edit.delete(range)
312 }
313 pub fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
315 self.edit.insert(offset, text.into())
316 }
317 pub fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
319 self.edit.replace(range, replace_with.into())
320 }
321 pub fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
322 diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
323 }
324 pub fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
325 let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
326 self.source_change.push_file_system_edit(file_system_edit);
327 }
328 pub fn move_file(&mut self, src: impl Into<FileId>, dst: AnchoredPathBuf) {
329 let file_system_edit = FileSystemEdit::MoveFile { src: src.into(), dst };
330 self.source_change.push_file_system_edit(file_system_edit);
331 }
332
333 pub fn trigger_parameter_hints(&mut self) {
335 self.command = Some(Command::TriggerParameterHints);
336 }
337
338 pub fn rename(&mut self) {
340 self.command = Some(Command::Rename);
341 }
342
343 fn add_snippet_annotation(&mut self, kind: AnnotationSnippet) -> SyntaxAnnotation {
344 let annotation = SyntaxAnnotation::default();
345 self.snippet_annotations.push((kind, annotation));
346 self.source_change.is_snippet = true;
347 annotation
348 }
349
350 pub fn finish(mut self) -> SourceChange {
351 self.commit();
352
353 stdx::never!(
355 self.source_change
356 .source_file_edits
357 .iter()
358 .filter(|(_, (_, snippet_edit))| snippet_edit.is_some())
359 .at_most_one()
360 .is_err()
361 );
362
363 self.source_change
364 }
365}
366
367#[derive(Debug, Clone)]
368pub enum FileSystemEdit {
369 CreateFile { dst: AnchoredPathBuf, initial_contents: String },
370 MoveFile { src: FileId, dst: AnchoredPathBuf },
371 MoveDir { src: AnchoredPathBuf, src_id: FileId, dst: AnchoredPathBuf },
372}
373
374impl From<FileSystemEdit> for SourceChange {
375 fn from(edit: FileSystemEdit) -> SourceChange {
376 SourceChange {
377 source_file_edits: Default::default(),
378 file_system_edits: vec![edit],
379 is_snippet: false,
380 ..SourceChange::default()
381 }
382 }
383}
384
385pub enum Snippet {
386 Tabstop(TextSize),
388 Placeholder(TextRange),
390 PlaceholderGroup(Vec<TextRange>),
397}
398
399enum AnnotationSnippet {
400 Before,
402 After,
404 Over,
406}