Skip to main content

vvv_engine/move_file/
symbol.rs

1//! `move --symbol`: one declaration moved between files of its language.
2//!
3//! The [`Extraction`] is the text that travels. The [`SymbolMove`] is the
4//! situation the graph establishes before anything is written — both files
5//! parsed, the old and new addresses, who consumes the declaration, whether
6//! the old file still uses it — and the operations over it: paths inside the
7//! moved text re-spelled from the new file, the imports it needs brought
8//! along, every consumer pointed at the new address, the old file kept
9//! working, visibility kept wide enough, and finally the cut and the paste.
10//! Each operation appends to one [`Change`]; only the paste depends on the
11//! others, since edits inside the moved text travel with it.
12
13use std::collections::BTreeSet;
14use std::path::Path;
15
16use vvv_core::{Address, Edit, Name, Parsed, Span, Surgery};
17
18use super::{Extraction, MoveSet, Rebase, Widen};
19use crate::change::Change;
20use crate::command::{Command, Context};
21use crate::graph::{Candidate, Namespace};
22use crate::{
23    Confidence, EngineError, MoveSymbol, MoveSymbolIntent, Notice, NoticeKind, Planned, Reach,
24    ReferencesQuery, VfsError,
25};
26
27/// Plan moving one declaration to another file of its language. Nothing is
28/// written; see [`Apply`](crate::Apply).
29impl Command for MoveSymbolIntent {
30    type Output = Planned<MoveSymbol>;
31
32    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
33        let from_path = cx.workspace.normalize(&self.from);
34        let to_path = cx.workspace.normalize(&self.to);
35        let graph = &mut *cx.graph;
36        let source = graph.file(&from_path)?;
37        let dest = graph
38            .candidate(&to_path)
39            .ok_or_else(|| VfsError::NotFound(to_path.clone()))?;
40        if source.language() != dest.language() {
41            return Err(EngineError::NoLanguage(to_path.clone().into()));
42        }
43        let ns = graph.namespace_of(&from_path)?;
44        let extraction = Extraction::of(source.facts()?, source.text(), &self.name, |kind| {
45            ns.is_addressable(kind)
46        })
47        .ok_or_else(|| EngineError::NoSuchSymbol {
48            name: self.name.clone(),
49            kind: None,
50        })?;
51        let old_module = ns.address(&from_path)?;
52        let old = old_module.join(self.name.as_str());
53        let consumers = graph.consumers(&ns, &old, &[&from_path, &to_path])?;
54        let evidence =
55            graph.references(&ReferencesQuery::new(self.name.as_str()).declared_in(&from_path))?;
56        let candidates = graph.files(Some(&ns.id()));
57
58        let mut mv = SymbolMove::new(&ns, &self.name, &source, &dest, extraction, consumers)?;
59        mv.notice_resolved_uses(&evidence.occurrences);
60        mv.respell_inner_paths();
61        mv.provision()?;
62        mv.rebase_consumers(&candidates)?;
63        mv.keep_old_file_working();
64        mv.drop_redundant_import();
65        mv.widen_for_consumers();
66        mv.cut_and_paste();
67        let (change, from, to) = mv.finish();
68        Planned::of(cx.workspace, change, |bound, files| MoveSymbol {
69            intent: self.clone(),
70            applied: false,
71            history_id: None,
72            from,
73            to,
74            notices: bound.notices,
75            respellings: bound.respellings,
76            files,
77        })
78    }
79}
80
81/// One declaration on its way from one file to another: what the graph
82/// established about it, and the change the operations build.
83struct SymbolMove<'a> {
84    ns: &'a Namespace,
85    surgery: &'a dyn Surgery,
86    name: &'a str,
87    from_path: &'a Path,
88    to_path: &'a Path,
89    old_module: Address,
90    new_module: Address,
91    old: Address,
92    new: Address,
93    source: Parsed<'a>,
94    dest: Parsed<'a>,
95    extraction: Extraction<'a>,
96    /// Modules that name the declaration and must still reach it afterwards.
97    consumers: Vec<Address>,
98    /// Whether the old file still names the declaration outside the moved
99    /// text and its imports, so it will need an import of the new address.
100    old_file_still_uses: bool,
101    change: Change,
102    /// Edits inside the moved text, in the old file's coordinates; they
103    /// travel with it rather than being written where they are.
104    text_edits: Vec<Edit>,
105    /// Import statements the destination gains, in order, no duplicates.
106    new_imports: Vec<String>,
107}
108
109impl<'a> SymbolMove<'a> {
110    fn new(
111        ns: &'a Namespace,
112        name: &'a str,
113        source: &'a Candidate,
114        dest: &'a Candidate,
115        extraction: Extraction<'a>,
116        consumers: Vec<Address>,
117    ) -> Result<Self, EngineError> {
118        let old_module = ns.address(source.path())?;
119        let new_module = ns.address(dest.path())?;
120        Ok(Self {
121            ns,
122            surgery: ns.surgery()?,
123            name,
124            from_path: source.path(),
125            to_path: dest.path(),
126            old: old_module.join(name),
127            new: new_module.join(name),
128            old_module,
129            new_module,
130            source: Parsed {
131                path: source.path(),
132                source: source.file().source(),
133                facts: source.facts()?,
134            },
135            dest: Parsed {
136                path: dest.path(),
137                source: dest.file().source(),
138                facts: dest.facts()?,
139            },
140            extraction,
141            consumers,
142            old_file_still_uses: false,
143            change: Change::new(),
144            text_edits: Vec::new(),
145            new_imports: Vec::new(),
146        })
147    }
148
149    /// What the resolved uses of the declaration say: a bare use left in the
150    /// old file means it needs an import afterwards; every other file with
151    /// one is a consumer too.
152    fn notice_resolved_uses(&mut self, occurrences: &[crate::Occurrence]) {
153        for m in occurrences
154            .iter()
155            .filter(|o| o.confidence == Confidence::Resolved)
156            .map(|o| &o.m)
157        {
158            if m.path == self.from_path {
159                let in_import = self
160                    .source
161                    .facts
162                    .imports
163                    .iter()
164                    .any(|i| i.span.contains(&m.span));
165                if !self.extraction.contains(m.span) && !in_import {
166                    self.old_file_still_uses = true;
167                }
168            } else if m.path != self.to_path
169                && let Ok(module) = self.ns.address(&m.path)
170                && !self.consumers.contains(&module)
171            {
172                self.consumers.push(module);
173            }
174        }
175    }
176
177    /// Qualified paths inside the moved text, re-rendered from the new file.
178    fn respell_inner_paths(&mut self) {
179        for import in self
180            .source
181            .facts
182            .imports
183            .iter()
184            .filter(|i| !i.declares && self.extraction.contains(i.span))
185        {
186            if let Some(resolved) = self.ns.resolve(self.from_path, &import.path) {
187                let rendered =
188                    self.surgery
189                        .render(self.ns.project(), self.to_path, &resolved, &import.path);
190                if rendered != import.path {
191                    self.text_edits
192                        .push(Edit::replace(import.span, rendered.to_string()));
193                }
194            }
195        }
196    }
197
198    /// What the moved text uses: imports of the old file it relied on, and
199    /// siblings declared beside it. Both become imports in the new file;
200    /// siblings must also stay visible from there.
201    fn provision(&mut self) -> Result<(), EngineError> {
202        let used = self.extraction.names_used(self.source.facts);
203        let already: BTreeSet<String> = self
204            .dest
205            .facts
206            .imports
207            .iter()
208            .filter(|i| i.declares && !self.dest.is_group_prefix(i))
209            .filter_map(|i| i.binding())
210            .map(Name::to_string)
211            .collect();
212        let source = self.source;
213        for import in source
214            .facts
215            .imports
216            .iter()
217            .filter(|i| i.declares && !self.extraction.contains(i.span))
218        {
219            if source.is_group_prefix(import) {
220                continue;
221            }
222            let Some(name) = import.binding().map(Name::to_string) else {
223                continue;
224            };
225            if !used.contains(&name) || already.contains(&name) || name == self.name {
226                continue;
227            }
228            let statement = match self.ns.resolve(self.from_path, &import.path) {
229                Some(address) if !address.is_root() => {
230                    self.surgery
231                        .import_statement(self.ns.project(), self.to_path, &address, &name)
232                }
233                _ => self.surgery.import_of_path(&import.path, &name),
234            };
235            if let Some(statement) = statement
236                && !self.new_imports.contains(&statement)
237            {
238                self.new_imports.push(statement);
239            }
240        }
241        let siblings: Vec<&vvv_core::Symbol> = source
242            .facts
243            .symbols
244            .iter()
245            .filter(|s| {
246                s.name != self.name
247                    && self.ns.is_addressable(s.kind)
248                    && used.contains(&s.name)
249                    && !already.contains(&s.name)
250                    && !self.extraction.contains(s.span)
251            })
252            .collect();
253        for sibling in siblings {
254            let address = self.old_module.join(sibling.name.as_str());
255            if let Some(statement) = self.surgery.import_statement(
256                self.ns.project(),
257                self.to_path,
258                &address,
259                &sibling.name,
260            ) && !self.new_imports.contains(&statement)
261            {
262                self.new_imports.push(statement);
263            }
264            if !self
265                .ns
266                .reach(&self.old_module, sibling)
267                .admits(&self.new_module)
268            {
269                let widen = Widen {
270                    symbol: sibling,
271                    source: self.source.source,
272                    needs: Reach::narrowest(
273                        &self.old_module,
274                        std::slice::from_ref(&self.new_module),
275                    ),
276                    consumer: self.new_module.clone(),
277                    notice_at: (
278                        self.from_path.to_path_buf(),
279                        self.source.source.position(sibling.name_span.start),
280                    ),
281                };
282                match widen.plan(self.surgery) {
283                    Ok(edit) => self.change.edit(self.from_path, edit),
284                    Err(notice) => self.change.notice(notice),
285                }
286            }
287        }
288        Ok(())
289    }
290
291    /// Every consumer: imports and qualified paths are rebased to the new
292    /// address. Self-references inside the moved text travel with it and are
293    /// not rows of the preview.
294    fn rebase_consumers(&mut self, candidates: &[Candidate]) -> Result<(), EngineError> {
295        let no_moves = MoveSet::default();
296        let rebase = Rebase::of_addresses(
297            self.ns.layout(),
298            self.surgery,
299            self.ns.project(),
300            &no_moves,
301            self.old.clone(),
302            self.new.clone(),
303        );
304        for candidate in candidates.iter().filter(|c| c.path() != self.to_path) {
305            let mut rewrite = rebase.rewrite(candidate)?;
306            if candidate.path() == self.from_path {
307                let (moving, staying): (Vec<Edit>, Vec<Edit>) = rewrite
308                    .change
309                    .take_edits(self.from_path)
310                    .into_iter()
311                    .partition(|e| self.extraction.contains(e.span));
312                self.text_edits.extend(moving);
313                rewrite.change.edits(self.from_path, staying);
314                let extraction = &self.extraction;
315                rewrite
316                    .change
317                    .retain_respellings(|r| !extraction.contains(r.span));
318            }
319            self.change.merge(rewrite.change);
320        }
321        Ok(())
322    }
323
324    /// A bare use left in the old file needs an import of the new address.
325    fn keep_old_file_working(&mut self) {
326        if self.old_file_still_uses
327            && let Some(statement) = self.surgery.import_statement(
328                self.ns.project(),
329                self.from_path,
330                &self.new,
331                self.name,
332            )
333        {
334            self.change.edit(
335                self.from_path,
336                Edit::insert(
337                    self.surgery.import_insertion(&self.source),
338                    format!("{statement}\n"),
339                ),
340            );
341        }
342    }
343
344    /// An import of the declaration in the file it moves to is now
345    /// redundant: delete the statement, or say so when it shares a group.
346    fn drop_redundant_import(&mut self) {
347        let text = self.dest.source.as_str();
348        for import in self.dest.facts.imports.iter().filter(|i| i.declares) {
349            if self.ns.resolve(self.to_path, &import.path).as_ref() != Some(&self.old) {
350                continue;
351            }
352            match &import.group {
353                None => {
354                    let statement = Span::new(
355                        text[..import.span.start].rfind('\n').map_or(0, |i| i + 1),
356                        text[import.span.end..]
357                            .find('\n')
358                            .map_or(text.len(), |nl| import.span.end + nl + 1),
359                    );
360                    self.change.edit(self.to_path, Edit::delete(statement));
361                }
362                Some(_) => self.change.notice(Notice {
363                    path: self.to_path.into(),
364                    start: self.dest.source.position(import.span.start),
365                    kind: NoticeKind::RedundantImport {
366                        import: import.path.to_string(),
367                    },
368                }),
369            }
370        }
371    }
372
373    /// The item's own reach at its new home: widened for the consumers it
374    /// no longer admits, as narrowly as real code writes.
375    fn widen_for_consumers(&mut self) {
376        let reach = self.ns.reach(&self.new_module, self.extraction.symbol);
377        let blind: Vec<Address> = self
378            .consumers
379            .iter()
380            .filter(|c| !reach.admits(c))
381            .cloned()
382            .collect();
383        let Some(first) = blind.first() else {
384            return;
385        };
386        let widen = Widen {
387            symbol: self.extraction.symbol,
388            source: self.source.source,
389            needs: Reach::narrowest(&self.new_module, &blind),
390            consumer: first.clone(),
391            notice_at: (
392                self.to_path.to_path_buf(),
393                self.dest.source.position(self.dest.source.len()),
394            ),
395        };
396        match widen.plan(self.surgery) {
397            Ok(edit) => self.text_edits.push(edit),
398            Err(notice) => self.change.notice(notice),
399        }
400    }
401
402    /// Cut the pieces out of the old file; paste them, with their edits,
403    /// where the destination keeps items, its new imports above.
404    fn cut_and_paste(&mut self) {
405        let moved = self.extraction.assemble(&self.text_edits);
406        for cut in self.extraction.cuts() {
407            self.change.edit(self.from_path, Edit::delete(cut));
408        }
409        if !self.new_imports.is_empty() {
410            let at = self.surgery.import_insertion(&self.dest);
411            let block: String = self.new_imports.iter().map(|s| format!("{s}\n")).collect();
412            self.change.edit(self.to_path, Edit::insert(at, block));
413        }
414        let at = self.surgery.item_insertion(&self.dest);
415        let text = self.dest.source.as_str();
416        let separator = if text.is_empty() || text.ends_with("\n\n") {
417            ""
418        } else if text.ends_with('\n') {
419            "\n"
420        } else {
421            "\n\n"
422        };
423        self.change.edit(
424            self.to_path,
425            Edit::insert(at, format!("{separator}{moved}\n")),
426        );
427    }
428
429    fn finish(self) -> (Change, Address, Address) {
430        (self.change, self.old, self.new)
431    }
432}