use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use vvv_core::{Address, Edit, Name, Parsed, Span, Surgery};
use super::{Extraction, Rebase, Site, Widen};
use crate::change::Change;
use crate::graph::{Candidate, Fragment, Namespace, Node};
use crate::protocol::vocabulary::IntentLine;
use crate::report::{Document, MoveCounts};
use crate::{
Confidence, EngineError, FileChange, Intent, Mutation, Notice, NoticeKind, Planned, Reach,
ReferencesQuery, Respelling, VfsError,
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MoveSymbolIntent {
pub name: String,
#[serde(default, skip_serializing_if = "crate::Selection::is_all")]
pub selection: crate::Selection,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected_content: Option<crate::ContentId>,
pub from: PathBuf,
pub to: PathBuf,
}
impl MoveSymbolIntent {
pub fn new(name: impl Into<String>, from: impl Into<PathBuf>, to: impl Into<PathBuf>) -> Self {
Self {
name: name.into(),
selection: crate::Selection::All,
expected_content: None,
from: from.into(),
to: to.into(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MoveSymbol {
pub intent: MoveSymbolIntent,
pub declaration: crate::Match,
pub pieces: Vec<crate::SymbolMovePiece>,
#[serde(flatten)]
pub state: crate::MutationState,
pub from: Address,
pub to: Address,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notices: Vec<Notice>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub respellings: Vec<Respelling>,
pub files: Vec<FileChange>,
}
impl Mutation for MoveSymbol {
fn into_mutation(self) -> crate::MutationAnswer {
crate::MutationAnswer::MoveSymbol(self)
}
fn applied(&mut self, id: u64) {
self.state = crate::MutationState::Applied { history_id: id };
}
}
impl MoveSymbolIntent {
pub fn selecting(mut self, selection: crate::Selection) -> Self {
self.selection = selection;
self
}
pub fn expecting(mut self, content: crate::ContentId) -> Self {
self.expected_content = Some(content);
self
}
pub fn plan(self, engine: &crate::Engine) -> Result<Planned<MoveSymbol>, EngineError> {
let _operation = engine.operation();
let mut graph = engine.graph()?;
self.plan_in(&mut graph, engine.workspace())
}
pub(crate) fn plan_in(
self,
graph: &mut crate::graph::Graph,
workspace: &crate::Workspace,
) -> Result<Planned<MoveSymbol>, EngineError> {
let from_path = workspace.normalize(&self.from);
let to_path = workspace.normalize(&self.to);
let source = graph.file(&from_path)?;
let dest = graph
.candidate(&to_path)
.ok_or_else(|| VfsError::NotFound(to_path.clone()))?;
if source.language() != dest.language() {
return Err(EngineError::NoLanguage(to_path.clone().into()));
}
let ns = graph.namespace_of(&from_path)?;
if self
.expected_content
.as_ref()
.is_some_and(|content| content != &source.file().content_id())
{
return Err(EngineError::StaleSource {
path: from_path.into(),
});
}
let selected = super::SymbolMoveCandidates::of(&source, &ns, &self.name)?
.select(&self.name, &self.selection)?;
let dest_facts = dest.facts()?;
let destination_reason = if from_path == to_path {
Some(crate::SymbolMoveUnsupported::SameFile)
} else if dest_facts
.symbols
.iter()
.any(|symbol| symbol.name == self.name && ns.is_addressable(symbol.kind))
{
Some(crate::SymbolMoveUnsupported::DestinationBindingConflict)
} else {
None
};
if let Some(reason) = destination_reason {
return Err(EngineError::UnsupportedSymbolMove {
declaration: Box::new(selected.declaration),
reason,
});
}
let symbol = selected
.declaration
.symbol
.as_ref()
.ok_or(EngineError::InvalidSymbolMoveEvidence)?;
let extraction = Extraction::of(
source.file(),
symbol,
selected.pieces.iter().map(|piece| &piece.symbol),
)?;
let old_module = ns.address(&from_path)?;
let old = old_module.join(self.name.as_str());
let consumers = graph.consumers(&ns, &old, &[&from_path, &to_path])?;
let evidence =
graph.references(&ReferencesQuery::new(self.name.as_str()).declared_in(&from_path))?;
let nodes = graph.fragments(&ns)?;
let mut mv = SymbolMove::new(&ns, &self.name, &source, &dest, extraction, consumers)?;
mv.notice_resolved_uses(&evidence.occurrences);
mv.provision()?;
mv.rebase_consumers(&nodes)?;
mv.keep_old_file_working()?;
mv.drop_redundant_import()?;
mv.widen_for_consumers();
mv.cut_and_paste()?;
let (change, from, to) = mv.finish();
Planned::of(
workspace,
change,
Intent::MoveSymbol(self.clone()),
|bound, files| MoveSymbol {
intent: self.clone(),
declaration: selected.declaration.clone(),
pieces: selected.pieces.clone(),
state: crate::MutationState::Preview,
from,
to,
notices: bound.notices,
respellings: bound.respellings,
files,
},
)
}
}
struct SymbolMove<'a> {
ns: &'a Namespace,
surgery: &'a dyn Surgery,
name: &'a str,
from_path: &'a Path,
to_path: &'a Path,
old_module: Address,
new_module: Address,
old: Address,
new: Address,
source_fragment: std::sync::Arc<Fragment>,
dest_fragment: std::sync::Arc<Fragment>,
source: Parsed<'a>,
dest: Parsed<'a>,
source_witness: &'a crate::workspace::SourceWitness,
dest_witness: &'a crate::workspace::SourceWitness,
extraction: Extraction<'a>,
consumers: Vec<Address>,
old_file_still_uses: bool,
change: Change,
text_edits: Vec<Edit>,
new_imports: Vec<String>,
}
impl<'a> SymbolMove<'a> {
fn new(
ns: &'a Namespace,
name: &'a str,
source: &'a Candidate,
dest: &'a Candidate,
extraction: Extraction<'a>,
consumers: Vec<Address>,
) -> Result<Self, EngineError> {
let old_module = ns.address(source.path())?;
let new_module = ns.address(dest.path())?;
Ok(Self {
ns,
surgery: ns.surgery()?,
name,
from_path: source.path(),
to_path: dest.path(),
old: old_module.join(name),
new: new_module.join(name),
old_module,
new_module,
source_fragment: source.fragment(ns)?,
dest_fragment: dest.fragment(ns)?,
source: Parsed {
path: source.path(),
source: source.file().source(),
facts: source.facts()?,
},
dest: Parsed {
path: dest.path(),
source: dest.file().source(),
facts: dest.facts()?,
},
source_witness: source.file().witness(),
dest_witness: dest.file().witness(),
extraction,
consumers,
old_file_still_uses: false,
change: Change::new(),
text_edits: Vec::new(),
new_imports: Vec::new(),
})
}
fn notice_resolved_uses(&mut self, occurrences: &[crate::Occurrence]) {
for m in occurrences
.iter()
.filter(|o| o.confidence == Confidence::Resolved)
.map(|o| &o.m)
{
if m.path == self.from_path {
let in_import = self
.source
.facts
.imports
.iter()
.any(|i| i.span.contains(&m.span));
if !self.extraction.contains(m.span)
&& !in_import
&& !self.extraction.shadowed(self.source.facts, m.span, |kind| {
self.ns.is_addressable(kind)
})
{
self.old_file_still_uses = true;
}
} else if m.path != self.to_path
&& let Ok(module) = self.ns.address(&m.path)
&& !self.consumers.contains(&module)
{
self.consumers.push(module);
}
}
}
fn provision(&mut self) -> Result<(), EngineError> {
let used = self.extraction.names_used(self.source.facts);
let already: BTreeSet<String> = self
.dest
.facts
.imports
.iter()
.filter(|i| i.declares && !self.dest.is_group_prefix(i))
.filter_map(|i| i.binding())
.map(Name::to_string)
.collect();
let source = self.source;
for edge in self
.source_fragment
.imports()
.filter(|e| !self.extraction.contains(e.import.span))
{
let import = &edge.import;
if source.is_group_prefix(import) {
continue;
}
let Some(name) = import.binding().map(Name::to_string) else {
continue;
};
if !used.contains(&name) || already.contains(&name) || name == self.name {
continue;
}
let statement = match edge.address() {
Some(address) if !address.is_root() => {
self.surgery
.import_statement(self.ns.project(), self.to_path, address, &name)
}
_ => self.surgery.import_of_path(&import.path, &name),
};
if let Some(statement) = statement
&& !self.new_imports.contains(&statement)
{
self.new_imports.push(statement);
}
}
let siblings: Vec<&vvv_core::Symbol> = source
.facts
.symbols
.iter()
.filter(|s| {
s.name != self.name
&& self.ns.is_addressable(s.kind)
&& used.contains(&s.name)
&& !already.contains(&s.name)
&& !self.extraction.contains(s.span)
})
.collect();
for sibling in siblings {
let address = self.old_module.join(sibling.name.as_str());
if let Some(statement) = self.surgery.import_statement(
self.ns.project(),
self.to_path,
&address,
&sibling.name,
) && !self.new_imports.contains(&statement)
{
self.new_imports.push(statement);
}
if !self
.ns
.reach(&self.old_module, sibling)
.admits(&self.new_module)
{
let widen = Widen {
symbol: sibling,
source: self.source.source,
needs: Reach::narrowest(
&self.old_module,
std::slice::from_ref(&self.new_module),
),
consumer: self.new_module.clone(),
notice_at: (
self.from_path.to_path_buf(),
self.source.source.position(sibling.name_span.start),
),
};
match widen.plan(self.surgery) {
Ok(edit) => self.change.edit(self.source_witness, edit)?,
Err(notice) => self.change.notice(notice),
}
}
}
Ok(())
}
fn rebase_consumers(&mut self, nodes: &[Node]) -> Result<(), EngineError> {
let rebase = Rebase::new(self.ns, self.old.clone(), self.new.clone());
for node in nodes.iter().filter(|c| c.path() != self.to_path) {
let site = if node.path() == self.from_path {
let (moving, staying) = Site::partition(node, self.to_path, &self.extraction);
let rewritten = rebase.rewrite(&moving)?;
self.text_edits.extend(rewritten.edits);
for notice in rewritten.notices {
self.change.notice(notice);
}
staying
} else {
Site::new(node, node.path())
};
let (contribution, _) = rebase.rewrite(&site)?.into_change()?;
self.change.merge(contribution)?;
}
Ok(())
}
fn keep_old_file_working(&mut self) -> Result<(), EngineError> {
if self.old_file_still_uses
&& let Some(statement) = self.surgery.import_statement(
self.ns.project(),
self.from_path,
&self.new,
self.name,
)
{
self.change.edit(
self.source_witness,
Edit::insert(
self.surgery.import_insertion(&self.source),
format!("{statement}\n"),
),
)?;
}
Ok(())
}
fn drop_redundant_import(&mut self) -> Result<(), EngineError> {
let text = self.dest.source.as_str();
for edge in self.dest_fragment.imports() {
let import = &edge.import;
if edge.address() != Some(&self.old) {
continue;
}
match &import.group {
None => {
let statement = Span::new(
text[..import.span.start].rfind('\n').map_or(0, |i| i + 1),
text[import.span.end..]
.find('\n')
.map_or(text.len(), |nl| import.span.end + nl + 1),
);
self.change
.edit(self.dest_witness, Edit::delete(statement))?;
}
Some(_) => self.change.notice(Notice {
path: self.to_path.into(),
start: self.dest.source.position(import.span.start),
kind: NoticeKind::RedundantImport {
import: import.path.to_string(),
},
}),
}
}
Ok(())
}
fn widen_for_consumers(&mut self) {
let reach = self.ns.reach(&self.new_module, self.extraction.symbol);
let blind: Vec<Address> = self
.consumers
.iter()
.filter(|c| !reach.admits(c))
.cloned()
.collect();
let Some(first) = blind.first() else {
return;
};
let widen = Widen {
symbol: self.extraction.symbol,
source: self.source.source,
needs: Reach::narrowest(&self.new_module, &blind),
consumer: first.clone(),
notice_at: (
self.to_path.to_path_buf(),
self.dest.source.position(self.dest.source.len()),
),
};
match widen.plan(self.surgery) {
Ok(edit) => self.text_edits.push(edit),
Err(notice) => self.change.notice(notice),
}
}
fn cut_and_paste(&mut self) -> Result<(), EngineError> {
let moved = self.extraction.assemble(&self.text_edits)?;
for cut in self.extraction.cuts() {
self.change.edit(self.source_witness, Edit::delete(cut))?;
}
if !self.new_imports.is_empty() {
let at = self.surgery.import_insertion(&self.dest);
let block: String = self.new_imports.iter().map(|s| format!("{s}\n")).collect();
self.change
.edit(self.dest_witness, Edit::insert(at, block))?;
}
let at = self.surgery.item_insertion(&self.dest);
let text = self.dest.source.as_str();
let separator = if text.is_empty() || text.ends_with("\n\n") {
""
} else if text.ends_with('\n') {
"\n"
} else {
"\n\n"
};
self.change.edit(
self.dest_witness,
Edit::insert(at, format!("{separator}{moved}\n")),
)?;
Ok(())
}
fn finish(self) -> (Change, Address, Address) {
(self.change, self.old, self.new)
}
}
impl Document {
pub(crate) fn move_symbol(result: &MoveSymbol) -> Self {
let mut report = Self::new();
report.title(IntentLine(&Intent::MoveSymbol(result.intent.clone())));
let structural = report.moved(
result.state,
&result.files,
&result.respellings,
&result.notices,
);
report.moved_summary(
result.state,
MoveCounts {
respellings: result.respellings.len(),
structural,
notices: result.notices.len(),
files: result.files.len(),
},
);
report
}
}