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 = (u16::MAX as usize) - 2;
138
139 pub const EMPTY: &Path = unsafe { &*("" as *const str as *const Path) };
141
142 pub const KERNEL_PATH: &str = "$kernel";
144 pub const ABSOLUTE_KERNEL_PATH: &str = "::$kernel";
145 pub const KERNEL: &Path =
146 unsafe { &*(Self::ABSOLUTE_KERNEL_PATH as *const str as *const Path) };
147
148 pub const EXEC_PATH: &str = "$exec";
150 pub const ABSOLUTE_EXEC_PATH: &str = "::$exec";
151 pub const EXEC: &Path = unsafe { &*(Self::ABSOLUTE_EXEC_PATH as *const str as *const Path) };
152
153 pub fn new<S: AsRef<str> + ?Sized>(path: &S) -> &Path {
154 unsafe { &*(path.as_ref() as *const str as *const Path) }
156 }
157
158 pub fn from_mut(path: &mut str) -> &mut Path {
159 unsafe { &mut *(path as *mut str as *mut Path) }
161 }
162
163 pub fn validate(path: &str) -> Result<&Path, PathError> {
165 match path {
166 "" | "\"\"" => return Err(PathError::Empty),
167 "::" => return Err(PathError::EmptyComponent),
168 _ => (),
169 }
170
171 if path.len() > u16::MAX as usize {
172 return Err(PathError::TooLong { max: u16::MAX as usize });
173 }
174
175 for result in Iter::new(path) {
176 result?;
177 }
178
179 Ok(Path::new(path))
180 }
181
182 pub const fn kernel_path() -> &'static Path {
184 Path::KERNEL
185 }
186
187 pub const fn exec_path() -> &'static Path {
189 Path::EXEC
190 }
191
192 #[inline]
193 pub const fn as_str(&self) -> &str {
194 &self.inner
195 }
196
197 #[inline]
198 pub fn as_mut_str(&mut self) -> &mut str {
199 &mut self.inner
200 }
201
202 pub fn as_ident(&self) -> Option<Ident> {
207 let mut components = self.components().filter_map(|c| c.ok());
208 match components.next()? {
209 component @ PathComponent::Normal(_) => {
210 if components.next().is_none() {
211 component.to_ident()
212 } else {
213 None
214 }
215 },
216 PathComponent::Root => None,
217 }
218 }
219
220 pub fn to_path_buf(&self) -> PathBuf {
222 PathBuf { inner: self.inner.to_string() }
223 }
224
225 pub fn from_ident(ident: &Ident) -> Cow<'_, Path> {
228 let ident = ident.as_str();
229 if Ident::requires_quoting(ident) {
230 let mut buf = PathBuf::with_capacity(ident.len() + 2);
231 buf.push_component(ident);
232 Cow::Owned(buf)
233 } else {
234 Cow::Borrowed(Path::new(ident))
235 }
236 }
237}
238
239impl Path {
241 pub fn is_empty(&self) -> bool {
243 matches!(&self.inner, "" | "::" | "\"\"")
244 }
245
246 pub fn len(&self) -> usize {
248 self.components().count()
249 }
250
251 pub fn char_len(&self) -> usize {
253 self.inner.chars().count()
254 }
255
256 #[inline]
258 pub fn byte_len(&self) -> usize {
259 self.inner.len()
260 }
261
262 pub fn is_absolute(&self) -> bool {
264 matches!(self.components().next(), Some(Ok(PathComponent::Root)))
265 }
266
267 pub fn to_absolute(&self) -> Cow<'_, Path> {
271 if self.is_absolute() {
272 Cow::Borrowed(self)
273 } else {
274 let mut buf = PathBuf::with_capacity(self.byte_len() + 2);
275 buf.push_component("::");
276 buf.extend_with_components(self.components()).expect("invalid path");
277 Cow::Owned(buf)
278 }
279 }
280
281 pub fn to_relative(&self) -> &Path {
283 match self.inner.strip_prefix("::") {
284 Some(rest) => Path::new(rest),
285 None => self,
286 }
287 }
288
289 pub fn parent(&self) -> Option<&Path> {
295 let mut components = self.components();
296 match components.next_back()?.ok()? {
297 PathComponent::Root => None,
298 _ => Some(components.as_path()),
299 }
300 }
301
302 pub fn components(&self) -> Iter<'_> {
304 Iter::new(&self.inner)
305 }
306
307 pub fn first(&self) -> Option<&str> {
311 self.split_first().map(|(first, _)| first)
312 }
313
314 pub fn last(&self) -> Option<&str> {
318 self.split_last().map(|(last, _)| last)
319 }
320
321 pub fn split_first(&self) -> Option<(&str, &Path)> {
326 let mut components = self.components();
327 match components.next()?.ok()? {
328 PathComponent::Root => {
329 let first = components.next().and_then(|c| c.ok()).map(|c| c.as_str())?;
330 Some((first, components.as_path()))
331 },
332 first @ PathComponent::Normal(_) => Some((first.as_str(), components.as_path())),
333 }
334 }
335
336 pub fn split_last(&self) -> Option<(&str, &Path)> {
341 let mut components = self.components();
342 match components.next_back()?.ok()? {
343 PathComponent::Root => None,
344 last @ PathComponent::Normal(_) => Some((last.as_str(), components.as_path())),
345 }
346 }
347
348 pub fn is_kernel_path(&self) -> bool {
350 match self.inner.strip_prefix("::") {
351 Some(Self::KERNEL_PATH) => true,
352 Some(_) => false,
353 None => &self.inner == Self::KERNEL_PATH,
354 }
355 }
356
357 pub fn is_in_kernel(&self) -> bool {
359 if self.is_kernel_path() {
360 return true;
361 }
362
363 match self.split_last() {
364 Some((_, prefix)) => prefix.is_kernel_path(),
365 None => false,
366 }
367 }
368
369 pub fn is_exec_path(&self) -> bool {
371 match self.inner.strip_prefix("::") {
372 Some(Self::EXEC_PATH) => true,
373 Some(_) => false,
374 None => &self.inner == Self::EXEC_PATH,
375 }
376 }
377
378 pub fn is_in_exec(&self) -> bool {
380 if self.is_exec_path() {
381 return true;
382 }
383
384 match self.split_last() {
385 Some((_, prefix)) => prefix.is_exec_path(),
386 None => false,
387 }
388 }
389
390 #[inline]
398 pub fn starts_with<Prefix>(&self, prefix: &Prefix) -> bool
399 where
400 Prefix: ?Sized,
401 Self: StartsWith<Prefix>,
402 {
403 <Self as StartsWith<Prefix>>::starts_with(self, prefix)
404 }
405
406 #[inline]
414 pub fn starts_with_exactly<Prefix>(&self, prefix: &Prefix) -> bool
415 where
416 Prefix: ?Sized,
417 Self: StartsWith<Prefix>,
418 {
419 <Self as StartsWith<Prefix>>::starts_with_exactly(self, prefix)
420 }
421
422 pub fn strip_prefix<'a>(&'a self, prefix: &Self) -> Option<&'a Self> {
428 let mut components = self.components();
429 for prefix_component in prefix.components() {
430 let prefix_component = prefix_component.expect("invalid prefix path");
439 match (components.next(), prefix_component) {
440 (Some(Ok(PathComponent::Root)), PathComponent::Root) => (),
441 (Some(Ok(c @ PathComponent::Normal(_))), pc @ PathComponent::Normal(_)) => {
442 if c.as_str() != pc.as_str() {
443 return None;
444 }
445 },
446 (Some(Ok(_) | Err(_)) | None, _) => return None,
447 }
448 }
449 Some(components.as_path())
450 }
451
452 #[inline]
465 pub fn join<P>(&self, other: &P) -> PathBuf
466 where
467 P: ?Sized,
468 Path: Join<P>,
469 {
470 <Path as Join<P>>::join(self, other)
471 }
472
473 pub fn canonicalize(&self) -> Result<PathBuf, PathError> {
482 let mut buf = PathBuf::with_capacity(self.byte_len());
483 buf.extend_with_components(self.components())?;
484 Ok(buf)
485 }
486}
487
488impl StartsWith<str> for Path {
489 fn starts_with(&self, prefix: &str) -> bool {
490 let this = self.to_relative();
491 <Path as StartsWith<str>>::starts_with_exactly(this, prefix)
492 }
493
494 #[inline]
495 fn starts_with_exactly(&self, prefix: &str) -> bool {
496 match prefix {
497 "" => true,
498 "::" => self.is_absolute(),
499 prefix => {
500 let mut components = self.components();
501 let prefix = if let Some(prefix) = prefix.strip_prefix("::") {
502 let is_absolute =
503 components.next().is_some_and(|c| matches!(c, Ok(PathComponent::Root)));
504 if !is_absolute {
505 return false;
506 }
507 prefix
508 } else {
509 prefix
510 };
511 components.next().is_some_and(
512 |c| matches!(c, Ok(c @ PathComponent::Normal(_)) if c.as_str() == prefix),
513 )
514 },
515 }
516 }
517}
518
519impl StartsWith<Path> for Path {
520 fn starts_with(&self, prefix: &Path) -> bool {
521 let this = self.to_relative();
522 let prefix = prefix.to_relative();
523 <Path as StartsWith<Path>>::starts_with_exactly(this, prefix)
524 }
525
526 #[inline]
527 fn starts_with_exactly(&self, prefix: &Path) -> bool {
528 let mut components = self.components();
529 for prefix_component in prefix.components() {
530 let prefix_component = prefix_component.expect("invalid prefix path");
539 match (components.next(), prefix_component) {
540 (Some(Ok(PathComponent::Root)), PathComponent::Root) => {},
541 (Some(Ok(c @ PathComponent::Normal(_))), pc @ PathComponent::Normal(_)) => {
542 if c.as_str() != pc.as_str() {
543 return false;
544 }
545 },
546 (Some(Ok(_) | Err(_)) | None, _) => return false,
547 }
548 }
549 true
550 }
551}
552
553impl PartialEq<str> for Path {
554 fn eq(&self, other: &str) -> bool {
555 &self.inner == other
556 }
557}
558
559impl PartialEq<PathBuf> for Path {
560 fn eq(&self, other: &PathBuf) -> bool {
561 &self.inner == other.inner.as_str()
562 }
563}
564
565impl PartialEq<&PathBuf> for Path {
566 fn eq(&self, other: &&PathBuf) -> bool {
567 &self.inner == other.inner.as_str()
568 }
569}
570
571impl PartialEq<Path> for PathBuf {
572 fn eq(&self, other: &Path) -> bool {
573 self.inner.as_str() == &other.inner
574 }
575}
576
577impl PartialEq<&Path> for Path {
578 fn eq(&self, other: &&Path) -> bool {
579 self.inner == other.inner
580 }
581}
582
583impl PartialEq<alloc::boxed::Box<Path>> for Path {
584 fn eq(&self, other: &alloc::boxed::Box<Path>) -> bool {
585 self.inner == other.inner
586 }
587}
588
589impl PartialEq<alloc::rc::Rc<Path>> for Path {
590 fn eq(&self, other: &alloc::rc::Rc<Path>) -> bool {
591 self.inner == other.inner
592 }
593}
594
595impl PartialEq<alloc::sync::Arc<Path>> for Path {
596 fn eq(&self, other: &alloc::sync::Arc<Path>) -> bool {
597 self.inner == other.inner
598 }
599}
600
601impl PartialEq<alloc::borrow::Cow<'_, Path>> for Path {
602 fn eq(&self, other: &alloc::borrow::Cow<'_, Path>) -> bool {
603 self.inner == other.as_ref().inner
604 }
605}
606
607impl fmt::Display for Path {
608 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609 f.write_str(&self.inner)
610 }
611}
612
613#[cfg(test)]
614mod tests {
615 use super::*;
616
617 #[test]
618 fn test_path_split_with_quotes_and_large_components() -> Result<(), PathError> {
619 let path = Path::new(
620 "::\"miden:counter-contract/counter-contract@0.1.0\"::counter_contract::_RNvXsg_NtNtCseaniv3neBPi_10miden_base5types7storageINtB5_10StorageMapNtNtCscxjsWiPtnzN_11miden_field4word4WordNtNtB19_10wasm_miden4FeltEINtNtCs3NSMmx5ugmE_4core7convert4FromNtNtNtCs52sTGLXFK3W_14miden_base_sys8bindings5types13StorageSlotIdE4fromCsanZ5gV8dMQ0_16counter_contract",
621 );
622 let canonicalized = path.canonicalize()?;
623
624 assert_eq!(canonicalized.as_path(), path);
625 Ok(())
626 }
627
628 #[test]
629 fn test_canonicalize_path_identity() -> Result<(), PathError> {
630 let path = Path::new("foo::bar");
631 let canonicalized = path.canonicalize()?;
632
633 assert_eq!(canonicalized.as_path(), path);
634 Ok(())
635 }
636
637 #[test]
638 fn test_canonicalize_path_kernel_is_absolute() -> Result<(), PathError> {
639 let path = Path::new("$kernel::bar");
640 let canonicalized = path.canonicalize()?;
641
642 let expected = Path::new("::$kernel::bar");
643 assert_eq!(canonicalized.as_path(), expected);
644 Ok(())
645 }
646
647 #[test]
648 fn test_canonicalize_path_exec_is_absolute() -> Result<(), PathError> {
649 let path = Path::new("$exec::$main");
650 let canonicalized = path.canonicalize()?;
651
652 let expected = Path::new("::$exec::$main");
653 assert_eq!(canonicalized.as_path(), expected);
654 Ok(())
655 }
656
657 #[test]
658 fn test_canonicalize_path_remove_unnecessary_quoting() -> Result<(), PathError> {
659 let path = Path::new("foo::\"bar\"");
660 let canonicalized = path.canonicalize()?;
661
662 let expected = Path::new("foo::bar");
663 assert_eq!(canonicalized.as_path(), expected);
664 Ok(())
665 }
666
667 #[test]
668 fn test_canonicalize_path_preserve_necessary_quoting() -> Result<(), PathError> {
669 let path = Path::new("foo::\"bar::baz\"");
670 let canonicalized = path.canonicalize()?;
671
672 assert_eq!(canonicalized.as_path(), path);
673 Ok(())
674 }
675
676 #[test]
677 fn test_canonicalize_path_add_required_quoting_to_components_without_delimiter()
678 -> Result<(), PathError> {
679 let path = Path::new("foo::$bar");
680 let canonicalized = path.canonicalize()?;
681
682 let expected = Path::new("foo::\"$bar\"");
683 assert_eq!(canonicalized.as_path(), expected);
684 Ok(())
685 }
686}