Skip to main content

miden_assembly_syntax/ast/path/
path.rs

1use 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/// A borrowed reference to a subset of a path, e.g. another [Path] or a [PathBuf]
11#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
12#[repr(transparent)]
13pub struct Path {
14    /// A view into the selected components of the path, i.e. the parts delimited by `::`
15    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
130/// Conversions
131impl Path {
132    /// Path components  must be 255 bytes or less
133    pub const MAX_COMPONENT_LENGTH: usize = u8::MAX as usize;
134
135    /// An empty path for use as a default value, placeholder, comparisons, etc.
136    pub const EMPTY: &Path = unsafe { &*("" as *const str as *const Path) };
137
138    /// Base kernel path.
139    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    /// Path for an executable module.
145    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        // SAFETY: The representation of Path is equivalent to str
151        unsafe { &*(path.as_ref() as *const str as *const Path) }
152    }
153
154    pub fn from_mut(path: &mut str) -> &mut Path {
155        // SAFETY: The representation of Path is equivalent to str
156        unsafe { &mut *(path as *mut str as *mut Path) }
157    }
158
159    /// Verify that `path` meets all the requirements for a valid [Path]
160    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    /// Get a [Path] corresponding to [Self::KERNEL_PATH]
175    pub const fn kernel_path() -> &'static Path {
176        Path::KERNEL
177    }
178
179    /// Get a [Path] corresponding to [Self::EXEC_PATH]
180    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    /// Get an [Ident] that is equivalent to this [Path], so long as the path has only a single
195    /// component.
196    ///
197    /// Returns `None` if the path cannot be losslessly represented as a single component.
198    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    /// Convert this [Path] to an owned [PathBuf]
213    pub fn to_path_buf(&self) -> PathBuf {
214        PathBuf { inner: self.inner.to_string() }
215    }
216
217    /// Convert an [Ident] to an equivalent [Path] or [PathBuf], depending on whether the identifier
218    /// would require quoting as a path.
219    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
231/// Accesssors
232impl Path {
233    /// Returns true if this path is empty (i.e. has no components)
234    pub fn is_empty(&self) -> bool {
235        matches!(&self.inner, "" | "::" | "\"\"")
236    }
237
238    /// Returns the number of components in the path
239    pub fn len(&self) -> usize {
240        self.components().count()
241    }
242
243    /// Return the size of the path in [char]s when displayed as a string
244    pub fn char_len(&self) -> usize {
245        self.inner.chars().count()
246    }
247
248    /// Return the size of the path in bytes when displayed as a string
249    #[inline]
250    pub fn byte_len(&self) -> usize {
251        self.inner.len()
252    }
253
254    /// Returns true if this path is an absolute path
255    pub fn is_absolute(&self) -> bool {
256        matches!(self.components().next(), Some(Ok(PathComponent::Root)))
257    }
258
259    /// Make this path absolute, if not already
260    ///
261    /// NOTE: This does not _resolve_ the path, it simply ensures the path has the root prefix
262    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    /// Strip the root prefix from this path, if it has one.
274    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    /// Returns the [Path] without its final component, if there is one.
282    ///
283    /// This means it may return an empty [Path] for relative paths with a single component.
284    ///
285    /// Returns `None` if the path terminates with the root prefix, or if it is empty.
286    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    /// Returns an iterator over all components of the path.
295    pub fn components(&self) -> Iter<'_> {
296        Iter::new(&self.inner)
297    }
298
299    /// Get the first non-root component of this path as a `str`
300    ///
301    /// Returns `None` if the path is empty, or consists only of the root prefix.
302    pub fn first(&self) -> Option<&str> {
303        self.split_first().map(|(first, _)| first)
304    }
305
306    /// Get the first non-root component of this path as a `str`
307    ///
308    /// Returns `None` if the path is empty, or consists only of the root prefix.
309    pub fn last(&self) -> Option<&str> {
310        self.split_last().map(|(last, _)| last)
311    }
312
313    /// Splits this path on the first non-root component, returning it and a new [Path] of the
314    /// remaining components.
315    ///
316    /// Returns `None` if there are no components to split
317    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    /// Splits this path on the last component, returning it and a new [Path] of the remaining
329    /// components.
330    ///
331    /// Returns `None` if there are no components to split
332    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    /// Returns true if this path is for the root kernel module.
341    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    /// Returns true if this path is for the root kernel module or an item in it
350    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    /// Returns true if this path is for an executable module.
362    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    /// Returns true if this path is for the executable module or an item in it
371    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    /// Returns true if the current path, sans root component, starts with `prefix`
383    ///
384    /// The matching semantics of `Prefix` depend on the implementation of [`StartsWith<Prefix>`],
385    /// in particular, if `Prefix` is `str`, then the prefix is matched against the first non-root
386    /// component of `self`, regardless of whether the string contains path delimiters (i.e. `::`).
387    ///
388    /// See the [StartsWith] trait for more details.
389    #[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    /// Returns true if the current path, including root component, starts with `prefix`
399    ///
400    /// The matching semantics of `Prefix` depend on the implementation of [`StartsWith<Prefix>`],
401    /// in particular, if `Prefix` is `str`, then the prefix is matched against the first component
402    /// of `self`, regardless of whether the string contains path delimiters (i.e. `::`).
403    ///
404    /// See the [StartsWith] trait for more details.
405    #[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    /// Strips `prefix` from `self`, or returns `None` if `self` does not start with `prefix`.
415    ///
416    /// NOTE: Prefixes must be exact, i.e. if you call `path.strip_prefix(prefix)` and `path` is
417    /// relative but `prefix` is absolute, then this will return `None`. The same is true if `path`
418    /// is absolute and `prefix` is relative.
419    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            // All `Path` APIs assume that a `Path` is valid upon construction, though this is not
423            // actually enforced currently. We assert here if iterating over the components of the
424            // path finds an invalid component, because we expected the caller to have already
425            // validated the path
426            //
427            // In the future, we will likely enforce validity at construction so that iterating
428            // over its components is infallible, but that will require a breaking change to some
429            // APIs
430            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    /// Create an owned [PathBuf] with `path` adjoined to `self`.
445    ///
446    /// If `path` is absolute, it replaces the current path.
447    ///
448    /// The semantics of how `other` is joined to `self` in the resulting path depends on the
449    /// implementation of [Join] used. The implementation for [Path] and [PathBuf] joins all
450    /// components of `other` to self`; while the implementation for [prim@str], string-like values,
451    /// and identifiers/symbols joins just a single component. You must be careful to ensure that
452    /// if you are passing a string here, that you specifically want to join it as a single
453    /// component, or the resulting path may be different than you expect. It is recommended that
454    /// you use `Path::new(&string)` if you want to be explicit about treating a string-like value
455    /// as a multi-component path.
456    #[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    /// Canonicalize this path by ensuring that all components are in canonical form.
466    ///
467    /// Canonical form dictates that:
468    ///
469    /// * A component is quoted only if it requires quoting, and unquoted otherwise
470    /// * Is made absolute if relative and the first component is $kernel or $exec
471    ///
472    /// Returns `Err` if the path is invalid
473    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            // All `Path` APIs assume that a `Path` is valid upon construction, though this is not
523            // actually enforced currently. We assert here if iterating over the components of the
524            // path finds an invalid component, because we expected the caller to have already
525            // validated the path
526            //
527            // In the future, we will likely enforce validity at construction so that iterating
528            // over its components is infallible, but that will require a breaking change to some
529            // APIs
530            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}