Skip to main content

vvv_core/resolve/
mod.rs

1//! How files and import paths map onto a language's namespace.
2//!
3//! Two capabilities, both pure: a [`Layout`] knows how a project is arranged
4//! — which [`Address`] a file has, what an import path written in a file
5//! points at, where a module may live — and a [`Surgery`] knows how to spell
6//! an edit in the language — a path from one file to an address, a grouped
7//! import rewritten, the declarations a move drags along. Neither touches a
8//! file system: both read a [`Project`], the workspace as data the engine
9//! built from its walk, and return plain values.
10
11mod address;
12mod project;
13
14use std::path::{Path, PathBuf};
15
16pub use address::{Address, Dependency, Package, PackageId, Packages};
17pub use project::{FileSet, Parsed, Project};
18
19use crate::edit::Edit;
20use crate::import::ImportRef;
21use crate::paths::{ModulePath, RelPath};
22use crate::semantics::ReachKind;
23use crate::symbol::Symbol;
24use crate::text::{SourceText, Span};
25
26/// Why a resolver could not address, read, or relocate a file. Each variant
27/// is a distinct situation with its own remedy; the message is one rendering.
28#[derive(Debug, thiserror::Error, PartialEq, Eq)]
29pub enum ResolveError {
30    #[error("{} is not addressable in this language (outside the module tree?)", .0.display())]
31    NotAddressable(RelPath),
32    #[error("{} does not exist", .0.display())]
33    Missing(RelPath),
34    #[error("{} is a crate or directory root; moving it is not supported", .0.display())]
35    Root(RelPath),
36    #[error("{} would end up inside itself at {}", from.display(), to.display())]
37    IntoItself { from: RelPath, to: RelPath },
38    #[error("moving between crates is not supported ({} → {})", from.display(), to.display())]
39    CrossProject { from: RelPath, to: RelPath },
40    #[error("cannot find the file declaring `{name}`")]
41    NoDeclaringFile { name: String },
42    #[error(
43        "no file declares module `{module}`; create {} first so `{declaration}` has a home",
44        Candidates(candidates)
45    )]
46    NoParentFile {
47        module: String,
48        candidates: Vec<RelPath>,
49        declaration: String,
50    },
51    #[error("no `{declaration}` in {}; inline or #[path] modules are not supported", parent.display())]
52    NoDeclaration {
53        declaration: String,
54        parent: RelPath,
55    },
56    #[error("cannot parse {}: {reason}", path.display())]
57    Syntax { path: RelPath, reason: String },
58}
59
60/// `a.rs (or a/mod.rs)` for error messages.
61struct Candidates<'a>(&'a [RelPath]);
62
63impl std::fmt::Display for Candidates<'_> {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self.0 {
66            [] => write!(f, "the module file"),
67            [only] => write!(f, "{}", only.display()),
68            [first, rest @ ..] => {
69                write!(f, "{}", first.display())?;
70                write!(f, " (or ")?;
71                for (i, p) in rest.iter().enumerate() {
72                    if i > 0 {
73                        write!(f, ", ")?;
74                    }
75                    write!(f, "{}", p.display())?;
76                }
77                write!(f, ")")
78            }
79        }
80    }
81}
82
83/// Extra change a move requires in a file other than import rewrites.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct SideEdit {
86    pub path: PathBuf,
87    pub edit: Edit,
88}
89
90/// How a language's projects are arranged on disk: a pure function of the
91/// [`Project`] — no file is read, no existence probed, beyond what the
92/// project already lists.
93pub trait Layout: Send + Sync {
94    /// File names of manifests that declare a package (`Cargo.toml`).
95    fn manifests(&self) -> &'static [&'static str];
96
97    /// The package a manifest declares, from its text; `None` when it
98    /// declares none (a workspace-only `Cargo.toml`).
99    fn package(&self, manifest: &Path, text: &str) -> Option<Package>;
100
101    /// Address a file or directory at `path` (workspace-relative) has or
102    /// would have.
103    fn address(&self, project: &Project, path: &Path) -> Result<Address, ResolveError>;
104
105    /// Where a module at `address` may be declared, most conventional first
106    /// (`a.rs` before `a/mod.rs`); the project says which exists.
107    fn candidates(&self, project: &Project, address: &Address) -> Vec<PathBuf>;
108
109    /// What `import` written in `from` points at, if the layout can tell. A
110    /// path into a dependency outside the workspace resolves into that
111    /// package's address space (its files are unknown, its name is not);
112    /// unresolvable relative paths and unknown heads yield `None`.
113    fn resolve(&self, project: &Project, from: &Path, import: &ModulePath) -> Option<Address>;
114
115    /// Paths that must move together with `from → to` because the language
116    /// treats them as one unit: Rust's `a.rs` and `a/`. Each pair is
117    /// (current path, destination); directories are expanded by the caller.
118    fn companions(&self, project: &Project, from: &Path, to: &Path) -> Vec<(PathBuf, PathBuf)> {
119        let _ = (project, from, to);
120        Vec::new()
121    }
122
123    /// Files whose contents a move of `from` to `to` changes beyond import
124    /// paths — the old and new parent of a Rust module — or why the move is
125    /// impossible. The engine parses them and hands them to
126    /// [`Surgery::relocate`].
127    fn touched_by_move(
128        &self,
129        project: &Project,
130        from: &Path,
131        to: &Path,
132    ) -> Result<Vec<PathBuf>, ResolveError> {
133        let _ = (project, from, to);
134        Ok(Vec::new())
135    }
136}
137
138/// How to spell an edit in a language. Text and facts in, edits out; never
139/// a file.
140pub trait Surgery: Send + Sync {
141    /// Spell a reference to `target` as `from` should write it. `original` is
142    /// the text being replaced, so the style (relative vs absolute, with or
143    /// without extension) can be kept.
144    fn render(
145        &self,
146        project: &Project,
147        from: &Path,
148        target: &Address,
149        original: &ModulePath,
150    ) -> ModulePath;
151
152    /// The statement that brings `name`, declared at `target`, into `from`:
153    /// `use crate::a::Name;`, `import { Name } from './a';`. `None` when the
154    /// language has no import statement vvv can write.
155    fn import_statement(
156        &self,
157        project: &Project,
158        from: &Path,
159        target: &Address,
160        name: &str,
161    ) -> Option<String> {
162        let _ = (project, from, target, name);
163        None
164    }
165
166    /// Rewrite grouped entries of one statement so each points at its new
167    /// target: in place when the target stays under the group's prefix,
168    /// otherwise by moving the entry out into its own statement. `from` is
169    /// where the statement will live; `entries` all share one
170    /// [`ImportGroup::statement`](crate::import::ImportGroup::statement). Every requested entry must have exactly one explicit outcome;
171    /// skipped entries become notices. Prefix addresses are supplied by the
172    /// caller after its planned prefix and binding changes, never re-resolved.
173    fn regroup(
174        &self,
175        project: &Project,
176        from: &Path,
177        source: &SourceText,
178        imports: &GroupedImports,
179    ) -> Regrouped {
180        let _ = (project, from, source);
181        Regrouped::skipped(imports)
182    }
183
184    /// Changes beyond import rewrites when `from` becomes `to`, computed from
185    /// the parsed files the layout named in [`Layout::touched_by_move`].
186    /// `widen_to` is the reach the moved declaration (Rust's `mod` line)
187    /// needs at its new parent, when the engine found consumers its current
188    /// modifier would no longer admit; `None` keeps it as written.
189    fn relocate(
190        &self,
191        project: &Project,
192        from: &Path,
193        to: &Path,
194        touched: &[Parsed<'_>],
195        widen_to: Option<ReachKind>,
196    ) -> Result<Vec<SideEdit>, ResolveError> {
197        let _ = (project, from, to, touched, widen_to);
198        Ok(Vec::new())
199    }
200
201    /// An import statement for a path as written (`use std::fmt;`), for
202    /// imports the layout cannot resolve but a moved item still needs.
203    fn import_of_path(&self, path: &ModulePath, name: &str) -> Option<String> {
204        let _ = (path, name);
205        None
206    }
207
208    /// Where a new import statement goes in a file: after its last import,
209    /// else after what must stay first (Rust's `//!` docs and `#![…]`).
210    fn import_insertion(&self, file: &Parsed<'_>) -> usize {
211        file.facts
212            .imports
213            .iter()
214            .filter(|i| i.declares)
215            .map(|i| i.span.end)
216            .max()
217            .map_or(0, |end| {
218                file.source.as_str()[end..]
219                    .find('\n')
220                    .map_or(file.source.len(), |nl| end + nl + 1)
221            })
222    }
223
224    /// Where a new declaration goes in a file: the end.
225    fn item_insertion(&self, file: &Parsed<'_>) -> usize {
226        file.source.len()
227    }
228
229    /// The edit that gives `symbol` the reach `to`: its modifier replaced, or
230    /// one inserted before the declaration. `None` when the language cannot
231    /// say it, or will not — `Everyone` is never spelled by vvv.
232    fn widen(&self, symbol: &Symbol, source: &SourceText, to: ReachKind) -> Option<Edit> {
233        let _ = (symbol, source, to);
234        None
235    }
236}
237
238/// One grouped entry's required target and its prefix's meaning after the move.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct GroupedImport {
241    pub import: ImportRef,
242    pub target: Address,
243    pub prefix: Option<Address>,
244}
245
246/// Unique grouped entries from one statement, validated at construction.
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub struct GroupedImports {
249    entries: Vec<GroupedImport>,
250    statement: Span,
251}
252
253impl GroupedImports {
254    pub fn new(entries: Vec<GroupedImport>) -> Result<Self, RegroupError> {
255        let first = entries.first().ok_or(RegroupError::Empty)?;
256        let statement = first
257            .import
258            .group
259            .as_ref()
260            .ok_or(RegroupError::NotGrouped(first.import.span))?
261            .statement;
262        for (i, entry) in entries.iter().enumerate() {
263            let group = entry
264                .import
265                .group
266                .as_ref()
267                .ok_or(RegroupError::NotGrouped(entry.import.span))?;
268            if entry.import.path.head != group.prefix.head
269                || !entry
270                    .import
271                    .path
272                    .segments
273                    .starts_with(&group.prefix.segments)
274            {
275                return Err(RegroupError::InvalidPrefix(entry.import.span));
276            }
277            if group.statement != statement {
278                return Err(RegroupError::DifferentStatement(entry.import.span));
279            }
280            if entries[..i]
281                .iter()
282                .any(|e| e.import.span == entry.import.span)
283            {
284                return Err(RegroupError::DuplicateEntry(entry.import.span));
285            }
286        }
287        Ok(Self { entries, statement })
288    }
289
290    pub fn entries(&self) -> &[GroupedImport] {
291        &self.entries
292    }
293    pub fn statement(&self) -> Span {
294        self.statement
295    }
296}
297
298/// The actual handling of one requested entry. In-place replacement is the
299/// text for the entry span, not a separately rendered full path.
300#[derive(Debug, Clone, PartialEq, Eq)]
301pub enum RegroupedOutcome {
302    InPlace { replacement: ModulePath },
303    Structural,
304    Skipped,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct RegroupedEntry {
309    pub span: Span,
310    pub outcome: RegroupedOutcome,
311}
312
313/// Outcome of [`Surgery::regroup`], checked against its request before use.
314#[derive(Debug, Clone, Default, PartialEq, Eq)]
315pub struct Regrouped {
316    pub edits: Vec<Edit>,
317    pub outcomes: Vec<RegroupedEntry>,
318}
319
320impl Regrouped {
321    pub fn skipped(imports: &GroupedImports) -> Self {
322        Self {
323            edits: Vec::new(),
324            outcomes: imports
325                .entries()
326                .iter()
327                .map(|e| RegroupedEntry {
328                    span: e.import.span,
329                    outcome: RegroupedOutcome::Skipped,
330                })
331                .collect(),
332        }
333    }
334
335    pub fn validate<'a>(
336        &'a self,
337        imports: &'a GroupedImports,
338    ) -> Result<Vec<(&'a GroupedImport, &'a RegroupedOutcome)>, RegroupError> {
339        for (i, outcome) in self.outcomes.iter().enumerate() {
340            if !imports
341                .entries()
342                .iter()
343                .any(|e| e.import.span == outcome.span)
344            {
345                return Err(RegroupError::ForeignOutcome(outcome.span));
346            }
347            if self.outcomes[..i].iter().any(|o| o.span == outcome.span) {
348                return Err(RegroupError::DuplicateOutcome(outcome.span));
349            }
350        }
351        imports
352            .entries()
353            .iter()
354            .map(|entry| {
355                let outcome = self
356                    .outcomes
357                    .iter()
358                    .find(|o| o.span == entry.import.span)
359                    .ok_or(RegroupError::MissingOutcome(entry.import.span))?;
360                if let RegroupedOutcome::InPlace { replacement } = &outcome.outcome {
361                    let matching: Vec<_> = self
362                        .edits
363                        .iter()
364                        .filter(|e| e.span == entry.import.span)
365                        .collect();
366                    if matching.len() != 1 || matching[0].replacement != replacement.to_string() {
367                        return Err(RegroupError::InconsistentReplacement(entry.import.span));
368                    }
369                }
370                Ok((entry, &outcome.outcome))
371            })
372            .collect()
373    }
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
377pub enum RegroupError {
378    #[error("a grouped rewrite requires at least one entry")]
379    Empty,
380    #[error("entry {0:?} is not grouped")]
381    NotGrouped(Span),
382    #[error("entry {0:?} belongs to another statement")]
383    DifferentStatement(Span),
384    #[error("entry {0:?} does not extend its group prefix")]
385    InvalidPrefix(Span),
386    #[error("duplicate grouped entry {0:?}")]
387    DuplicateEntry(Span),
388    #[error("grouped rewrite returned a foreign entry {0:?}")]
389    ForeignOutcome(Span),
390    #[error("grouped rewrite returned entry {0:?} twice")]
391    DuplicateOutcome(Span),
392    #[error("grouped rewrite omitted entry {0:?}")]
393    MissingOutcome(Span),
394    #[error("grouped rewrite replacement for {0:?} differs from its edit")]
395    InconsistentReplacement(Span),
396}
397
398#[cfg(test)]
399mod regroup_tests {
400    use super::*;
401    use crate::{ImportGroup, PathSyntax};
402
403    struct Fixture {
404        imports: GroupedImports,
405    }
406
407    impl Fixture {
408        fn new() -> Self {
409            let prefix = PathSyntax::Scoped.parse("crate::a");
410            let mut import =
411                ImportRef::new(Span::new(15, 16), PathSyntax::Scoped.parse("crate::a::X"));
412            import.group = Some(ImportGroup {
413                prefix,
414                item: import.span,
415                list: Span::new(14, 17),
416                items: 1,
417                statement: Span::new(0, 18),
418                top_level: true,
419            });
420            Self {
421                imports: GroupedImports::new(vec![GroupedImport {
422                    import,
423                    target: Address::new("p", ["b", "X"]),
424                    prefix: Some(Address::new("p", ["a"])),
425                }])
426                .unwrap(),
427            }
428        }
429
430        fn span(&self) -> Span {
431            self.imports.entries()[0].import.span
432        }
433        fn outcome(&self, outcome: RegroupedOutcome) -> Regrouped {
434            Regrouped {
435                edits: vec![],
436                outcomes: vec![RegroupedEntry {
437                    span: self.span(),
438                    outcome,
439                }],
440            }
441        }
442    }
443
444    #[test]
445    fn grouped_requests_require_unique_entries_from_one_statement() {
446        let fixture = Fixture::new();
447        assert_eq!(GroupedImports::new(vec![]), Err(RegroupError::Empty));
448        let entry = fixture.imports.entries()[0].clone();
449        assert_eq!(
450            GroupedImports::new(vec![entry.clone(), entry.clone()]),
451            Err(RegroupError::DuplicateEntry(entry.import.span))
452        );
453        let mut other = entry.clone();
454        other.import.group.as_mut().unwrap().statement = Span::new(20, 40);
455        assert_eq!(
456            GroupedImports::new(vec![entry.clone(), other]),
457            Err(RegroupError::DifferentStatement(entry.import.span))
458        );
459        let mut ungrouped = entry;
460        ungrouped.import.group = None;
461        assert_eq!(
462            GroupedImports::new(vec![ungrouped]),
463            Err(RegroupError::NotGrouped(fixture.span()))
464        );
465    }
466
467    #[test]
468    fn regrouped_outcomes_cover_exactly_the_requested_entries() {
469        let fixture = Fixture::new();
470        let mut out = fixture.outcome(RegroupedOutcome::Structural);
471        assert!(out.validate(&fixture.imports).is_ok());
472        out.outcomes.push(out.outcomes[0].clone());
473        assert_eq!(
474            out.validate(&fixture.imports),
475            Err(RegroupError::DuplicateOutcome(fixture.span()))
476        );
477        out.outcomes.pop();
478        out.outcomes[0].span = Span::new(30, 31);
479        assert_eq!(
480            out.validate(&fixture.imports),
481            Err(RegroupError::ForeignOutcome(Span::new(30, 31)))
482        );
483        out.outcomes.clear();
484        assert_eq!(
485            out.validate(&fixture.imports),
486            Err(RegroupError::MissingOutcome(fixture.span()))
487        );
488    }
489
490    #[test]
491    fn in_place_outcomes_report_the_actual_replacement() {
492        let fixture = Fixture::new();
493        let mut out = fixture.outcome(RegroupedOutcome::InPlace {
494            replacement: PathSyntax::Scoped.parse("Y"),
495        });
496        assert_eq!(
497            out.validate(&fixture.imports),
498            Err(RegroupError::InconsistentReplacement(fixture.span()))
499        );
500        out.edits.push(Edit::replace(fixture.span(), "different"));
501        assert_eq!(
502            out.validate(&fixture.imports),
503            Err(RegroupError::InconsistentReplacement(fixture.span()))
504        );
505        out.edits[0].replacement = "Y".into();
506        assert!(out.validate(&fixture.imports).is_ok());
507    }
508
509    #[test]
510    fn default_grouped_outcomes_explicitly_skip_every_target() {
511        let fixture = Fixture::new();
512        let out = Regrouped::skipped(&fixture.imports);
513        let validated = out.validate(&fixture.imports).unwrap();
514        assert_eq!(validated.len(), 1);
515        assert_eq!(validated[0].0.target, Address::new("p", ["b", "X"]));
516        assert!(matches!(validated[0].1, RegroupedOutcome::Skipped));
517        assert!(out.edits.is_empty());
518    }
519}