vvv_engine/capabilities/moves/
file.rs1use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13use vvv_core::{Address, Facts, Parsed, ReachKind, RelPath, ResolveError};
14
15use super::{MoveSet, Reachability, Rebase, Site, Widen};
16use crate::change::Change;
17use crate::protocol::vocabulary::IntentLine;
18use crate::report::{Document, MoveCounts};
19use crate::{
20 EngineError, FileChange, Intent, Mutation, Notice, Planned, Respelling, SourceFile, VfsError,
21};
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
26pub struct MoveIntent {
27 pub from: PathBuf,
28 pub to: PathBuf,
29}
30
31impl MoveIntent {
32 pub fn new(from: impl Into<PathBuf>, to: impl Into<PathBuf>) -> Self {
33 Self {
34 from: from.into(),
35 to: to.into(),
36 }
37 }
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43pub struct Move {
44 pub intent: MoveIntent,
45 #[serde(flatten)]
47 pub state: crate::MutationState,
48 pub from: RelPath,
50 pub to: RelPath,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub from_address: Option<Address>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub to_address: Option<Address>,
56 #[serde(default, skip_serializing_if = "Vec::is_empty")]
58 pub notices: Vec<Notice>,
59 #[serde(default, skip_serializing_if = "Vec::is_empty")]
62 pub respellings: Vec<Respelling>,
63 pub files: Vec<FileChange>,
64}
65
66impl Mutation for Move {
67 fn into_mutation(self) -> crate::MutationAnswer {
68 crate::MutationAnswer::Move(self)
69 }
70
71 fn applied(&mut self, id: u64) {
72 self.state = crate::MutationState::Applied { history_id: id };
73 }
74}
75
76impl MoveIntent {
80 pub fn plan(self, engine: &crate::Engine) -> Result<Planned<Move>, EngineError> {
82 let _operation = engine.operation();
83 let mut graph = engine.graph()?;
84 self.plan_in(&mut graph, engine.workspace())
85 }
86
87 pub(crate) fn plan_in(
88 self,
89 graph: &mut crate::graph::Graph,
90 workspace: &crate::Workspace,
91 ) -> Result<Planned<Move>, EngineError> {
92 let intent = &self;
93 let from = workspace.normalize(&intent.from);
94 let to = workspace.normalize(&intent.to);
95 if to.starts_with(&from) {
96 return Err(ResolveError::IntoItself {
97 from: from.into(),
98 to: to.into(),
99 }
100 .into());
101 }
102 let language = graph
103 .language_of(&from)
104 .or_else(|| graph.language_of_directory(&from))
105 .ok_or_else(|| EngineError::NoLanguage(from.clone().into()))?;
106 let ns = graph
107 .namespace(&language.id())
108 .ok_or_else(|| EngineError::NoLayout(language.id()))?;
109 let (layout, surgery) = (ns.layout(), ns.surgery()?);
110 let project = ns.project().clone();
111 let nodes = graph.fragments(&ns)?;
112 let moves = MoveSet::compute(workspace, layout, &project, &from, &to)?;
113 if moves.is_empty() {
114 return Err(VfsError::NotFound(from).into());
115 }
116 for (f, t) in moves.iter() {
117 let same_language = |p: &Path| {
118 graph
119 .language_of(p)
120 .is_some_and(|l| l.id() == language.id())
121 };
122 if !same_language(f) {
123 return Err(EngineError::NoLanguage(f.into()));
124 }
125 if !same_language(t) {
126 return Err(EngineError::NoLanguage(t.into()));
127 }
128 if workspace
129 .vfs()
130 .entry_kind(&workspace.absolute(t))?
131 .is_some()
132 && !workspace
133 .vfs()
134 .same_entry(&workspace.absolute(f), &workspace.absolute(t))?
135 {
136 return Err(EngineError::Exists(t.into()));
137 }
138 }
139
140 let old = ns.address(&from)?;
141 let new = ns.address(&to)?;
142 let rebase = Rebase::new(&ns, old.clone(), new.clone());
143 let mut change = Change::new();
144 let mut references: Vec<(Address, Address)> = Vec::new();
145 for node in &nodes {
146 let site = Site::new(node, moves.destination(node.path()).unwrap_or(node.path()));
147 let (contribution, affected) = rebase.rewrite(&site)?.into_change()?;
148 change.merge(contribution)?;
149 references.extend(affected);
150 }
151 references.sort();
152 references.dedup();
153
154 let violations = Reachability::new(layout, ns.semantics(), &project, &old, &new)
157 .check(graph, &references)?;
158 let mut moved_mod_needs: Option<ReachKind> = None;
159 for violation in violations {
160 let is_moved_mod = violation.symbol.kind == vvv_core::SymbolKind::Module
161 && violation.declaring.join(violation.symbol.name.as_str()) == new;
162 if is_moved_mod && violation.needs != ReachKind::Everyone {
163 moved_mod_needs = Some(violation.needs);
165 continue;
166 }
167 let candidate = graph.file(&violation.path)?;
168 let file = candidate.file();
169 let at = (
170 violation.path.clone(),
171 file.source().position(violation.symbol.name_span.start),
172 );
173 let consumers: Vec<Address> = if violation.needs == ReachKind::Everyone {
176 violation.consumers.clone()
177 } else {
178 vec![
179 violation
180 .consumers
181 .first()
182 .cloned()
183 .unwrap_or_else(|| new.clone()),
184 ]
185 };
186 for consumer in consumers {
187 let widen = Widen {
188 symbol: &violation.symbol,
189 source: file.source(),
190 needs: violation.needs,
191 consumer,
192 notice_at: at.clone(),
193 };
194 match widen.plan(surgery) {
195 Ok(edit) => change.edit(file.witness(), edit)?,
196 Err(notice) => change.notice(notice),
197 }
198 }
199 }
200
201 let touched: Vec<(SourceFile, Facts)> = layout
204 .touched_by_move(&project, &from, &to)?
205 .into_iter()
206 .map(|path| {
207 let file = match graph.candidate(&path) {
208 Some(candidate) => candidate.file().clone(),
209 None => workspace.load(&path)?,
210 };
211 let facts =
212 file.facts(language.as_ref())
213 .map_err(|source| EngineError::Search {
214 path: path.clone().into(),
215 source,
216 })?;
217 Ok((file, facts))
218 })
219 .collect::<Result<_, EngineError>>()?;
220 let parsed: Vec<Parsed<'_>> = touched
221 .iter()
222 .map(|(file, facts)| Parsed {
223 path: file.path(),
224 source: file.source(),
225 facts,
226 })
227 .collect();
228 for side in surgery.relocate(&project, &from, &to, &parsed, moved_mod_needs)? {
229 let file = touched
230 .iter()
231 .find(|(file, _)| file.path() == side.path)
232 .ok_or_else(|| ResolveError::Missing(side.path.clone().into()))?;
233 change.edit(file.0.witness(), side.edit)?;
234 }
235 for (f, t) in moves.iter() {
236 change.move_file(graph.file(f)?.file().witness(), t)?;
237 }
238 Planned::of(
239 workspace,
240 change,
241 Intent::Move(intent.clone()),
242 |bound, files| Move {
243 intent: intent.clone(),
244 state: crate::MutationState::Preview,
245 from: from.into(),
246 to: to.into(),
247 from_address: Some(old),
248 to_address: Some(new),
249 notices: bound.notices,
250 respellings: bound.respellings,
251 files,
252 },
253 )
254 }
255}
256
257impl Document {
258 pub(crate) fn move_file(result: &Move) -> Self {
259 let mut report = Self::new();
260 report.title(IntentLine(&Intent::Move(MoveIntent::new(
262 &result.from,
263 &result.to,
264 ))));
265 let structural = report.moved(
266 result.state,
267 &result.files,
268 &result.respellings,
269 &result.notices,
270 );
271 report.moved_summary(
272 result.state,
273 MoveCounts {
274 respellings: result.respellings.len(),
275 structural,
276 notices: result.notices.len(),
277 files: result.files.len(),
278 },
279 );
280 report
281 }
282}