Skip to main content

miden_assembly_syntax/ast/item/resolver/
mod.rs

1mod error;
2mod symbol_table;
3
4use alloc::sync::Arc;
5
6use miden_debug_types::{SourceManager, SourceSpan, Span, Spanned};
7
8use self::symbol_table::LocalSymbolTable;
9pub use self::{
10    error::SymbolResolutionError,
11    symbol_table::{LocalSymbol, SymbolTable},
12};
13use super::{GlobalItemIndex, ModuleIndex};
14use crate::{
15    Path, Word,
16    ast::{Ident, ItemIndex},
17};
18
19/// Represents the result of resolving a symbol
20#[derive(Debug, Clone)]
21pub enum SymbolResolution {
22    /// The name was resolved to a definition in the same module at the given index
23    Local(Span<ItemIndex>),
24    /// The name was resolved to a path referring to an item exported from another module
25    External(Span<Arc<Path>>),
26    /// The name was resolved to a procedure MAST root
27    MastRoot(Span<Word>),
28    /// The name was resolved to a known definition in with the given global index and absolute path
29    Exact {
30        gid: GlobalItemIndex,
31        path: Span<Arc<Path>>,
32    },
33    /// The name was resolved to a known module
34    Module { id: ModuleIndex, path: Span<Arc<Path>> },
35}
36
37impl SymbolResolution {
38    pub fn into_global_id(&self) -> Option<GlobalItemIndex> {
39        match self {
40            Self::Exact { gid, .. } => Some(*gid),
41            Self::Local(_) | Self::External(_) | Self::MastRoot(_) | Self::Module { .. } => None,
42        }
43    }
44}
45
46impl Spanned for SymbolResolution {
47    fn span(&self) -> SourceSpan {
48        match self {
49            Self::Local(p) => p.span(),
50            Self::External(p) => p.span(),
51            Self::MastRoot(p) => p.span(),
52            Self::Exact { path, .. } => path.span(),
53            Self::Module { path, .. } => path.span(),
54        }
55    }
56}
57
58// LOCAL SYMBOL RESOLVER
59// ================================================================================================
60
61/// A resolver for symbol references in the context of some module.
62///
63/// This resolver does not attempt to resolve external references, aside from expanding any uses
64/// of imports in an external path.
65///
66/// This is used as a low-level symbol resolution primitive in the linker as well.
67pub struct LocalSymbolResolver {
68    source_manager: Arc<dyn SourceManager>,
69    symbols: LocalSymbolTable,
70}
71
72impl LocalSymbolResolver {
73    /// Create a new resolver using the provided [SymbolTable] and [SourceManager].
74    pub fn new<S>(
75        symbols: S,
76        source_manager: Arc<dyn SourceManager>,
77    ) -> Result<Self, SymbolResolutionError>
78    where
79        S: SymbolTable,
80    {
81        let symbols = LocalSymbolTable::new(symbols, source_manager.clone())?;
82        Ok(Self { source_manager, symbols })
83    }
84
85    #[inline]
86    pub fn source_manager(&self) -> Arc<dyn SourceManager> {
87        self.source_manager.clone()
88    }
89
90    /// Try to resolve `name` to an item, either local or external
91    ///
92    /// See `SymbolTable::get` for details.
93    #[inline]
94    pub fn resolve(&self, name: Span<&str>) -> Result<SymbolResolution, SymbolResolutionError> {
95        self.symbols.get(name)
96    }
97
98    /// Try to resolve `path` to an item, either local or external
99    pub fn resolve_path(
100        &self,
101        path: Span<&Path>,
102    ) -> Result<SymbolResolution, SymbolResolutionError> {
103        if path.is_absolute() {
104            return Ok(SymbolResolution::External(path.map(Into::into)));
105        }
106        log::debug!(target: "local-symbol-resolver", "resolving path '{path}'");
107        let (ns, subpath) = path.split_first().expect("invalid item path");
108        log::debug!(target: "local-symbol-resolver", "resolving symbol '{ns}'");
109        match self.resolve(Span::new(path.span(), ns))? {
110            SymbolResolution::External(target) => {
111                log::debug!(target: "local-symbol-resolver", "resolved '{ns}' to import of '{target}'");
112                if subpath.is_empty() {
113                    log::debug!(target: "local-symbol-resolver", "resolved '{path}' '{target}'");
114                    Ok(SymbolResolution::External(target))
115                } else {
116                    let resolved = target.join(subpath).into();
117                    log::debug!(target: "local-symbol-resolver", "resolved '{path}' '{resolved}'");
118                    Ok(SymbolResolution::External(Span::new(target.span(), resolved)))
119                }
120            },
121            SymbolResolution::Local(item) => {
122                log::debug!(target: "local-symbol-resolver", "resolved '{ns}' to local item '{item}'");
123                if subpath.is_empty() {
124                    return Ok(SymbolResolution::Local(item));
125                }
126
127                // This is an invalid subpath reference
128                log::error!(target: "local-symbol-resolver", "cannot resolve '{subpath}' relative to non-module item");
129                Err(SymbolResolutionError::invalid_sub_path(
130                    path.span(),
131                    item.span(),
132                    &*self.source_manager,
133                ))
134            },
135            SymbolResolution::MastRoot(digest) => {
136                log::debug!(target: "local-symbol-resolver", "resolved '{ns}' to procedure root '{digest}'");
137                if subpath.is_empty() {
138                    return Ok(SymbolResolution::MastRoot(digest));
139                }
140
141                // This is an invalid subpath reference
142                log::error!(target: "local-symbol-resolver", "cannot resolve '{subpath}' relative to procedure");
143                Err(SymbolResolutionError::invalid_sub_path(
144                    path.span(),
145                    digest.span(),
146                    &*self.source_manager,
147                ))
148            },
149            SymbolResolution::Module { id, path, .. } => {
150                if subpath.is_empty() {
151                    Ok(SymbolResolution::Module { id, path })
152                } else {
153                    Ok(SymbolResolution::External(path.map(|p| p.join(subpath).into())))
154                }
155            },
156            SymbolResolution::Exact { .. } => unreachable!(),
157        }
158    }
159
160    /// Get the name of the item at `index`
161    ///
162    /// This is guaranteed to resolve if `index` is valid, and will panic if not.
163    pub fn get_item_name(&self, index: ItemIndex) -> Ident {
164        match &self.symbols[index] {
165            LocalSymbol::Item { name, .. } => name.clone(),
166            LocalSymbol::Import { name, .. } => Ident::from_raw_parts(name.clone()),
167        }
168    }
169}