Skip to main content

vvv_core/paths/
mod.rs

1//! Names and paths as types, never as text.
2//!
3//! A [`Name`] is one identifier. A [`ModulePath`] is a path *as a language
4//! spells it* — `crate::a::b`, `../x/y`, `react/jsx-runtime` — parsed once
5//! by the grammar's [`PathSyntax`] when facts are extracted, and spelled
6//! back only by that syntax. What a path *means* is an
7//! [`Address`](crate::resolve::Address), which the layout resolves; the two
8//! never mix. Nothing above the grammar ever sees a separator character.
9
10use std::borrow::Borrow;
11use std::fmt;
12use std::ops::Deref;
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16
17/// One identifier: a module, a declaration, a file stem. Compared by text.
18#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
19#[serde(transparent)]
20pub struct Name(String);
21
22impl Name {
23    pub fn new(text: impl Into<String>) -> Self {
24        Self(text.into())
25    }
26
27    pub fn as_str(&self) -> &str {
28        &self.0
29    }
30
31    /// The path as this machine spells it, for an actual file call.
32    pub fn as_path(&self) -> &Path {
33        Path::new(&self.0)
34    }
35}
36
37impl Deref for Name {
38    type Target = str;
39    fn deref(&self) -> &str {
40        &self.0
41    }
42}
43
44impl Borrow<str> for Name {
45    fn borrow(&self) -> &str {
46        &self.0
47    }
48}
49
50impl AsRef<str> for Name {
51    fn as_ref(&self) -> &str {
52        &self.0
53    }
54}
55
56impl PartialEq<str> for Name {
57    fn eq(&self, other: &str) -> bool {
58        self.0 == other
59    }
60}
61
62impl PartialEq<&str> for Name {
63    fn eq(&self, other: &&str) -> bool {
64        self.0 == *other
65    }
66}
67
68impl PartialEq<String> for Name {
69    fn eq(&self, other: &String) -> bool {
70        &self.0 == other
71    }
72}
73
74impl From<&str> for Name {
75    fn from(text: &str) -> Self {
76        Self::new(text)
77    }
78}
79
80impl From<String> for Name {
81    fn from(text: String) -> Self {
82        Self(text)
83    }
84}
85
86impl From<&String> for Name {
87    fn from(text: &String) -> Self {
88        Self(text.clone())
89    }
90}
91
92impl From<Name> for String {
93    fn from(name: Name) -> Self {
94        name.0
95    }
96}
97
98impl fmt::Display for Name {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.write_str(&self.0)
101    }
102}
103
104impl fmt::Debug for Name {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        write!(f, "{:?}", self.0)
107    }
108}
109
110/// A file's path inside the workspace, spelled the way the project does: `/`
111/// on every platform.
112///
113/// A workspace path is a project path — like a `mod` path or a
114/// `crate::a::b` address — not a path of the machine, so it carries its own
115/// spelling and is what goes on the wire, into a row, or into a diagnostic.
116/// It reads as a [`Path`] (an OS path is made from one at the edge, where a
117/// file is actually read), but it cannot spell a separator the host's way:
118/// `Display`, serde and the stored bytes are always `/`.
119#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
120#[serde(transparent)]
121pub struct RelPath(String);
122
123impl RelPath {
124    /// Whatever the host spells a path with, a workspace path is `/`.
125    pub fn new(path: &Path) -> Self {
126        Self(spell(path.display().to_string()))
127    }
128
129    pub fn as_str(&self) -> &str {
130        &self.0
131    }
132
133    /// The path as this machine spells it, for an actual file call.
134    pub fn as_path(&self) -> &Path {
135        Path::new(&self.0)
136    }
137}
138
139/// `/` on every platform; on Unix this is the text unchanged.
140fn spell(text: String) -> String {
141    if std::path::MAIN_SEPARATOR == '/' {
142        text
143    } else {
144        text.replace(std::path::MAIN_SEPARATOR, "/")
145    }
146}
147
148impl Deref for RelPath {
149    type Target = Path;
150    fn deref(&self) -> &Path {
151        Path::new(&self.0)
152    }
153}
154
155impl AsRef<Path> for RelPath {
156    fn as_ref(&self) -> &Path {
157        self
158    }
159}
160
161impl AsRef<str> for RelPath {
162    fn as_ref(&self) -> &str {
163        &self.0
164    }
165}
166
167impl Borrow<Path> for RelPath {
168    fn borrow(&self) -> &Path {
169        self
170    }
171}
172
173impl PartialEq<Path> for RelPath {
174    fn eq(&self, other: &Path) -> bool {
175        self.as_path() == other
176    }
177}
178
179impl PartialEq<&Path> for RelPath {
180    fn eq(&self, other: &&Path) -> bool {
181        self.as_path() == *other
182    }
183}
184
185impl PartialEq<RelPath> for Path {
186    fn eq(&self, other: &RelPath) -> bool {
187        self == other.as_path()
188    }
189}
190
191impl PartialEq<PathBuf> for RelPath {
192    fn eq(&self, other: &PathBuf) -> bool {
193        self.as_path() == other.as_path()
194    }
195}
196
197impl PartialEq<RelPath> for PathBuf {
198    fn eq(&self, other: &RelPath) -> bool {
199        self.as_path() == other.as_path()
200    }
201}
202
203impl PartialEq<str> for RelPath {
204    fn eq(&self, other: &str) -> bool {
205        self.0 == other
206    }
207}
208
209impl PartialEq<&str> for RelPath {
210    fn eq(&self, other: &&str) -> bool {
211        self.0 == *other
212    }
213}
214
215impl From<&RelPath> for RelPath {
216    fn from(path: &RelPath) -> Self {
217        path.clone()
218    }
219}
220
221impl From<&str> for RelPath {
222    fn from(path: &str) -> Self {
223        Self(spell(path.to_owned()))
224    }
225}
226
227impl From<String> for RelPath {
228    fn from(path: String) -> Self {
229        Self(spell(path))
230    }
231}
232
233impl From<&Path> for RelPath {
234    fn from(path: &Path) -> Self {
235        Self::new(path)
236    }
237}
238
239impl From<PathBuf> for RelPath {
240    fn from(path: PathBuf) -> Self {
241        Self::new(&path)
242    }
243}
244
245impl From<&PathBuf> for RelPath {
246    fn from(path: &PathBuf) -> Self {
247        Self::new(path)
248    }
249}
250
251impl From<&RelPath> for PathBuf {
252    fn from(path: &RelPath) -> Self {
253        PathBuf::from(&path.0)
254    }
255}
256
257impl fmt::Display for RelPath {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.write_str(&self.0)
260    }
261}
262
263impl fmt::Debug for RelPath {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        write!(f, "{:?}", self.0)
266    }
267}
268
269/// Where a path starts: the part before its segments that says what they
270/// are relative to.
271#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
272#[serde(rename_all = "snake_case")]
273pub enum PathHead {
274    /// The root of the package the file belongs to: Rust's `crate::`.
275    Package,
276    /// The file's own module or directory: `self::`, `./`.
277    Here,
278    /// `n` levels up from the file's module or directory: `super::super::`,
279    /// `../../`.
280    Up(u8),
281    /// The enclosing type, not a module: Rust's `Self::`. Never a module path.
282    SelfType,
283    /// A named package or an in-scope name, which only the layout can tell
284    /// apart: `serde::`, `react`, `@scope/pkg`, a child module, an imported
285    /// name. The name is the first segment.
286    Named,
287    /// The file system root: `/x/y`.
288    Root,
289}
290
291/// How a language spells paths: the separator between segments and the
292/// words it uses for a head. A grammar declares one; it parses import text
293/// into [`ModulePath`]s and spells them back.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
295#[serde(rename_all = "snake_case")]
296pub enum PathSyntax {
297    /// `crate::a::b`, `self::a`, `super::super::a`, `Self::A`, `serde::X`.
298    Scoped,
299    /// `./a/b`, `../../a`, `/a/b`, `react/x`, `@scope/pkg`.
300    Posix,
301}
302
303impl PathSyntax {
304    pub const fn separator(self) -> &'static str {
305        match self {
306            Self::Scoped => "::",
307            Self::Posix => "/",
308        }
309    }
310
311    /// Read a path as written. Lossless for what a grammar hands over:
312    /// `spell(parse(text)) == text` for every well-formed path.
313    pub fn parse(self, text: &str) -> ModulePath {
314        let mut segments: Vec<&str> = text.split(self.separator()).collect();
315        let head = match self {
316            Self::Scoped => match segments.first().copied() {
317                Some("crate") => {
318                    segments.remove(0);
319                    PathHead::Package
320                }
321                Some("self") => {
322                    segments.remove(0);
323                    PathHead::Here
324                }
325                Some("Self") => {
326                    segments.remove(0);
327                    PathHead::SelfType
328                }
329                Some("super") => {
330                    let ups = segments.iter().take_while(|s| **s == "super").count();
331                    segments.drain(..ups);
332                    PathHead::Up(ups as u8)
333                }
334                _ => PathHead::Named,
335            },
336            Self::Posix => match segments.first().copied() {
337                Some("") if segments.len() > 1 => {
338                    segments.remove(0);
339                    PathHead::Root
340                }
341                Some(".") => {
342                    segments.remove(0);
343                    PathHead::Here
344                }
345                Some("..") => {
346                    let ups = segments.iter().take_while(|s| **s == "..").count();
347                    segments.drain(..ups);
348                    PathHead::Up(ups as u8)
349                }
350                // `@scope/pkg` is one package name.
351                Some(scope) if scope.starts_with('@') && segments.len() > 1 => {
352                    let package = format!("{scope}/{}", segments[1]);
353                    segments.drain(..2);
354                    segments.insert(0, "");
355                    let mut path = ModulePath {
356                        syntax: self,
357                        head: PathHead::Named,
358                        segments: segments.iter().map(|s| Name::new(*s)).collect(),
359                    };
360                    path.segments[0] = Name::new(package);
361                    return path;
362                }
363                _ => PathHead::Named,
364            },
365        };
366        ModulePath {
367            syntax: self,
368            head,
369            segments: segments
370                .into_iter()
371                .filter(|s| !s.is_empty())
372                .map(Name::new)
373                .collect(),
374        }
375    }
376
377    /// The path as this syntax writes it.
378    pub fn spell(self, path: &ModulePath) -> String {
379        let sep = self.separator();
380        let segments = path
381            .segments
382            .iter()
383            .map(Name::as_str)
384            .collect::<Vec<_>>()
385            .join(sep);
386        match (self, &path.head) {
387            (Self::Scoped, PathHead::Package) => Self::joined("crate", sep, &segments),
388            (Self::Scoped, PathHead::Here) => Self::joined("self", sep, &segments),
389            (Self::Scoped, PathHead::SelfType) => Self::joined("Self", sep, &segments),
390            (Self::Scoped, PathHead::Up(n)) => {
391                let ups = vec!["super"; *n as usize].join(sep);
392                Self::joined(&ups, sep, &segments)
393            }
394            (Self::Scoped, PathHead::Named | PathHead::Root) => segments,
395            (Self::Posix, PathHead::Here) => Self::joined(".", sep, &segments),
396            (Self::Posix, PathHead::Up(n)) => {
397                let ups = vec![".."; *n as usize].join(sep);
398                Self::joined(&ups, sep, &segments)
399            }
400            (Self::Posix, PathHead::Root) => format!("/{segments}"),
401            (Self::Posix, PathHead::Package | PathHead::SelfType | PathHead::Named) => segments,
402        }
403    }
404
405    fn joined(head: &str, sep: &str, segments: &str) -> String {
406        if segments.is_empty() {
407            head.to_owned()
408        } else {
409            format!("{head}{sep}{segments}")
410        }
411    }
412}
413
414/// A path as spelled in source: its head and its segments, with the syntax
415/// that spells it. Serialises as the text, so the wire is what the user
416/// wrote.
417#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
418pub struct ModulePath {
419    syntax: PathSyntax,
420    pub head: PathHead,
421    pub segments: Vec<Name>,
422}
423
424impl ModulePath {
425    pub fn new(
426        syntax: PathSyntax,
427        head: PathHead,
428        segments: impl IntoIterator<Item = impl Into<Name>>,
429    ) -> Self {
430        Self {
431            syntax,
432            head,
433            segments: segments.into_iter().map(Into::into).collect(),
434        }
435    }
436
437    pub fn syntax(&self) -> PathSyntax {
438        self.syntax
439    }
440
441    pub fn first(&self) -> Option<&Name> {
442        self.segments.first()
443    }
444
445    pub fn last(&self) -> Option<&Name> {
446        self.segments.last()
447    }
448
449    pub fn is_empty(&self) -> bool {
450        self.segments.is_empty()
451    }
452
453    /// The segments after `prefix`, when this path continues it: same head,
454    /// its segments first.
455    pub fn strip_prefix(&self, prefix: &ModulePath) -> Option<&[Name]> {
456        (self.head == prefix.head)
457            .then(|| self.segments.strip_prefix(prefix.segments.as_slice()))
458            .flatten()
459    }
460
461    /// Whether this path continues `prefix` by at least one segment.
462    pub fn continues(&self, prefix: &ModulePath) -> bool {
463        self.strip_prefix(prefix)
464            .is_some_and(|rest| !rest.is_empty())
465    }
466
467    /// The same path with `segments` in place of its own.
468    pub fn with_segments(&self, segments: impl IntoIterator<Item = impl Into<Name>>) -> Self {
469        Self::new(self.syntax, self.head.clone(), segments)
470    }
471
472    /// The path up to and including segment `index`: what a token in the
473    /// middle of a path names.
474    pub fn prefix(&self, index: usize) -> Self {
475        self.with_segments(self.segments[..=index].iter().cloned())
476    }
477
478    /// Which segment is spelled at byte `offset` from the path's start, as
479    /// its syntax writes it; `None` on a separator or the head.
480    pub fn segment_at(&self, offset: usize) -> Option<usize> {
481        let sep = self.syntax.separator().len();
482        let head = self
483            .syntax
484            .spell(&self.with_segments(std::iter::empty::<Name>()));
485        let mut at = match (&self.head, head.len()) {
486            (PathHead::Root, n) => n,
487            (_, 0) => 0,
488            (_, n) => n + sep,
489        };
490        for (i, segment) in self.segments.iter().enumerate() {
491            if (at..at + segment.len()).contains(&offset) {
492                return Some(i);
493            }
494            at += segment.len() + sep;
495        }
496        None
497    }
498
499    /// `segments` alone, spelled in this path's syntax: the tail after a
500    /// group's prefix.
501    pub fn spell_segments(&self, segments: &[Name]) -> String {
502        segments
503            .iter()
504            .map(Name::as_str)
505            .collect::<Vec<_>>()
506            .join(self.syntax.separator())
507    }
508}
509
510impl fmt::Display for ModulePath {
511    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512        f.write_str(&self.syntax.spell(self))
513    }
514}
515
516impl fmt::Debug for ModulePath {
517    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518        write!(f, "ModulePath({:?})", self.to_string())
519    }
520}
521
522impl Serialize for ModulePath {
523    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
524        serializer.serialize_str(&self.to_string())
525    }
526}
527
528/// A path read back from text carries no syntax; `::` anywhere means
529/// scoped, anything else Posix.
530impl<'de> Deserialize<'de> for ModulePath {
531    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
532        let text = String::deserialize(deserializer)?;
533        let syntax = if text.contains("::") {
534            PathSyntax::Scoped
535        } else {
536            PathSyntax::Posix
537        };
538        Ok(syntax.parse(&text))
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    fn round_trip(syntax: PathSyntax, text: &str) -> ModulePath {
547        let path = syntax.parse(text);
548        assert_eq!(syntax.spell(&path), text, "{path:?}");
549        path
550    }
551
552    #[test]
553    fn scoped_paths_parse_and_spell_losslessly() {
554        assert_eq!(
555            round_trip(PathSyntax::Scoped, "crate::a::b").head,
556            PathHead::Package
557        );
558        assert_eq!(
559            round_trip(PathSyntax::Scoped, "self::a").head,
560            PathHead::Here
561        );
562        assert_eq!(
563            round_trip(PathSyntax::Scoped, "super::super::x").head,
564            PathHead::Up(2)
565        );
566        assert_eq!(round_trip(PathSyntax::Scoped, "super").segments.len(), 0);
567        assert_eq!(
568            round_trip(PathSyntax::Scoped, "Self::X").head,
569            PathHead::SelfType
570        );
571        let named = round_trip(PathSyntax::Scoped, "serde::Serialize");
572        assert_eq!(named.head, PathHead::Named);
573        assert_eq!(named.first().map(Name::as_str), Some("serde"));
574        assert_eq!(round_trip(PathSyntax::Scoped, "Foo").segments.len(), 1);
575    }
576
577    /// The one platform that spells its separator differently must not reach
578    /// a workspace path: built by `join`, it is still shown with `/`.
579    #[test]
580    fn a_workspace_path_is_spelled_with_slashes() {
581        let native = PathBuf::from("a").join("b.rs");
582        assert_eq!(RelPath::new(&native).as_str(), "a/b.rs");
583        assert_eq!(RelPath::from(&native).to_string(), "a/b.rs");
584    }
585
586    #[test]
587    fn posix_paths_parse_and_spell_losslessly() {
588        assert_eq!(round_trip(PathSyntax::Posix, "./x.js").head, PathHead::Here);
589        assert_eq!(round_trip(PathSyntax::Posix, ".").segments.len(), 0);
590        assert_eq!(
591            round_trip(PathSyntax::Posix, "../../a/b").head,
592            PathHead::Up(2)
593        );
594        assert_eq!(round_trip(PathSyntax::Posix, "../..").head, PathHead::Up(2));
595        assert_eq!(round_trip(PathSyntax::Posix, "/etc/x").head, PathHead::Root);
596        let scoped = round_trip(PathSyntax::Posix, "@scope/pkg/sub");
597        assert_eq!(scoped.first().map(Name::as_str), Some("@scope/pkg"));
598        assert_eq!(scoped.segments.len(), 2);
599        assert_eq!(
600            round_trip(PathSyntax::Posix, "react/jsx-runtime").head,
601            PathHead::Named
602        );
603    }
604
605    #[test]
606    fn prefixes_compare_by_head_and_segments() {
607        let group = PathSyntax::Scoped.parse("crate::util");
608        let entry = PathSyntax::Scoped.parse("crate::util::parse::X");
609        assert_eq!(
610            entry.strip_prefix(&group).map(|r| entry.spell_segments(r)),
611            Some("parse::X".to_owned())
612        );
613        assert!(!PathSyntax::Scoped.parse("crate::util").continues(&group));
614        assert!(
615            PathSyntax::Scoped
616                .parse("self::util::x")
617                .strip_prefix(&group)
618                .is_none()
619        );
620    }
621
622    #[test]
623    fn segments_are_found_by_offset() {
624        let path = PathSyntax::Scoped.parse("crate::commands::batch::BatchCmd");
625        assert_eq!(path.segment_at(0), None, "the head");
626        assert_eq!(path.segment_at(7), Some(0));
627        assert_eq!(path.segment_at(17), Some(1));
628        assert_eq!(path.segment_at(24), Some(2));
629        assert_eq!(path.segment_at(15), None, "a separator");
630        assert_eq!(path.prefix(1).to_string(), "crate::commands::batch");
631        let bare = PathSyntax::Scoped.parse("a::b");
632        assert_eq!(bare.segment_at(0), Some(0));
633        assert_eq!(bare.segment_at(3), Some(1));
634        let posix = PathSyntax::Posix.parse("../x/y.ts");
635        assert_eq!(posix.segment_at(3), Some(0));
636        assert_eq!(posix.segment_at(5), Some(1));
637        assert_eq!(PathSyntax::Posix.parse("/etc/x").segment_at(1), Some(0));
638    }
639
640    #[test]
641    fn serialises_as_text() {
642        let path = PathSyntax::Scoped.parse("crate::a");
643        assert_eq!(serde_json::to_string(&path).unwrap(), "\"crate::a\"");
644        let back: ModulePath = serde_json::from_str("\"../x/y\"").unwrap();
645        assert_eq!(back, PathSyntax::Posix.parse("../x/y"));
646    }
647}