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::{AliasTarget, 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    symbols: LocalSymbolTable,
69}
70
71impl LocalSymbolResolver {
72    /// Create a new resolver using the provided [SymbolTable] and [SourceManager].
73    pub fn new<S>(symbols: S, source_manager: Arc<dyn SourceManager>) -> Self
74    where
75        S: SymbolTable,
76    {
77        Self {
78            symbols: LocalSymbolTable::new(symbols, source_manager),
79        }
80    }
81
82    /// Expand `path` using `get_import` to resolve a raw symbol name to an import in the current
83    /// symbol resolution context.
84    ///
85    /// Uses the provided [SourceManager] to emit errors that are discovered during expansion.
86    #[inline]
87    pub fn expand<F>(
88        get_import: F,
89        path: Span<&Path>,
90        source_manager: &dyn SourceManager,
91    ) -> Result<SymbolResolution, SymbolResolutionError>
92    where
93        F: Fn(&str) -> Option<AliasTarget>,
94    {
95        LocalSymbolTable::expand(get_import, path, source_manager)
96    }
97
98    #[inline]
99    pub fn source_manager(&self) -> Arc<dyn SourceManager> {
100        self.symbols.source_manager_arc()
101    }
102
103    /// Try to resolve `name` to an item, either local or external
104    ///
105    /// See `SymbolTable::get` for details.
106    #[inline]
107    pub fn resolve(&self, name: Span<&str>) -> Result<SymbolResolution, SymbolResolutionError> {
108        self.symbols.get(name)
109    }
110
111    /// Try to resolve `path` to an item, either local or external
112    pub fn resolve_path(
113        &self,
114        path: Span<&Path>,
115    ) -> Result<SymbolResolution, SymbolResolutionError> {
116        if path.is_absolute() {
117            return Ok(SymbolResolution::External(path.map(|p| p.into())));
118        }
119        log::debug!(target: "local-symbol-resolver", "resolving path '{path}'");
120        let (ns, subpath) = path.split_first().expect("invalid item path");
121        log::debug!(target: "local-symbol-resolver", "resolving symbol '{ns}'");
122        match self.resolve(Span::new(path.span(), ns))? {
123            SymbolResolution::External(target) => {
124                log::debug!(target: "local-symbol-resolver", "resolved '{ns}' to import of '{target}'");
125                if subpath.is_empty() {
126                    log::debug!(target: "local-symbol-resolver", "resolved '{path}' '{target}'");
127                    Ok(SymbolResolution::External(target))
128                } else {
129                    let resolved = target.join(subpath).into();
130                    log::debug!(target: "local-symbol-resolver", "resolved '{path}' '{resolved}'");
131                    Ok(SymbolResolution::External(Span::new(target.span(), resolved)))
132                }
133            },
134            SymbolResolution::Local(item) => {
135                log::debug!(target: "local-symbol-resolver", "resolved '{ns}' to local item '{item}'");
136                if subpath.is_empty() {
137                    return Ok(SymbolResolution::Local(item));
138                }
139
140                // This is an invalid subpath reference
141                log::error!(target: "local-symbol-resolver", "cannot resolve '{subpath}' relative to non-module item");
142                Err(SymbolResolutionError::invalid_sub_path(
143                    path.span(),
144                    item.span(),
145                    self.symbols.source_manager(),
146                ))
147            },
148            SymbolResolution::MastRoot(digest) => {
149                log::debug!(target: "local-symbol-resolver", "resolved '{ns}' to procedure root '{digest}'");
150                if subpath.is_empty() {
151                    return Ok(SymbolResolution::MastRoot(digest));
152                }
153
154                // This is an invalid subpath reference
155                log::error!(target: "local-symbol-resolver", "cannot resolve '{subpath}' relative to procedure");
156                Err(SymbolResolutionError::invalid_sub_path(
157                    path.span(),
158                    digest.span(),
159                    self.symbols.source_manager(),
160                ))
161            },
162            SymbolResolution::Module { id, path, .. } => {
163                if subpath.is_empty() {
164                    Ok(SymbolResolution::Module { id, path })
165                } else {
166                    Ok(SymbolResolution::External(path.map(|p| p.join(subpath).into())))
167                }
168            },
169            SymbolResolution::Exact { .. } => unreachable!(),
170        }
171    }
172
173    /// Get the name of the item at `index`
174    ///
175    /// This is guaranteed to resolve if `index` is valid, and will panic if not.
176    pub fn get_item_name(&self, index: ItemIndex) -> Ident {
177        match &self.symbols[index] {
178            LocalSymbol::Item { name, .. } => name.clone(),
179            LocalSymbol::Import { name, .. } => Ident::from_raw_parts(name.clone()),
180        }
181    }
182}