miden-assembly-syntax 0.22.1

Parsing and semantic analysis of the Miden Assembly language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use alloc::{
    borrow::{Borrow, Cow, ToOwned},
    string::ToString,
};
use core::fmt;

use super::{Iter, Join, PathBuf, PathComponent, PathError, StartsWith};
use crate::ast::Ident;

/// A borrowed reference to a subset of a path, e.g. another [Path] or a [PathBuf]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Path {
    /// A view into the selected components of the path, i.e. the parts delimited by `::`
    inner: str,
}

impl fmt::Debug for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.inner, f)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Path {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.inner)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for &'de Path {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Visitor;

        struct PathVisitor;

        impl<'de> Visitor<'de> for PathVisitor {
            type Value = &'de Path;

            fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
                formatter.write_str("a borrowed Path")
            }

            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Path::validate(v).map_err(serde::de::Error::custom)
            }
        }

        deserializer.deserialize_any(PathVisitor)
    }
}

impl ToOwned for Path {
    type Owned = PathBuf;
    #[inline]
    fn to_owned(&self) -> PathBuf {
        self.to_path_buf()
    }
    #[inline]
    fn clone_into(&self, target: &mut Self::Owned) {
        self.inner.clone_into(&mut target.inner)
    }
}

impl Borrow<Path> for PathBuf {
    fn borrow(&self) -> &Path {
        Path::new(self)
    }
}

impl AsRef<str> for Path {
    #[inline]
    fn as_ref(&self) -> &str {
        &self.inner
    }
}

impl AsRef<Path> for str {
    #[inline(always)]
    fn as_ref(&self) -> &Path {
        unsafe { &*(self as *const str as *const Path) }
    }
}

impl AsRef<Path> for Ident {
    #[inline(always)]
    fn as_ref(&self) -> &Path {
        self.as_str().as_ref()
    }
}

impl AsRef<Path> for crate::ast::ProcedureName {
    #[inline(always)]
    fn as_ref(&self) -> &Path {
        let ident: &Ident = self.as_ref();
        ident.as_str().as_ref()
    }
}

impl AsRef<Path> for crate::ast::QualifiedProcedureName {
    #[inline(always)]
    fn as_ref(&self) -> &Path {
        self.as_path()
    }
}

impl AsRef<Path> for Path {
    #[inline(always)]
    fn as_ref(&self) -> &Path {
        self
    }
}

impl From<&Path> for alloc::sync::Arc<Path> {
    fn from(path: &Path) -> Self {
        path.to_path_buf().into()
    }
}

/// Conversions
impl Path {
    /// Path components  must be 255 bytes or less
    pub const MAX_COMPONENT_LENGTH: usize = u8::MAX as usize;

    /// An empty path for use as a default value, placeholder, comparisons, etc.
    pub const EMPTY: &Path = unsafe { &*("" as *const str as *const Path) };

    /// Base kernel path.
    pub const KERNEL_PATH: &str = "$kernel";
    pub const ABSOLUTE_KERNEL_PATH: &str = "::$kernel";
    pub const KERNEL: &Path =
        unsafe { &*(Self::ABSOLUTE_KERNEL_PATH as *const str as *const Path) };

    /// Path for an executable module.
    pub const EXEC_PATH: &str = "$exec";
    pub const ABSOLUTE_EXEC_PATH: &str = "::$exec";
    pub const EXEC: &Path = unsafe { &*(Self::ABSOLUTE_EXEC_PATH as *const str as *const Path) };

    pub fn new<S: AsRef<str> + ?Sized>(path: &S) -> &Path {
        // SAFETY: The representation of Path is equivalent to str
        unsafe { &*(path.as_ref() as *const str as *const Path) }
    }

    pub fn from_mut(path: &mut str) -> &mut Path {
        // SAFETY: The representation of Path is equivalent to str
        unsafe { &mut *(path as *mut str as *mut Path) }
    }

    /// Verify that `path` meets all the requirements for a valid [Path]
    pub fn validate(path: &str) -> Result<&Path, PathError> {
        match path {
            "" | "\"\"" => return Err(PathError::Empty),
            "::" => return Err(PathError::EmptyComponent),
            _ => (),
        }

        if path.len() > u16::MAX as usize {
            return Err(PathError::TooLong { max: u16::MAX as usize });
        }

        for result in Iter::new(path) {
            result?;
        }

        Ok(Path::new(path))
    }

    /// Get a [Path] corresponding to [Self::KERNEL_PATH]
    pub const fn kernel_path() -> &'static Path {
        Path::KERNEL
    }

    /// Get a [Path] corresponding to [Self::EXEC_PATH]
    pub const fn exec_path() -> &'static Path {
        Path::EXEC
    }

    #[inline]
    pub const fn as_str(&self) -> &str {
        &self.inner
    }

    #[inline]
    pub fn as_mut_str(&mut self) -> &mut str {
        &mut self.inner
    }

    /// Get an [Ident] that is equivalent to this [Path], so long as the path has only a single
    /// component.
    ///
    /// Returns `None` if the path cannot be losslessly represented as a single component.
    pub fn as_ident(&self) -> Option<Ident> {
        let mut components = self.components().filter_map(|c| c.ok());
        match components.next()? {
            component @ PathComponent::Normal(_) => {
                if components.next().is_none() {
                    component.to_ident()
                } else {
                    None
                }
            },
            PathComponent::Root => None,
        }
    }

    /// Convert this [Path] to an owned [PathBuf]
    pub fn to_path_buf(&self) -> PathBuf {
        PathBuf { inner: self.inner.to_string() }
    }

    /// Convert an [Ident] to an equivalent [Path] or [PathBuf], depending on whether the identifier
    /// would require quoting as a path.
    pub fn from_ident(ident: &Ident) -> Cow<'_, Path> {
        let ident = ident.as_str();
        if Ident::requires_quoting(ident) {
            let mut buf = PathBuf::with_capacity(ident.len() + 2);
            buf.push_component(ident);
            Cow::Owned(buf)
        } else {
            Cow::Borrowed(Path::new(ident))
        }
    }
}

/// Accesssors
impl Path {
    /// Returns true if this path is empty (i.e. has no components)
    pub fn is_empty(&self) -> bool {
        matches!(&self.inner, "" | "::" | "\"\"")
    }

    /// Returns the number of components in the path
    pub fn len(&self) -> usize {
        self.components().count()
    }

    /// Return the size of the path in [char]s when displayed as a string
    pub fn char_len(&self) -> usize {
        self.inner.chars().count()
    }

    /// Return the size of the path in bytes when displayed as a string
    #[inline]
    pub fn byte_len(&self) -> usize {
        self.inner.len()
    }

    /// Returns true if this path is an absolute path
    pub fn is_absolute(&self) -> bool {
        matches!(self.components().next(), Some(Ok(PathComponent::Root)))
    }

    /// Make this path absolute, if not already
    ///
    /// NOTE: This does not _resolve_ the path, it simply ensures the path has the root prefix
    pub fn to_absolute(&self) -> Cow<'_, Path> {
        if self.is_absolute() {
            Cow::Borrowed(self)
        } else {
            let mut buf = PathBuf::with_capacity(self.byte_len() + 2);
            buf.push_component("::");
            buf.extend_with_components(self.components()).expect("invalid path");
            Cow::Owned(buf)
        }
    }

    /// Strip the root prefix from this path, if it has one.
    pub fn to_relative(&self) -> &Path {
        match self.inner.strip_prefix("::") {
            Some(rest) => Path::new(rest),
            None => self,
        }
    }

    /// Returns the [Path] without its final component, if there is one.
    ///
    /// This means it may return an empty [Path] for relative paths with a single component.
    ///
    /// Returns `None` if the path terminates with the root prefix, or if it is empty.
    pub fn parent(&self) -> Option<&Path> {
        let mut components = self.components();
        match components.next_back()?.ok()? {
            PathComponent::Root => None,
            _ => Some(components.as_path()),
        }
    }

    /// Returns an iterator over all components of the path.
    pub fn components(&self) -> Iter<'_> {
        Iter::new(&self.inner)
    }

    /// Get the first non-root component of this path as a `str`
    ///
    /// Returns `None` if the path is empty, or consists only of the root prefix.
    pub fn first(&self) -> Option<&str> {
        self.split_first().map(|(first, _)| first)
    }

    /// Get the first non-root component of this path as a `str`
    ///
    /// Returns `None` if the path is empty, or consists only of the root prefix.
    pub fn last(&self) -> Option<&str> {
        self.split_last().map(|(last, _)| last)
    }

    /// Splits this path on the first non-root component, returning it and a new [Path] of the
    /// remaining components.
    ///
    /// Returns `None` if there are no components to split
    pub fn split_first(&self) -> Option<(&str, &Path)> {
        let mut components = self.components();
        match components.next()?.ok()? {
            PathComponent::Root => {
                let first = components.next().and_then(|c| c.ok()).map(|c| c.as_str())?;
                Some((first, components.as_path()))
            },
            first @ PathComponent::Normal(_) => Some((first.as_str(), components.as_path())),
        }
    }

    /// Splits this path on the last component, returning it and a new [Path] of the remaining
    /// components.
    ///
    /// Returns `None` if there are no components to split
    pub fn split_last(&self) -> Option<(&str, &Path)> {
        let mut components = self.components();
        match components.next_back()?.ok()? {
            PathComponent::Root => None,
            last @ PathComponent::Normal(_) => Some((last.as_str(), components.as_path())),
        }
    }

    /// Returns true if this path is for the root kernel module.
    pub fn is_kernel_path(&self) -> bool {
        match self.inner.strip_prefix("::") {
            Some(Self::KERNEL_PATH) => true,
            Some(_) => false,
            None => &self.inner == Self::KERNEL_PATH,
        }
    }

    /// Returns true if this path is for the root kernel module or an item in it
    pub fn is_in_kernel(&self) -> bool {
        if self.is_kernel_path() {
            return true;
        }

        match self.split_last() {
            Some((_, prefix)) => prefix.is_kernel_path(),
            None => false,
        }
    }

    /// Returns true if this path is for an executable module.
    pub fn is_exec_path(&self) -> bool {
        match self.inner.strip_prefix("::") {
            Some(Self::EXEC_PATH) => true,
            Some(_) => false,
            None => &self.inner == Self::EXEC_PATH,
        }
    }

    /// Returns true if this path is for the executable module or an item in it
    pub fn is_in_exec(&self) -> bool {
        if self.is_exec_path() {
            return true;
        }

        match self.split_last() {
            Some((_, prefix)) => prefix.is_exec_path(),
            None => false,
        }
    }

    /// Returns true if the current path, sans root component, starts with `prefix`
    ///
    /// The matching semantics of `Prefix` depend on the implementation of [`StartsWith<Prefix>`],
    /// in particular, if `Prefix` is `str`, then the prefix is matched against the first non-root
    /// component of `self`, regardless of whether the string contains path delimiters (i.e. `::`).
    ///
    /// See the [StartsWith] trait for more details.
    #[inline]
    pub fn starts_with<Prefix>(&self, prefix: &Prefix) -> bool
    where
        Prefix: ?Sized,
        Self: StartsWith<Prefix>,
    {
        <Self as StartsWith<Prefix>>::starts_with(self, prefix)
    }

    /// Returns true if the current path, including root component, starts with `prefix`
    ///
    /// The matching semantics of `Prefix` depend on the implementation of [`StartsWith<Prefix>`],
    /// in particular, if `Prefix` is `str`, then the prefix is matched against the first component
    /// of `self`, regardless of whether the string contains path delimiters (i.e. `::`).
    ///
    /// See the [StartsWith] trait for more details.
    #[inline]
    pub fn starts_with_exactly<Prefix>(&self, prefix: &Prefix) -> bool
    where
        Prefix: ?Sized,
        Self: StartsWith<Prefix>,
    {
        <Self as StartsWith<Prefix>>::starts_with_exactly(self, prefix)
    }

    /// Strips `prefix` from `self`, or returns `None` if `self` does not start with `prefix`.
    ///
    /// NOTE: Prefixes must be exact, i.e. if you call `path.strip_prefix(prefix)` and `path` is
    /// relative but `prefix` is absolute, then this will return `None`. The same is true if `path`
    /// is absolute and `prefix` is relative.
    pub fn strip_prefix<'a>(&'a self, prefix: &Self) -> Option<&'a Self> {
        let mut components = self.components();
        for prefix_component in prefix.components() {
            // All `Path` APIs assume that a `Path` is valid upon construction, though this is not
            // actually enforced currently. We assert here if iterating over the components of the
            // path finds an invalid component, because we expected the caller to have already
            // validated the path
            //
            // In the future, we will likely enforce validity at construction so that iterating
            // over its components is infallible, but that will require a breaking change to some
            // APIs
            let prefix_component = prefix_component.expect("invalid prefix path");
            match (components.next(), prefix_component) {
                (Some(Ok(PathComponent::Root)), PathComponent::Root) => (),
                (Some(Ok(c @ PathComponent::Normal(_))), pc @ PathComponent::Normal(_)) => {
                    if c.as_str() != pc.as_str() {
                        return None;
                    }
                },
                (Some(Ok(_) | Err(_)) | None, _) => return None,
            }
        }
        Some(components.as_path())
    }

    /// Create an owned [PathBuf] with `path` adjoined to `self`.
    ///
    /// If `path` is absolute, it replaces the current path.
    ///
    /// The semantics of how `other` is joined to `self` in the resulting path depends on the
    /// implementation of [Join] used. The implementation for [Path] and [PathBuf] joins all
    /// components of `other` to self`; while the implementation for [prim@str], string-like values,
    /// and identifiers/symbols joins just a single component. You must be careful to ensure that
    /// if you are passing a string here, that you specifically want to join it as a single
    /// component, or the resulting path may be different than you expect. It is recommended that
    /// you use `Path::new(&string)` if you want to be explicit about treating a string-like value
    /// as a multi-component path.
    #[inline]
    pub fn join<P>(&self, other: &P) -> PathBuf
    where
        P: ?Sized,
        Path: Join<P>,
    {
        <Path as Join<P>>::join(self, other)
    }

    /// Canonicalize this path by ensuring that all components are in canonical form.
    ///
    /// Canonical form dictates that:
    ///
    /// * A component is quoted only if it requires quoting, and unquoted otherwise
    /// * Is made absolute if relative and the first component is $kernel or $exec
    ///
    /// Returns `Err` if the path is invalid
    pub fn canonicalize(&self) -> Result<PathBuf, PathError> {
        let mut buf = PathBuf::with_capacity(self.byte_len());
        buf.extend_with_components(self.components())?;
        Ok(buf)
    }
}

impl StartsWith<str> for Path {
    fn starts_with(&self, prefix: &str) -> bool {
        let this = self.to_relative();
        <Path as StartsWith<str>>::starts_with_exactly(this, prefix)
    }

    #[inline]
    fn starts_with_exactly(&self, prefix: &str) -> bool {
        match prefix {
            "" => true,
            "::" => self.is_absolute(),
            prefix => {
                let mut components = self.components();
                let prefix = if let Some(prefix) = prefix.strip_prefix("::") {
                    let is_absolute =
                        components.next().is_some_and(|c| matches!(c, Ok(PathComponent::Root)));
                    if !is_absolute {
                        return false;
                    }
                    prefix
                } else {
                    prefix
                };
                components.next().is_some_and(
                    |c| matches!(c, Ok(c @ PathComponent::Normal(_)) if c.as_str() == prefix),
                )
            },
        }
    }
}

impl StartsWith<Path> for Path {
    fn starts_with(&self, prefix: &Path) -> bool {
        let this = self.to_relative();
        let prefix = prefix.to_relative();
        <Path as StartsWith<Path>>::starts_with_exactly(this, prefix)
    }

    #[inline]
    fn starts_with_exactly(&self, prefix: &Path) -> bool {
        let mut components = self.components();
        for prefix_component in prefix.components() {
            // All `Path` APIs assume that a `Path` is valid upon construction, though this is not
            // actually enforced currently. We assert here if iterating over the components of the
            // path finds an invalid component, because we expected the caller to have already
            // validated the path
            //
            // In the future, we will likely enforce validity at construction so that iterating
            // over its components is infallible, but that will require a breaking change to some
            // APIs
            let prefix_component = prefix_component.expect("invalid prefix path");
            match (components.next(), prefix_component) {
                (Some(Ok(PathComponent::Root)), PathComponent::Root) => {},
                (Some(Ok(c @ PathComponent::Normal(_))), pc @ PathComponent::Normal(_)) => {
                    if c.as_str() != pc.as_str() {
                        return false;
                    }
                },
                (Some(Ok(_) | Err(_)) | None, _) => return false,
            }
        }
        true
    }
}

impl PartialEq<str> for Path {
    fn eq(&self, other: &str) -> bool {
        &self.inner == other
    }
}

impl PartialEq<PathBuf> for Path {
    fn eq(&self, other: &PathBuf) -> bool {
        &self.inner == other.inner.as_str()
    }
}

impl PartialEq<&PathBuf> for Path {
    fn eq(&self, other: &&PathBuf) -> bool {
        &self.inner == other.inner.as_str()
    }
}

impl PartialEq<Path> for PathBuf {
    fn eq(&self, other: &Path) -> bool {
        self.inner.as_str() == &other.inner
    }
}

impl PartialEq<&Path> for Path {
    fn eq(&self, other: &&Path) -> bool {
        self.inner == other.inner
    }
}

impl PartialEq<alloc::boxed::Box<Path>> for Path {
    fn eq(&self, other: &alloc::boxed::Box<Path>) -> bool {
        self.inner == other.inner
    }
}

impl PartialEq<alloc::rc::Rc<Path>> for Path {
    fn eq(&self, other: &alloc::rc::Rc<Path>) -> bool {
        self.inner == other.inner
    }
}

impl PartialEq<alloc::sync::Arc<Path>> for Path {
    fn eq(&self, other: &alloc::sync::Arc<Path>) -> bool {
        self.inner == other.inner
    }
}

impl PartialEq<alloc::borrow::Cow<'_, Path>> for Path {
    fn eq(&self, other: &alloc::borrow::Cow<'_, Path>) -> bool {
        self.inner == other.as_ref().inner
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.inner)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_canonicalize_path_identity() -> Result<(), PathError> {
        let path = Path::new("foo::bar");
        let canonicalized = path.canonicalize()?;

        assert_eq!(canonicalized.as_path(), path);
        Ok(())
    }

    #[test]
    fn test_canonicalize_path_kernel_is_absolute() -> Result<(), PathError> {
        let path = Path::new("$kernel::bar");
        let canonicalized = path.canonicalize()?;

        let expected = Path::new("::$kernel::bar");
        assert_eq!(canonicalized.as_path(), expected);
        Ok(())
    }

    #[test]
    fn test_canonicalize_path_exec_is_absolute() -> Result<(), PathError> {
        let path = Path::new("$exec::$main");
        let canonicalized = path.canonicalize()?;

        let expected = Path::new("::$exec::$main");
        assert_eq!(canonicalized.as_path(), expected);
        Ok(())
    }

    #[test]
    fn test_canonicalize_path_remove_unnecessary_quoting() -> Result<(), PathError> {
        let path = Path::new("foo::\"bar\"");
        let canonicalized = path.canonicalize()?;

        let expected = Path::new("foo::bar");
        assert_eq!(canonicalized.as_path(), expected);
        Ok(())
    }

    #[test]
    fn test_canonicalize_path_preserve_necessary_quoting() -> Result<(), PathError> {
        let path = Path::new("foo::\"bar::baz\"");
        let canonicalized = path.canonicalize()?;

        assert_eq!(canonicalized.as_path(), path);
        Ok(())
    }

    #[test]
    fn test_canonicalize_path_add_required_quoting_to_components_without_delimiter()
    -> Result<(), PathError> {
        let path = Path::new("foo::$bar");
        let canonicalized = path.canonicalize()?;

        let expected = Path::new("foo::\"$bar\"");
        assert_eq!(canonicalized.as_path(), expected);
        Ok(())
    }
}