miden_assembly/ast/
imports.rs

1use core::fmt;
2
3use crate::{LibraryNamespace, LibraryPath, SourceSpan, Spanned, ast::Ident};
4
5// IMPORT
6// ================================================================================================
7
8/// Represents an import statement in Miden Assembly syntax.
9#[derive(Clone)]
10pub struct Import {
11    /// The source span of the statement.
12    pub span: SourceSpan,
13    /// The local module name/alias.
14    ///
15    /// When the imported item is aliased to a new name, this field contains the alias, while
16    /// `path.last()` can be used to obtain the actual name.
17    pub name: Ident,
18    /// The fully-qualified path.
19    pub path: LibraryPath,
20    /// The number of times this import has been used locally.
21    pub uses: usize,
22}
23
24impl Import {
25    /// Returns true if this import is aliased to a different name in its containing module.
26    pub fn is_aliased(&self) -> bool {
27        self.name.as_ref() != self.path.last()
28    }
29
30    /// Returns the namespace of the imported module.
31    pub fn namespace(&self) -> &LibraryNamespace {
32        self.path.namespace()
33    }
34
35    /// Returns the fully-qualified path of the imported module.
36    pub fn path(&self) -> &LibraryPath {
37        &self.path
38    }
39
40    /// Returns true if this import has at least one use in its containing module.
41    pub fn is_used(&self) -> bool {
42        self.uses > 0
43    }
44}
45
46impl fmt::Debug for Import {
47    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48        f.debug_struct("Import")
49            .field("name", &self.name)
50            .field("path", &self.path)
51            .field("uses", &self.uses)
52            .finish()
53    }
54}
55
56impl crate::prettier::PrettyPrint for Import {
57    fn render(&self) -> crate::prettier::Document {
58        use crate::prettier::*;
59
60        let mut doc = const_text("use") + const_text(".") + display(&self.path);
61        if self.is_aliased() {
62            doc += const_text("->") + display(&self.name);
63        }
64        doc
65    }
66}
67
68impl Eq for Import {}
69
70impl PartialEq for Import {
71    fn eq(&self, other: &Self) -> bool {
72        self.name == other.name && self.path == other.path
73    }
74}
75
76impl Spanned for Import {
77    fn span(&self) -> SourceSpan {
78        self.span
79    }
80}