1use std::collections::BTreeSet;
14use std::path::{Path, PathBuf};
15
16use serde::{Deserialize, Serialize};
17use vvv_core::{Address, Edit, Name, Parsed, Span, Surgery};
18
19use super::{Extraction, Rebase, Site, Widen};
20use crate::change::Change;
21use crate::graph::{Candidate, Fragment, Namespace, Node};
22use crate::protocol::vocabulary::IntentLine;
23use crate::report::{Document, MoveCounts};
24use crate::{
25 Confidence, EngineError, FileChange, Intent, Mutation, Notice, NoticeKind, Planned, Reach,
26 ReferencesQuery, Respelling, VfsError,
27};
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
34pub struct MoveSymbolIntent {
35 pub name: String,
36 #[serde(default, skip_serializing_if = "crate::Selection::is_all")]
37 pub selection: crate::Selection,
38 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub expected_content: Option<crate::ContentId>,
40 pub from: PathBuf,
42 pub to: PathBuf,
44}
45
46impl MoveSymbolIntent {
47 pub fn new(name: impl Into<String>, from: impl Into<PathBuf>, to: impl Into<PathBuf>) -> Self {
48 Self {
49 name: name.into(),
50 selection: crate::Selection::All,
51 expected_content: None,
52 from: from.into(),
53 to: to.into(),
54 }
55 }
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
60#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
61pub struct MoveSymbol {
62 pub intent: MoveSymbolIntent,
63 pub declaration: crate::Match,
64 pub pieces: Vec<crate::SymbolMovePiece>,
65 #[serde(flatten)]
67 pub state: crate::MutationState,
68 pub from: Address,
70 pub to: Address,
71 #[serde(default, skip_serializing_if = "Vec::is_empty")]
72 pub notices: Vec<Notice>,
73 #[serde(default, skip_serializing_if = "Vec::is_empty")]
76 pub respellings: Vec<Respelling>,
77 pub files: Vec<FileChange>,
78}
79
80impl Mutation for MoveSymbol {
81 fn into_mutation(self) -> crate::MutationAnswer {
82 crate::MutationAnswer::MoveSymbol(self)
83 }
84
85 fn applied(&mut self, id: u64) {
86 self.state = crate::MutationState::Applied { history_id: id };
87 }
88}
89
90impl MoveSymbolIntent {
93 pub fn selecting(mut self, selection: crate::Selection) -> Self {
94 self.selection = selection;
95 self
96 }
97 pub fn expecting(mut self, content: crate::ContentId) -> Self {
98 self.expected_content = Some(content);
99 self
100 }
101 pub fn plan(self, engine: &crate::Engine) -> Result<Planned<MoveSymbol>, EngineError> {
103 let _operation = engine.operation();
104 let mut graph = engine.graph()?;
105 self.plan_in(&mut graph, engine.workspace())
106 }
107
108 pub(crate) fn plan_in(
109 self,
110 graph: &mut crate::graph::Graph,
111 workspace: &crate::Workspace,
112 ) -> Result<Planned<MoveSymbol>, EngineError> {
113 let from_path = workspace.normalize(&self.from);
114 let to_path = workspace.normalize(&self.to);
115 let source = graph.file(&from_path)?;
116 let dest = graph
117 .candidate(&to_path)
118 .ok_or_else(|| VfsError::NotFound(to_path.clone()))?;
119 if source.language() != dest.language() {
120 return Err(EngineError::NoLanguage(to_path.clone().into()));
121 }
122 let ns = graph.namespace_of(&from_path)?;
123 if self
124 .expected_content
125 .as_ref()
126 .is_some_and(|content| content != &source.file().content_id())
127 {
128 return Err(EngineError::StaleSource {
129 path: from_path.into(),
130 });
131 }
132 let selected = super::SymbolMoveCandidates::of(&source, &ns, &self.name)?
133 .select(&self.name, &self.selection)?;
134 let dest_facts = dest.facts()?;
135 let destination_reason = if from_path == to_path {
136 Some(crate::SymbolMoveUnsupported::SameFile)
137 } else if dest_facts
138 .symbols
139 .iter()
140 .any(|symbol| symbol.name == self.name && ns.is_addressable(symbol.kind))
141 {
142 Some(crate::SymbolMoveUnsupported::DestinationBindingConflict)
143 } else {
144 None
145 };
146 if let Some(reason) = destination_reason {
147 return Err(EngineError::UnsupportedSymbolMove {
148 declaration: Box::new(selected.declaration),
149 reason,
150 });
151 }
152 let symbol = selected
153 .declaration
154 .symbol
155 .as_ref()
156 .ok_or(EngineError::InvalidSymbolMoveEvidence)?;
157 let extraction = Extraction::of(
158 source.file(),
159 symbol,
160 selected.pieces.iter().map(|piece| &piece.symbol),
161 )?;
162 let old_module = ns.address(&from_path)?;
163 let old = old_module.join(self.name.as_str());
164 let consumers = graph.consumers(&ns, &old, &[&from_path, &to_path])?;
165 let evidence =
166 graph.references(&ReferencesQuery::new(self.name.as_str()).declared_in(&from_path))?;
167 let nodes = graph.fragments(&ns)?;
168
169 let mut mv = SymbolMove::new(&ns, &self.name, &source, &dest, extraction, consumers)?;
170 mv.notice_resolved_uses(&evidence.occurrences);
171 mv.provision()?;
172 mv.rebase_consumers(&nodes)?;
173 mv.keep_old_file_working()?;
174 mv.drop_redundant_import()?;
175 mv.widen_for_consumers();
176 mv.cut_and_paste()?;
177 let (change, from, to) = mv.finish();
178 Planned::of(
179 workspace,
180 change,
181 Intent::MoveSymbol(self.clone()),
182 |bound, files| MoveSymbol {
183 intent: self.clone(),
184 declaration: selected.declaration.clone(),
185 pieces: selected.pieces.clone(),
186 state: crate::MutationState::Preview,
187 from,
188 to,
189 notices: bound.notices,
190 respellings: bound.respellings,
191 files,
192 },
193 )
194 }
195}
196
197struct SymbolMove<'a> {
200 ns: &'a Namespace,
201 surgery: &'a dyn Surgery,
202 name: &'a str,
203 from_path: &'a Path,
204 to_path: &'a Path,
205 old_module: Address,
206 new_module: Address,
207 old: Address,
208 new: Address,
209 source_fragment: std::sync::Arc<Fragment>,
210 dest_fragment: std::sync::Arc<Fragment>,
211 source: Parsed<'a>,
212 dest: Parsed<'a>,
213 source_witness: &'a crate::workspace::SourceWitness,
214 dest_witness: &'a crate::workspace::SourceWitness,
215 extraction: Extraction<'a>,
216 consumers: Vec<Address>,
218 old_file_still_uses: bool,
221 change: Change,
222 text_edits: Vec<Edit>,
225 new_imports: Vec<String>,
227}
228
229impl<'a> SymbolMove<'a> {
230 fn new(
231 ns: &'a Namespace,
232 name: &'a str,
233 source: &'a Candidate,
234 dest: &'a Candidate,
235 extraction: Extraction<'a>,
236 consumers: Vec<Address>,
237 ) -> Result<Self, EngineError> {
238 let old_module = ns.address(source.path())?;
239 let new_module = ns.address(dest.path())?;
240 Ok(Self {
241 ns,
242 surgery: ns.surgery()?,
243 name,
244 from_path: source.path(),
245 to_path: dest.path(),
246 old: old_module.join(name),
247 new: new_module.join(name),
248 old_module,
249 new_module,
250 source_fragment: source.fragment(ns)?,
251 dest_fragment: dest.fragment(ns)?,
252 source: Parsed {
253 path: source.path(),
254 source: source.file().source(),
255 facts: source.facts()?,
256 },
257 dest: Parsed {
258 path: dest.path(),
259 source: dest.file().source(),
260 facts: dest.facts()?,
261 },
262 source_witness: source.file().witness(),
263 dest_witness: dest.file().witness(),
264 extraction,
265 consumers,
266 old_file_still_uses: false,
267 change: Change::new(),
268 text_edits: Vec::new(),
269 new_imports: Vec::new(),
270 })
271 }
272
273 fn notice_resolved_uses(&mut self, occurrences: &[crate::Occurrence]) {
277 for m in occurrences
278 .iter()
279 .filter(|o| o.confidence == Confidence::Resolved)
280 .map(|o| &o.m)
281 {
282 if m.path == self.from_path {
283 let in_import = self
284 .source
285 .facts
286 .imports
287 .iter()
288 .any(|i| i.span.contains(&m.span));
289 if !self.extraction.contains(m.span)
290 && !in_import
291 && !self.extraction.shadowed(self.source.facts, m.span, |kind| {
292 self.ns.is_addressable(kind)
293 })
294 {
295 self.old_file_still_uses = true;
296 }
297 } else if m.path != self.to_path
298 && let Ok(module) = self.ns.address(&m.path)
299 && !self.consumers.contains(&module)
300 {
301 self.consumers.push(module);
302 }
303 }
304 }
305
306 fn provision(&mut self) -> Result<(), EngineError> {
310 let used = self.extraction.names_used(self.source.facts);
311 let already: BTreeSet<String> = self
312 .dest
313 .facts
314 .imports
315 .iter()
316 .filter(|i| i.declares && !self.dest.is_group_prefix(i))
317 .filter_map(|i| i.binding())
318 .map(Name::to_string)
319 .collect();
320 let source = self.source;
321 for edge in self
322 .source_fragment
323 .imports()
324 .filter(|e| !self.extraction.contains(e.import.span))
325 {
326 let import = &edge.import;
327 if source.is_group_prefix(import) {
328 continue;
329 }
330 let Some(name) = import.binding().map(Name::to_string) else {
331 continue;
332 };
333 if !used.contains(&name) || already.contains(&name) || name == self.name {
334 continue;
335 }
336 let statement = match edge.address() {
337 Some(address) if !address.is_root() => {
338 self.surgery
339 .import_statement(self.ns.project(), self.to_path, address, &name)
340 }
341 _ => self.surgery.import_of_path(&import.path, &name),
342 };
343 if let Some(statement) = statement
344 && !self.new_imports.contains(&statement)
345 {
346 self.new_imports.push(statement);
347 }
348 }
349 let siblings: Vec<&vvv_core::Symbol> = source
350 .facts
351 .symbols
352 .iter()
353 .filter(|s| {
354 s.name != self.name
355 && self.ns.is_addressable(s.kind)
356 && used.contains(&s.name)
357 && !already.contains(&s.name)
358 && !self.extraction.contains(s.span)
359 })
360 .collect();
361 for sibling in siblings {
362 let address = self.old_module.join(sibling.name.as_str());
363 if let Some(statement) = self.surgery.import_statement(
364 self.ns.project(),
365 self.to_path,
366 &address,
367 &sibling.name,
368 ) && !self.new_imports.contains(&statement)
369 {
370 self.new_imports.push(statement);
371 }
372 if !self
373 .ns
374 .reach(&self.old_module, sibling)
375 .admits(&self.new_module)
376 {
377 let widen = Widen {
378 symbol: sibling,
379 source: self.source.source,
380 needs: Reach::narrowest(
381 &self.old_module,
382 std::slice::from_ref(&self.new_module),
383 ),
384 consumer: self.new_module.clone(),
385 notice_at: (
386 self.from_path.to_path_buf(),
387 self.source.source.position(sibling.name_span.start),
388 ),
389 };
390 match widen.plan(self.surgery) {
391 Ok(edit) => self.change.edit(self.source_witness, edit)?,
392 Err(notice) => self.change.notice(notice),
393 }
394 }
395 }
396 Ok(())
397 }
398
399 fn rebase_consumers(&mut self, nodes: &[Node]) -> Result<(), EngineError> {
403 let rebase = Rebase::new(self.ns, self.old.clone(), self.new.clone());
404 for node in nodes.iter().filter(|c| c.path() != self.to_path) {
405 let site = if node.path() == self.from_path {
406 let (moving, staying) = Site::partition(node, self.to_path, &self.extraction);
407 let rewritten = rebase.rewrite(&moving)?;
408 self.text_edits.extend(rewritten.edits);
409 for notice in rewritten.notices {
410 self.change.notice(notice);
411 }
412 staying
413 } else {
414 Site::new(node, node.path())
415 };
416 let (contribution, _) = rebase.rewrite(&site)?.into_change()?;
417 self.change.merge(contribution)?;
418 }
419 Ok(())
420 }
421
422 fn keep_old_file_working(&mut self) -> Result<(), EngineError> {
424 if self.old_file_still_uses
425 && let Some(statement) = self.surgery.import_statement(
426 self.ns.project(),
427 self.from_path,
428 &self.new,
429 self.name,
430 )
431 {
432 self.change.edit(
433 self.source_witness,
434 Edit::insert(
435 self.surgery.import_insertion(&self.source),
436 format!("{statement}\n"),
437 ),
438 )?;
439 }
440 Ok(())
441 }
442
443 fn drop_redundant_import(&mut self) -> Result<(), EngineError> {
446 let text = self.dest.source.as_str();
447 for edge in self.dest_fragment.imports() {
448 let import = &edge.import;
449 if edge.address() != Some(&self.old) {
450 continue;
451 }
452 match &import.group {
453 None => {
454 let statement = Span::new(
455 text[..import.span.start].rfind('\n').map_or(0, |i| i + 1),
456 text[import.span.end..]
457 .find('\n')
458 .map_or(text.len(), |nl| import.span.end + nl + 1),
459 );
460 self.change
461 .edit(self.dest_witness, Edit::delete(statement))?;
462 }
463 Some(_) => self.change.notice(Notice {
464 path: self.to_path.into(),
465 start: self.dest.source.position(import.span.start),
466 kind: NoticeKind::RedundantImport {
467 import: import.path.to_string(),
468 },
469 }),
470 }
471 }
472 Ok(())
473 }
474
475 fn widen_for_consumers(&mut self) {
478 let reach = self.ns.reach(&self.new_module, self.extraction.symbol);
479 let blind: Vec<Address> = self
480 .consumers
481 .iter()
482 .filter(|c| !reach.admits(c))
483 .cloned()
484 .collect();
485 let Some(first) = blind.first() else {
486 return;
487 };
488 let widen = Widen {
489 symbol: self.extraction.symbol,
490 source: self.source.source,
491 needs: Reach::narrowest(&self.new_module, &blind),
492 consumer: first.clone(),
493 notice_at: (
494 self.to_path.to_path_buf(),
495 self.dest.source.position(self.dest.source.len()),
496 ),
497 };
498 match widen.plan(self.surgery) {
499 Ok(edit) => self.text_edits.push(edit),
500 Err(notice) => self.change.notice(notice),
501 }
502 }
503
504 fn cut_and_paste(&mut self) -> Result<(), EngineError> {
507 let moved = self.extraction.assemble(&self.text_edits)?;
508 for cut in self.extraction.cuts() {
509 self.change.edit(self.source_witness, Edit::delete(cut))?;
510 }
511 if !self.new_imports.is_empty() {
512 let at = self.surgery.import_insertion(&self.dest);
513 let block: String = self.new_imports.iter().map(|s| format!("{s}\n")).collect();
514 self.change
515 .edit(self.dest_witness, Edit::insert(at, block))?;
516 }
517 let at = self.surgery.item_insertion(&self.dest);
518 let text = self.dest.source.as_str();
519 let separator = if text.is_empty() || text.ends_with("\n\n") {
520 ""
521 } else if text.ends_with('\n') {
522 "\n"
523 } else {
524 "\n\n"
525 };
526 self.change.edit(
527 self.dest_witness,
528 Edit::insert(at, format!("{separator}{moved}\n")),
529 )?;
530 Ok(())
531 }
532
533 fn finish(self) -> (Change, Address, Address) {
534 (self.change, self.old, self.new)
535 }
536}
537
538impl Document {
539 pub(crate) fn move_symbol(result: &MoveSymbol) -> Self {
540 let mut report = Self::new();
541 report.title(IntentLine(&Intent::MoveSymbol(result.intent.clone())));
542 let structural = report.moved(
543 result.state,
544 &result.files,
545 &result.respellings,
546 &result.notices,
547 );
548 report.moved_summary(
549 result.state,
550 MoveCounts {
551 respellings: result.respellings.len(),
552 structural,
553 notices: result.notices.len(),
554 files: result.files.len(),
555 },
556 );
557 report
558 }
559}