miden_assembly_syntax/ast/path/
path.rs1use alloc::{
2 borrow::{Borrow, Cow, ToOwned},
3 string::ToString,
4};
5use core::fmt;
6
7use super::{Iter, Join, PathBuf, PathComponent, PathError, StartsWith};
8use crate::ast::Ident;
9
10#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
12#[repr(transparent)]
13pub struct Path {
14 inner: str,
16}
17
18impl fmt::Debug for Path {
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 fmt::Debug::fmt(&self.inner, f)
21 }
22}
23
24#[cfg(feature = "serde")]
25impl serde::Serialize for Path {
26 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
27 where
28 S: serde::Serializer,
29 {
30 serializer.serialize_str(&self.inner)
31 }
32}
33
34#[cfg(feature = "serde")]
35impl<'de> serde::Deserialize<'de> for &'de Path {
36 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
37 where
38 D: serde::Deserializer<'de>,
39 {
40 use serde::de::Visitor;
41
42 struct PathVisitor;
43
44 impl<'de> Visitor<'de> for PathVisitor {
45 type Value = &'de Path;
46
47 fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
48 formatter.write_str("a borrowed Path")
49 }
50
51 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
52 where
53 E: serde::de::Error,
54 {
55 Path::validate(v).map_err(serde::de::Error::custom)
56 }
57 }
58
59 deserializer.deserialize_any(PathVisitor)
60 }
61}
62
63impl ToOwned for Path {
64 type Owned = PathBuf;
65 #[inline]
66 fn to_owned(&self) -> PathBuf {
67 self.to_path_buf()
68 }
69 #[inline]
70 fn clone_into(&self, target: &mut Self::Owned) {
71 self.inner.clone_into(&mut target.inner)
72 }
73}
74
75impl Borrow<Path> for PathBuf {
76 fn borrow(&self) -> &Path {
77 Path::new(self)
78 }
79}
80
81impl AsRef<str> for Path {
82 #[inline]
83 fn as_ref(&self) -> &str {
84 &self.inner
85 }
86}
87
88impl AsRef<Path> for str {
89 #[inline(always)]
90 fn as_ref(&self) -> &Path {
91 unsafe { &*(self as *const str as *const Path) }
92 }
93}
94
95impl AsRef<Path> for Ident {
96 #[inline(always)]
97 fn as_ref(&self) -> &Path {
98 self.as_str().as_ref()
99 }
100}
101
102impl AsRef<Path> for crate::ast::ProcedureName {
103 #[inline(always)]
104 fn as_ref(&self) -> &Path {
105 let ident: &Ident = self.as_ref();
106 ident.as_str().as_ref()
107 }
108}
109
110impl AsRef<Path> for crate::ast::QualifiedProcedureName {
111 #[inline(always)]
112 fn as_ref(&self) -> &Path {
113 self.as_path()
114 }
115}
116
117impl AsRef<Path> for Path {
118 #[inline(always)]
119 fn as_ref(&self) -> &Path {
120 self
121 }
122}
123
124impl From<&Path> for alloc::sync::Arc<Path> {
125 fn from(path: &Path) -> Self {
126 path.to_path_buf().into()
127 }
128}
129
130impl Path {
132 pub const MAX_COMPONENT_LENGTH: usize = u8::MAX as usize;
134
135 pub const EMPTY: &Path = unsafe { &*("" as *const str as *const Path) };
137
138 pub const KERNEL_PATH: &str = "$kernel";
140 pub const ABSOLUTE_KERNEL_PATH: &str = "::$kernel";
141 pub const KERNEL: &Path =
142 unsafe { &*(Self::ABSOLUTE_KERNEL_PATH as *const str as *const Path) };
143
144 pub const EXEC_PATH: &str = "$exec";
146 pub const ABSOLUTE_EXEC_PATH: &str = "::$exec";
147 pub const EXEC: &Path = unsafe { &*(Self::ABSOLUTE_EXEC_PATH as *const str as *const Path) };
148
149 pub fn new<S: AsRef<str> + ?Sized>(path: &S) -> &Path {
150 unsafe { &*(path.as_ref() as *const str as *const Path) }
152 }
153
154 pub fn from_mut(path: &mut str) -> &mut Path {
155 unsafe { &mut *(path as *mut str as *mut Path) }
157 }
158
159 pub fn validate(path: &str) -> Result<&Path, PathError> {
161 match path {
162 "" | "\"\"" => return Err(PathError::Empty),
163 "::" => return Err(PathError::EmptyComponent),
164 _ => (),
165 }
166
167 for result in Iter::new(path) {
168 result?;
169 }
170
171 Ok(Path::new(path))
172 }
173
174 pub const fn kernel_path() -> &'static Path {
176 Path::KERNEL
177 }
178
179 pub const fn exec_path() -> &'static Path {
181 Path::EXEC
182 }
183
184 #[inline]
185 pub const fn as_str(&self) -> &str {
186 &self.inner
187 }
188
189 #[inline]
190 pub fn as_mut_str(&mut self) -> &mut str {
191 &mut self.inner
192 }
193
194 pub fn as_ident(&self) -> Option<Ident> {
199 let mut components = self.components().filter_map(|c| c.ok());
200 match components.next()? {
201 component @ PathComponent::Normal(_) => {
202 if components.next().is_none() {
203 component.to_ident()
204 } else {
205 None
206 }
207 },
208 PathComponent::Root => None,
209 }
210 }
211
212 pub fn to_path_buf(&self) -> PathBuf {
214 PathBuf { inner: self.inner.to_string() }
215 }
216
217 pub fn from_ident(ident: &Ident) -> Cow<'_, Path> {
220 let ident = ident.as_str();
221 if Ident::requires_quoting(ident) {
222 let mut buf = PathBuf::with_capacity(ident.len() + 2);
223 buf.push_component(ident);
224 Cow::Owned(buf)
225 } else {
226 Cow::Borrowed(Path::new(ident))
227 }
228 }
229}
230
231impl Path {
233 pub fn is_empty(&self) -> bool {
235 matches!(&self.inner, "" | "::" | "\"\"")
236 }
237
238 pub fn len(&self) -> usize {
240 self.components().count()
241 }
242
243 pub fn char_len(&self) -> usize {
245 self.inner.chars().count()
246 }
247
248 #[inline]
250 pub fn byte_len(&self) -> usize {
251 self.inner.len()
252 }
253
254 pub fn is_absolute(&self) -> bool {
256 matches!(self.components().next(), Some(Ok(PathComponent::Root)))
257 }
258
259 pub fn to_absolute(&self) -> Cow<'_, Path> {
263 if self.is_absolute() {
264 Cow::Borrowed(self)
265 } else {
266 let mut buf = PathBuf::with_capacity(self.byte_len() + 2);
267 buf.push_component("::");
268 buf.extend_with_components(self.components()).expect("invalid path");
269 Cow::Owned(buf)
270 }
271 }
272
273 pub fn to_relative(&self) -> &Path {
275 match self.inner.strip_prefix("::") {
276 Some(rest) => Path::new(rest),
277 None => self,
278 }
279 }
280
281 pub fn parent(&self) -> Option<&Path> {
287 let mut components = self.components();
288 match components.next_back()?.ok()? {
289 PathComponent::Root => None,
290 _ => Some(components.as_path()),
291 }
292 }
293
294 pub fn components(&self) -> Iter<'_> {
296 Iter::new(&self.inner)
297 }
298
299 pub fn first(&self) -> Option<&str> {
303 self.split_first().map(|(first, _)| first)
304 }
305
306 pub fn last(&self) -> Option<&str> {
310 self.split_last().map(|(last, _)| last)
311 }
312
313 pub fn split_first(&self) -> Option<(&str, &Path)> {
318 let mut components = self.components();
319 match components.next()?.ok()? {
320 PathComponent::Root => {
321 let first = components.next().and_then(|c| c.ok()).map(|c| c.as_str())?;
322 Some((first, components.as_path()))
323 },
324 first @ PathComponent::Normal(_) => Some((first.as_str(), components.as_path())),
325 }
326 }
327
328 pub fn split_last(&self) -> Option<(&str, &Path)> {
333 let mut components = self.components();
334 match components.next_back()?.ok()? {
335 PathComponent::Root => None,
336 last @ PathComponent::Normal(_) => Some((last.as_str(), components.as_path())),
337 }
338 }
339
340 pub fn is_kernel_path(&self) -> bool {
342 match self.inner.strip_prefix("::") {
343 Some(Self::KERNEL_PATH) => true,
344 Some(_) => false,
345 None => &self.inner == Self::KERNEL_PATH,
346 }
347 }
348
349 pub fn is_in_kernel(&self) -> bool {
351 if self.is_kernel_path() {
352 return true;
353 }
354
355 match self.split_last() {
356 Some((_, prefix)) => prefix.is_kernel_path(),
357 None => false,
358 }
359 }
360
361 pub fn is_exec_path(&self) -> bool {
363 match self.inner.strip_prefix("::") {
364 Some(Self::EXEC_PATH) => true,
365 Some(_) => false,
366 None => &self.inner == Self::EXEC_PATH,
367 }
368 }
369
370 pub fn is_in_exec(&self) -> bool {
372 if self.is_exec_path() {
373 return true;
374 }
375
376 match self.split_last() {
377 Some((_, prefix)) => prefix.is_exec_path(),
378 None => false,
379 }
380 }
381
382 #[inline]
390 pub fn starts_with<Prefix>(&self, prefix: &Prefix) -> bool
391 where
392 Prefix: ?Sized,
393 Self: StartsWith<Prefix>,
394 {
395 <Self as StartsWith<Prefix>>::starts_with(self, prefix)
396 }
397
398 #[inline]
406 pub fn starts_with_exactly<Prefix>(&self, prefix: &Prefix) -> bool
407 where
408 Prefix: ?Sized,
409 Self: StartsWith<Prefix>,
410 {
411 <Self as StartsWith<Prefix>>::starts_with_exactly(self, prefix)
412 }
413
414 pub fn strip_prefix<'a>(&'a self, prefix: &Self) -> Option<&'a Self> {
420 let mut components = self.components();
421 for prefix_component in prefix.components() {
422 let prefix_component = prefix_component.expect("invalid prefix path");
431 match (components.next(), prefix_component) {
432 (Some(Ok(PathComponent::Root)), PathComponent::Root) => (),
433 (Some(Ok(c @ PathComponent::Normal(_))), pc @ PathComponent::Normal(_)) => {
434 if c.as_str() != pc.as_str() {
435 return None;
436 }
437 },
438 (Some(Ok(_) | Err(_)) | None, _) => return None,
439 }
440 }
441 Some(components.as_path())
442 }
443
444 #[inline]
457 pub fn join<P>(&self, other: &P) -> PathBuf
458 where
459 P: ?Sized,
460 Path: Join<P>,
461 {
462 <Path as Join<P>>::join(self, other)
463 }
464
465 pub fn canonicalize(&self) -> Result<PathBuf, PathError> {
474 let mut buf = PathBuf::with_capacity(self.byte_len());
475 buf.extend_with_components(self.components())?;
476 Ok(buf)
477 }
478}
479
480impl StartsWith<str> for Path {
481 fn starts_with(&self, prefix: &str) -> bool {
482 let this = self.to_relative();
483 <Path as StartsWith<str>>::starts_with_exactly(this, prefix)
484 }
485
486 #[inline]
487 fn starts_with_exactly(&self, prefix: &str) -> bool {
488 match prefix {
489 "" => true,
490 "::" => self.is_absolute(),
491 prefix => {
492 let mut components = self.components();
493 let prefix = if let Some(prefix) = prefix.strip_prefix("::") {
494 let is_absolute =
495 components.next().is_some_and(|c| matches!(c, Ok(PathComponent::Root)));
496 if !is_absolute {
497 return false;
498 }
499 prefix
500 } else {
501 prefix
502 };
503 components.next().is_some_and(
504 |c| matches!(c, Ok(c @ PathComponent::Normal(_)) if c.as_str() == prefix),
505 )
506 },
507 }
508 }
509}
510
511impl StartsWith<Path> for Path {
512 fn starts_with(&self, prefix: &Path) -> bool {
513 let this = self.to_relative();
514 let prefix = prefix.to_relative();
515 <Path as StartsWith<Path>>::starts_with_exactly(this, prefix)
516 }
517
518 #[inline]
519 fn starts_with_exactly(&self, prefix: &Path) -> bool {
520 let mut components = self.components();
521 for prefix_component in prefix.components() {
522 let prefix_component = prefix_component.expect("invalid prefix path");
531 match (components.next(), prefix_component) {
532 (Some(Ok(PathComponent::Root)), PathComponent::Root) => continue,
533 (Some(Ok(c @ PathComponent::Normal(_))), pc @ PathComponent::Normal(_)) => {
534 if c.as_str() != pc.as_str() {
535 return false;
536 }
537 },
538 (Some(Ok(_) | Err(_)) | None, _) => return false,
539 }
540 }
541 true
542 }
543}
544
545impl PartialEq<str> for Path {
546 fn eq(&self, other: &str) -> bool {
547 &self.inner == other
548 }
549}
550
551impl PartialEq<PathBuf> for Path {
552 fn eq(&self, other: &PathBuf) -> bool {
553 &self.inner == other.inner.as_str()
554 }
555}
556
557impl PartialEq<&PathBuf> for Path {
558 fn eq(&self, other: &&PathBuf) -> bool {
559 &self.inner == other.inner.as_str()
560 }
561}
562
563impl PartialEq<Path> for PathBuf {
564 fn eq(&self, other: &Path) -> bool {
565 self.inner.as_str() == &other.inner
566 }
567}
568
569impl PartialEq<&Path> for Path {
570 fn eq(&self, other: &&Path) -> bool {
571 self.inner == other.inner
572 }
573}
574
575impl PartialEq<alloc::boxed::Box<Path>> for Path {
576 fn eq(&self, other: &alloc::boxed::Box<Path>) -> bool {
577 self.inner == other.inner
578 }
579}
580
581impl PartialEq<alloc::rc::Rc<Path>> for Path {
582 fn eq(&self, other: &alloc::rc::Rc<Path>) -> bool {
583 self.inner == other.inner
584 }
585}
586
587impl PartialEq<alloc::sync::Arc<Path>> for Path {
588 fn eq(&self, other: &alloc::sync::Arc<Path>) -> bool {
589 self.inner == other.inner
590 }
591}
592
593impl PartialEq<alloc::borrow::Cow<'_, Path>> for Path {
594 fn eq(&self, other: &alloc::borrow::Cow<'_, Path>) -> bool {
595 self.inner == other.as_ref().inner
596 }
597}
598
599impl fmt::Display for Path {
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601 f.write_str(&self.inner)
602 }
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608
609 #[test]
610 fn test_canonicalize_path_identity() -> Result<(), PathError> {
611 let path = Path::new("foo::bar");
612 let canonicalized = path.canonicalize()?;
613
614 assert_eq!(canonicalized.as_path(), path);
615 Ok(())
616 }
617
618 #[test]
619 fn test_canonicalize_path_kernel_is_absolute() -> Result<(), PathError> {
620 let path = Path::new("$kernel::bar");
621 let canonicalized = path.canonicalize()?;
622
623 let expected = Path::new("::$kernel::bar");
624 assert_eq!(canonicalized.as_path(), expected);
625 Ok(())
626 }
627
628 #[test]
629 fn test_canonicalize_path_exec_is_absolute() -> Result<(), PathError> {
630 let path = Path::new("$exec::$main");
631 let canonicalized = path.canonicalize()?;
632
633 let expected = Path::new("::$exec::$main");
634 assert_eq!(canonicalized.as_path(), expected);
635 Ok(())
636 }
637
638 #[test]
639 fn test_canonicalize_path_remove_unnecessary_quoting() -> Result<(), PathError> {
640 let path = Path::new("foo::\"bar\"");
641 let canonicalized = path.canonicalize()?;
642
643 let expected = Path::new("foo::bar");
644 assert_eq!(canonicalized.as_path(), expected);
645 Ok(())
646 }
647
648 #[test]
649 fn test_canonicalize_path_preserve_necessary_quoting() -> Result<(), PathError> {
650 let path = Path::new("foo::\"bar::baz\"");
651 let canonicalized = path.canonicalize()?;
652
653 assert_eq!(canonicalized.as_path(), path);
654 Ok(())
655 }
656
657 #[test]
658 fn test_canonicalize_path_add_required_quoting_to_components_without_delimiter()
659 -> Result<(), PathError> {
660 let path = Path::new("foo::$bar");
661 let canonicalized = path.canonicalize()?;
662
663 let expected = Path::new("foo::\"$bar\"");
664 assert_eq!(canonicalized.as_path(), expected);
665 Ok(())
666 }
667}