Skip to main content

vvv_engine/move_file/
mod.rs

1//! Moving a file or a directory: the [`MoveSet`] lists every file that
2//! travels (a directory's contents, plus the layout's companions such as
3//! Rust's `a.rs` beside `a/`); the [`Rebase`] knows the old and new address
4//! of the moved thing, via the language's [`Layout`](vvv_core::Layout),
5//! and re-renders every import that resolved under the old one — moved
6//! files' own imports from their new locations. The language's
7//! [`Surgery`](vvv_core::Surgery) adds whatever else it needs (Rust `mod`
8//! declarations), from the parsed files the layout named.
9
10mod extraction;
11mod reachability;
12mod rebase;
13mod set;
14mod symbol;
15mod widen;
16
17pub(crate) use extraction::Extraction;
18pub(crate) use reachability::Reachability;
19pub(crate) use rebase::Rebase;
20pub(crate) use set::MoveSet;
21pub(crate) use widen::Widen;
22
23use std::path::Path;
24
25use vvv_core::{Address, Facts, Parsed, ReachKind, ResolveError};
26
27use crate::change::Change;
28use crate::command::{Command, Context};
29use crate::{EngineError, Move, MoveIntent, Planned, SourceFile, VfsError};
30
31/// Plan moving a file or a directory. Nothing is written; see
32/// [`Apply`](crate::Apply). A directory moves with everything under it; a
33/// Rust module moves with its `a.rs` + `a/` pair either way.
34impl Command for MoveIntent {
35    type Output = Planned<Move>;
36
37    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
38        let intent = &self;
39        let from = cx.workspace.normalize(&intent.from);
40        let to = cx.workspace.normalize(&intent.to);
41        if to.starts_with(&from) {
42            return Err(ResolveError::IntoItself {
43                from: from.into(),
44                to: to.into(),
45            }
46            .into());
47        }
48        let graph = &mut *cx.graph;
49        let language = graph
50            .language_of(&from)
51            .or_else(|| graph.language_of_directory(&from))
52            .ok_or_else(|| EngineError::NoLanguage(from.clone().into()))?;
53        let ns = graph
54            .namespace(&language.id())
55            .ok_or_else(|| EngineError::NoLayout(language.id()))?;
56        let (layout, surgery) = (ns.layout(), ns.surgery()?);
57        let project = ns.project().clone();
58        let candidates = graph.files(Some(&language.id()));
59        let moves = MoveSet::compute(cx.workspace, layout, &project, &from, &to)?;
60        if moves.is_empty() {
61            return Err(VfsError::NotFound(from).into());
62        }
63        for (f, t) in moves.iter() {
64            let same_language = |p: &Path| {
65                graph
66                    .language_of(p)
67                    .is_some_and(|l| l.id() == language.id())
68            };
69            if !same_language(f) {
70                return Err(EngineError::NoLanguage(f.into()));
71            }
72            if !same_language(t) {
73                return Err(EngineError::NoLanguage(t.into()));
74            }
75            if cx.workspace.vfs().exists(&cx.workspace.absolute(t)) {
76                return Err(EngineError::Exists(t.into()));
77            }
78        }
79
80        let rebase = Rebase::new(layout, surgery, &project, &from, &to, &moves)?;
81        let mut change = Change::new();
82        let mut references: Vec<(Address, Address)> = Vec::new();
83        for candidate in &candidates {
84            let rewrite = rebase.rewrite(candidate)?;
85            change.merge(rewrite.change);
86            references.extend(rewrite.references);
87        }
88        references.sort();
89        references.dedup();
90
91        // Can every reference still see what it names? Widen what needs it,
92        // as narrowly as real code writes; across a package boundary, say so.
93        let old = layout.address(&project, &from)?;
94        let new = layout.address(&project, &to)?;
95        let violations = Reachability::new(layout, ns.semantics(), &project, &old, &new)
96            .check(graph, &references)?;
97        let mut moved_mod_needs: Option<ReachKind> = None;
98        for violation in violations {
99            let is_moved_mod = violation.symbol.kind == vvv_core::SymbolKind::Module
100                && violation.declaring.join(violation.symbol.name.as_str()) == new;
101            if is_moved_mod && violation.needs != ReachKind::Everyone {
102                // Its line is being moved by `relocate`; tell it what to write.
103                moved_mod_needs = Some(violation.needs);
104                continue;
105            }
106            let file = cx.workspace.load(&violation.path)?;
107            let at = (
108                violation.path.clone(),
109                file.source().position(violation.symbol.name_span.start),
110            );
111            // Across a package boundary every consumer is told; otherwise one
112            // widening serves them all.
113            let consumers: Vec<Address> = if violation.needs == ReachKind::Everyone {
114                violation.consumers.clone()
115            } else {
116                vec![
117                    violation
118                        .consumers
119                        .first()
120                        .cloned()
121                        .unwrap_or_else(|| new.clone()),
122                ]
123            };
124            for consumer in consumers {
125                let widen = Widen {
126                    symbol: &violation.symbol,
127                    source: file.source(),
128                    needs: violation.needs,
129                    consumer,
130                    notice_at: at.clone(),
131                };
132                match widen.plan(surgery) {
133                    Ok(edit) => change.edit(&violation.path, edit),
134                    Err(notice) => change.notice(notice),
135                }
136            }
137        }
138
139        // What else the move changes — Rust's `mod` lines — the layout names
140        // and the surgery writes, from the parsed files, never from disk.
141        let touched: Vec<(SourceFile, Facts)> = layout
142            .touched_by_move(&project, &from, &to)?
143            .into_iter()
144            .map(|path| {
145                let file = cx.workspace.load(&path)?;
146                let facts = language
147                    .facts(file.text())
148                    .map_err(|source| EngineError::Search {
149                        path: path.clone().into(),
150                        source,
151                    })?;
152                Ok((file, facts))
153            })
154            .collect::<Result<_, EngineError>>()?;
155        let parsed: Vec<Parsed<'_>> = touched
156            .iter()
157            .map(|(file, facts)| Parsed {
158                path: file.path(),
159                source: file.source(),
160                facts,
161            })
162            .collect();
163        for side in surgery.relocate(&project, &from, &to, &parsed, moved_mod_needs)? {
164            change.edit(side.path, side.edit);
165        }
166        for (f, t) in moves.iter() {
167            change.move_file(f, t);
168        }
169        Planned::of(cx.workspace, change, |bound, files| Move {
170            intent: intent.clone(),
171            applied: false,
172            history_id: None,
173            from: from.into(),
174            to: to.into(),
175            from_address: Some(old),
176            to_address: Some(new),
177            notices: bound.notices,
178            respellings: bound.respellings,
179            files,
180        })
181    }
182}