1use std::borrow::Borrow;
11use std::fmt;
12use std::ops::Deref;
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16
17#[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 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#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
120#[serde(transparent)]
121pub struct RelPath(String);
122
123impl RelPath {
124 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 pub fn as_path(&self) -> &Path {
135 Path::new(&self.0)
136 }
137}
138
139fn 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#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
272#[serde(rename_all = "snake_case")]
273pub enum PathHead {
274 Package,
276 Here,
278 Up(u8),
281 SelfType,
283 Named,
287 Root,
289}
290
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
295#[serde(rename_all = "snake_case")]
296pub enum PathSyntax {
297 Scoped,
299 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 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 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 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#[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 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 pub fn continues(&self, prefix: &ModulePath) -> bool {
463 self.strip_prefix(prefix)
464 .is_some_and(|rest| !rest.is_empty())
465 }
466
467 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 pub fn prefix(&self, index: usize) -> Self {
475 self.with_segments(self.segments[..=index].iter().cloned())
476 }
477
478 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 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
528impl<'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 #[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}