Skip to main content

miden_processor/host/
default.rs

1use alloc::{sync::Arc, vec::Vec};
2
3use miden_core::{
4    Word,
5    events::{EventId, EventName},
6    mast::MastForest,
7};
8use miden_debug_types::{DefaultSourceManager, Location, SourceFile, SourceManager, SourceSpan};
9use miden_mast_package::{PackageDebugInfoError, debug_info::PackageDebugInfo};
10
11use super::handlers::{
12    EventError, EventHandler, EventHandlerRegistry, TraceError, TraceHandler, TraceHandlerRegistry,
13};
14use crate::{
15    BaseHost, ExecutionError, LoadedMastForest, MastForestStore, MemMastForestStore,
16    ProcessorState, SyncHost, advice::AdviceMutation,
17};
18
19// DEFAULT HOST IMPLEMENTATION
20// ================================================================================================
21
22/// A default SyncHost implementation that provides the essential functionality required by the VM.
23#[derive(Debug)]
24pub struct DefaultHost<S: SourceManager = DefaultSourceManager> {
25    store: MemMastForestStore,
26    event_handlers: EventHandlerRegistry,
27    trace_handlers: TraceHandlerRegistry,
28    source_manager: Arc<S>,
29}
30
31impl Default for DefaultHost {
32    fn default() -> Self {
33        Self {
34            store: MemMastForestStore::default(),
35            event_handlers: EventHandlerRegistry::default(),
36            trace_handlers: TraceHandlerRegistry::default(),
37            source_manager: Arc::new(DefaultSourceManager::default()),
38        }
39    }
40}
41
42impl<S> DefaultHost<S>
43where
44    S: SourceManager,
45{
46    /// Use the given source manager implementation instead of the default one
47    /// [`DefaultSourceManager`].
48    pub fn with_source_manager<O>(self, source_manager: Arc<O>) -> DefaultHost<O>
49    where
50        O: SourceManager,
51    {
52        DefaultHost::<O> {
53            store: self.store,
54            event_handlers: self.event_handlers,
55            trace_handlers: self.trace_handlers,
56            source_manager,
57        }
58    }
59
60    /// Loads a [`HostLibrary`] containing a [`MastForest`] with its list of event handlers.
61    ///
62    /// The load is atomic: if one handler fails to register, the host keeps the state it had
63    /// before the call. It holds no handler of the library and it does not hold the MAST forest.
64    ///
65    /// # Errors
66    /// Returns an error when a handler of the library has an empty or reserved event name, or
67    /// when its event already has a handler in this host.
68    pub fn load_library(&mut self, library: impl Into<HostLibrary>) -> Result<(), ExecutionError> {
69        let library = library.into();
70
71        // Each successful registration adds a handler that the registry did not have, so
72        // un-registering the added IDs gives back the state before the call.
73        let mut registered = Vec::with_capacity(library.handlers.len());
74        for (event, handler) in library.handlers {
75            let id = event.to_event_id();
76            if let Err(err) = self.event_handlers.register(event, handler) {
77                for id in registered {
78                    self.event_handlers.unregister(id);
79                }
80                return Err(err);
81            }
82            registered.push(id);
83        }
84
85        self.store.insert_loaded(LoadedMastForest::with_package_debug_info(
86            library.mast_forest,
87            library.package_debug_info,
88        ));
89        Ok(())
90    }
91
92    /// Adds a [`HostLibrary`] containing a [`MastForest`] with its list of event handlers.
93    /// to the host.
94    pub fn with_library(mut self, library: impl Into<HostLibrary>) -> Result<Self, ExecutionError> {
95        self.load_library(library)?;
96        Ok(self)
97    }
98
99    /// Registers a single [`EventHandler`] into this host.
100    ///
101    /// The handler can be either a closure or a free function with signature
102    /// `fn(&mut ProcessorState) -> Result<(), EventHandler>`
103    pub fn register_handler(
104        &mut self,
105        event: EventName,
106        handler: Arc<dyn EventHandler>,
107    ) -> Result<(), ExecutionError> {
108        self.event_handlers.register(event, handler)
109    }
110
111    /// Un-registers a handler with the given id, returning a flag indicating whether a handler
112    /// was previously registered with this id.
113    pub fn unregister_handler(&mut self, id: EventId) -> bool {
114        self.event_handlers.unregister(id)
115    }
116
117    /// Replaces a handler with the given event, returning a flag indicating whether a handler
118    /// was previously registered with this event ID.
119    ///
120    /// # Errors
121    /// Returns an error when the event name is empty or reserved; the host is not changed
122    /// then.
123    pub fn replace_handler(
124        &mut self,
125        event: EventName,
126        handler: Arc<dyn EventHandler>,
127    ) -> Result<bool, ExecutionError> {
128        self.event_handlers.replace(event, handler)
129    }
130
131    /// Registers a single [`TraceHandler`] into this host.
132    ///
133    /// Trace handlers observe VM state for optional, read-only trace events; they cannot mutate the
134    /// advice provider. Unhandled trace event IDs are ignored. The handler can be either a closure
135    /// or a free function.
136    pub fn register_trace_handler(
137        &mut self,
138        event: EventName,
139        handler: Arc<dyn TraceHandler>,
140    ) -> Result<(), ExecutionError> {
141        self.trace_handlers.register(event, handler)
142    }
143
144    /// Un-registers a trace handler with the given id, returning a flag indicating whether a
145    /// handler was previously registered with this id.
146    pub fn unregister_trace_handler(&mut self, id: EventId) -> bool {
147        self.trace_handlers.unregister(id)
148    }
149
150    /// Replaces a trace handler with the given event, returning a flag indicating whether a
151    /// handler was previously registered with this event ID.
152    ///
153    /// # Errors
154    /// Returns an error when the event name is empty or reserved; the host is not changed
155    /// then.
156    pub fn replace_trace_handler(
157        &mut self,
158        event: EventName,
159        handler: Arc<dyn TraceHandler>,
160    ) -> Result<bool, ExecutionError> {
161        self.trace_handlers.replace(event, handler)
162    }
163}
164
165impl<S> BaseHost for DefaultHost<S>
166where
167    S: SourceManager,
168{
169    fn get_label_and_source_file(
170        &self,
171        location: &Location,
172    ) -> (SourceSpan, Option<Arc<SourceFile>>) {
173        let maybe_file = self.source_manager.get_by_uri(location.uri());
174        let span = self.source_manager.location_to_span(location.clone()).unwrap_or_default();
175        (span, maybe_file)
176    }
177
178    fn resolve_event(&self, event_id: EventId) -> Option<&EventName> {
179        self.event_handlers.resolve_event(event_id)
180    }
181
182    fn resolve_trace(&self, trace_id: EventId) -> Option<&EventName> {
183        self.trace_handlers.resolve_trace(trace_id)
184    }
185}
186
187impl<S> SyncHost for DefaultHost<S>
188where
189    S: SourceManager,
190{
191    fn get_mast_forest(&self, node_digest: &Word) -> Option<LoadedMastForest> {
192        self.store.get(node_digest)
193    }
194
195    fn on_event(
196        &mut self,
197        process: &ProcessorState<'_>,
198    ) -> Result<Vec<AdviceMutation>, EventError> {
199        let event_id = EventId::from_felt(process.get_stack_item(0));
200        match self.event_handlers.handle_event(event_id, process) {
201            Ok(Some(mutations)) => Ok(mutations),
202            Ok(None) => {
203                #[derive(Debug, thiserror::Error)]
204                #[error("no event handler registered")]
205                struct UnhandledEvent;
206
207                Err(UnhandledEvent.into())
208            },
209            Err(e) => Err(e),
210        }
211    }
212
213    fn on_trace(&mut self, process: &ProcessorState<'_>) -> Result<(), TraceError> {
214        // The trace id sits one below the `SystemEvent::TraceEvent` id.
215        let trace_id = EventId::from_felt(process.get_stack_item(1));
216        match self.trace_handlers.handle_trace(trace_id, process) {
217            Ok(Some(())) => Ok(()),
218            // Traces are optional/readonly, so an unhandled trace is not an error.
219            Ok(None) => Ok(()),
220            Err(e) => Err(e),
221        }
222    }
223}
224
225// NOOPHOST
226// ================================================================================================
227
228/// A SyncHost which does nothing.
229pub struct NoopHost;
230
231impl BaseHost for NoopHost {
232    #[inline(always)]
233    fn get_label_and_source_file(
234        &self,
235        _location: &Location,
236    ) -> (SourceSpan, Option<Arc<SourceFile>>) {
237        (SourceSpan::UNKNOWN, None)
238    }
239}
240
241impl SyncHost for NoopHost {
242    #[inline(always)]
243    fn get_mast_forest(&self, _node_digest: &Word) -> Option<LoadedMastForest> {
244        None
245    }
246
247    #[inline(always)]
248    fn on_event(
249        &mut self,
250        _process: &ProcessorState<'_>,
251    ) -> Result<Vec<AdviceMutation>, EventError> {
252        Ok(Vec::new())
253    }
254}
255
256// HOST LIBRARY
257// ================================================================================================
258
259/// A rich library representing a [`MastForest`] which also exports
260/// a list of handlers for events it may call.
261pub struct HostLibrary {
262    /// A `MastForest` with procedures exposed by this library.
263    pub mast_forest: Arc<MastForest>,
264    /// Package-owned debug info that belongs to `mast_forest`.
265    pub package_debug_info: Result<Option<PackageDebugInfo>, PackageDebugInfoError>,
266    /// List of handlers along with their event names to call them with `emit`.
267    pub handlers: Vec<(EventName, Arc<dyn EventHandler>)>,
268}
269
270impl HostLibrary {
271    /// Replaces the event handlers of this library.
272    ///
273    /// Use this to supply handlers that the source of the library does not provide, for example
274    /// the Wasm event handlers of a package.
275    pub fn set_handlers(mut self, handlers: Vec<(EventName, Arc<dyn EventHandler>)>) -> Self {
276        self.handlers = handlers;
277        self
278    }
279}
280
281impl Default for HostLibrary {
282    fn default() -> Self {
283        Self {
284            mast_forest: Arc::new(MastForest::new()),
285            package_debug_info: Ok(None),
286            handlers: Vec::new(),
287        }
288    }
289}
290
291/// Converts a package into a host library.
292///
293/// The packaged Wasm event handlers are NOT loaded: this crate cannot depend on the Wasm runner
294/// crate. To get a library with the handlers of the `event_handlers` section, use
295/// `miden_wasm_event_handlers::host_library_from_package`.
296impl From<Arc<miden_mast_package::Package>> for HostLibrary {
297    fn from(package: Arc<miden_mast_package::Package>) -> Self {
298        let package_debug_info = match package.debug_info() {
299            Ok(debug_info) => Ok(debug_info),
300            Err(PackageDebugInfoError::UntrustedSections) => Ok(None),
301            Err(err) => Err(err),
302        };
303        Self {
304            mast_forest: package.mast_forest().clone(),
305            package_debug_info,
306            handlers: vec![],
307        }
308    }
309}
310
311impl From<Arc<MastForest>> for HostLibrary {
312    fn from(mast_forest: Arc<MastForest>) -> Self {
313        Self {
314            mast_forest,
315            package_debug_info: Ok(None),
316            handlers: vec![],
317        }
318    }
319}
320
321impl From<&Arc<MastForest>> for HostLibrary {
322    fn from(mast_forest: &Arc<MastForest>) -> Self {
323        Self {
324            mast_forest: mast_forest.clone(),
325            package_debug_info: Ok(None),
326            handlers: vec![],
327        }
328    }
329}
330
331// TESTS
332// ================================================================================================
333
334#[cfg(test)]
335mod tests {
336    use miden_core::{mast::BasicBlockNodeBuilder, operations::Operation};
337
338    use super::{super::handlers::NoopEventHandler, *};
339    use crate::errors::HostError;
340
341    /// Builds a library with one procedure and one handler per event name.
342    fn library(events: &[&'static str]) -> HostLibrary {
343        let mut mast_forest = MastForest::new();
344        let block = BasicBlockNodeBuilder::new(vec![Operation::Swap, Operation::Swap])
345            .add_to_forest(&mut mast_forest)
346            .unwrap();
347        mast_forest.make_root(block);
348
349        let handlers = events
350            .iter()
351            .map(|event| {
352                (EventName::new(event), Arc::new(NoopEventHandler) as Arc<dyn EventHandler>)
353            })
354            .collect();
355        HostLibrary::from(Arc::new(mast_forest)).set_handlers(handlers)
356    }
357
358    /// Returns `true` when the host resolves a handler for the named event.
359    fn is_registered(host: &DefaultHost, event: &'static str) -> bool {
360        host.resolve_event(EventName::new(event).to_event_id()).is_some()
361    }
362
363    #[test]
364    fn load_library_registers_the_handlers_and_the_forest() {
365        let library = library(&["test::a", "test::b"]);
366        let procedure = library.mast_forest.local_procedure_digests().next().unwrap();
367
368        let mut host = DefaultHost::default();
369        host.load_library(library).unwrap();
370
371        assert!(is_registered(&host, "test::a"));
372        assert!(is_registered(&host, "test::b"));
373        assert!(host.get_mast_forest(&procedure).is_some());
374    }
375
376    #[test]
377    fn failed_load_library_leaves_no_partial_state() {
378        let mut host = DefaultHost::default();
379        host.register_handler(EventName::new("test::b"), Arc::new(NoopEventHandler))
380            .unwrap();
381
382        // The second handler of the library collides with the handler of the host.
383        let library = library(&["test::a", "test::b"]);
384        let procedure = library.mast_forest.local_procedure_digests().next().unwrap();
385        let err = host.load_library(library).unwrap_err();
386
387        assert!(
388            matches!(err, ExecutionError::HostError(HostError::DuplicateEventHandler { .. })),
389            "unexpected error: {err}"
390        );
391        assert!(!is_registered(&host, "test::a"), "the first handler must be rolled back");
392        assert!(host.get_mast_forest(&procedure).is_none(), "the forest must not be loaded");
393    }
394}