Skip to main content

miden_core/mast/node/
mod.rs

1mod basic_block_node;
2use alloc::{boxed::Box, vec::Vec};
3use core::fmt;
4
5pub use basic_block_node::{
6    BATCH_SIZE as OP_BATCH_SIZE, BasicBlockNode, BasicBlockNodeBuilder,
7    GROUP_SIZE as OP_GROUP_SIZE, OpBatch,
8};
9pub(crate) use basic_block_node::{collect_immediate_placements, hash_op_batches};
10use derive_more::From;
11use miden_utils_core_derive::MastNodeExt;
12
13mod call_node;
14pub use call_node::{CallNode, CallNodeBuilder};
15
16mod dyn_node;
17pub use dyn_node::{DynNode, DynNodeBuilder};
18
19mod external;
20pub use external::{ExternalNode, ExternalNodeBuilder};
21
22mod join_node;
23pub use join_node::{JoinNode, JoinNodeBuilder};
24
25mod split_node;
26use miden_crypto::{Felt, Word};
27use miden_formatting::prettier::PrettyPrint;
28pub use split_node::{SplitNode, SplitNodeBuilder};
29
30mod loop_node;
31#[cfg(any(test, feature = "arbitrary"))]
32pub use basic_block_node::arbitrary;
33pub use loop_node::{LoopNode, LoopNodeBuilder};
34
35mod mast_forest_contributor;
36pub(super) use mast_forest_contributor::fingerprint_with_child_fingerprints;
37pub use mast_forest_contributor::{MastForestContributor, MastNodeBuilder, MastNodeContext};
38
39use crate::{
40    chiplets::hasher,
41    mast::{MastForest, MastForestError, MastNodeId},
42};
43
44pub trait MastNodeExt {
45    /// Returns a commitment/hash of the node.
46    fn digest(&self) -> Word;
47
48    /// Returns a display formatter for this node.
49    fn to_display<'a>(&'a self, mast_forest: &'a MastForest) -> Box<dyn fmt::Display + 'a>;
50
51    /// Returns a pretty printer for this node.
52    fn to_pretty_print<'a>(&'a self, mast_forest: &'a MastForest) -> Box<dyn PrettyPrint + 'a>;
53
54    /// Returns true if the this node has children.
55    fn has_children(&self) -> bool;
56
57    /// Appends the NodeIds of the children of this node, if any, to the vector.
58    fn append_children_to(&self, target: &mut Vec<MastNodeId>);
59
60    /// Executes the given closure for each child of this node.
61    fn for_each_child<F>(&self, f: F)
62    where
63        F: FnMut(MastNodeId);
64
65    /// Returns the domain of this node.
66    fn domain(&self) -> Felt;
67
68    /// Converts this node into its corresponding builder, reusing allocated data where possible.
69    type Builder: MastForestContributor;
70
71    fn to_builder(self, forest: &MastForest) -> Self::Builder;
72}
73
74// MAST NODE
75// ================================================================================================
76
77#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
78pub(in crate::mast) enum MastNodeOrderClass {
79    External,
80    BasicBlock,
81    Internal,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, From, MastNodeExt)]
85#[mast_node_ext(builder = "MastNodeBuilder")]
86pub enum MastNode {
87    Block(BasicBlockNode),
88    Join(JoinNode),
89    Split(SplitNode),
90    Loop(LoopNode),
91    Call(CallNode),
92    Dyn(DynNode),
93    External(ExternalNode),
94}
95
96// ------------------------------------------------------------------------------------------------
97/// Public accessors
98impl MastNode {
99    /// Recomputes this node's digest from its payload and the supplied child digests.
100    /// External nodes retain their opaque dependency digest.
101    pub(in crate::mast) fn compute_digest(
102        &self,
103        mut child_digest: impl FnMut(MastNodeId) -> Result<Word, MastForestError>,
104    ) -> Result<Word, MastForestError> {
105        Ok(match self {
106            Self::Block(block) => hash_op_batches(block.op_batches()),
107            Self::Join(join) => hasher::merge_in_mast_domain(
108                &[child_digest(join.first())?, child_digest(join.second())?],
109                JoinNode::DOMAIN,
110            ),
111            Self::Split(split) => hasher::merge_in_mast_domain(
112                &[child_digest(split.on_true())?, child_digest(split.on_false())?],
113                SplitNode::DOMAIN,
114            ),
115            Self::Loop(loop_node) => hasher::merge_in_mast_domain(
116                &[child_digest(loop_node.body())?, Word::default()],
117                LoopNode::DOMAIN,
118            ),
119            Self::Call(call) => hasher::merge_in_mast_domain(
120                &[child_digest(call.callee())?, Word::default()],
121                if call.is_syscall() {
122                    CallNode::SYSCALL_DOMAIN
123                } else {
124                    CallNode::CALL_DOMAIN
125                },
126            ),
127            Self::Dyn(dyn_node) => {
128                if dyn_node.is_dyncall() {
129                    DynNode::DYNCALL_DEFAULT_DIGEST
130                } else {
131                    DynNode::DYN_DEFAULT_DIGEST
132                }
133            },
134            Self::External(_) => self.digest(),
135        })
136    }
137
138    /// Returns the ordering class used by finalized dense MAST forests.
139    pub(in crate::mast) fn order_class(&self) -> MastNodeOrderClass {
140        if self.is_external() {
141            MastNodeOrderClass::External
142        } else if self.is_basic_block() {
143            MastNodeOrderClass::BasicBlock
144        } else {
145            MastNodeOrderClass::Internal
146        }
147    }
148
149    /// Returns true if this node is an external node.
150    pub fn is_external(&self) -> bool {
151        matches!(self, MastNode::External(_))
152    }
153
154    /// Returns true if this node is a Dyn node.
155    pub fn is_dyn(&self) -> bool {
156        matches!(self, MastNode::Dyn(_))
157    }
158
159    /// Returns true if this node is a basic block.
160    pub fn is_basic_block(&self) -> bool {
161        matches!(self, Self::Block(_))
162    }
163
164    /// Returns the inner basic block node if the [`MastNode`] wraps a [`BasicBlockNode`]; `None`
165    /// otherwise.
166    pub fn get_basic_block(&self) -> Option<&BasicBlockNode> {
167        match self {
168            MastNode::Block(basic_block_node) => Some(basic_block_node),
169            _ => None,
170        }
171    }
172
173    /// Unwraps the inner basic block node if the [`MastNode`] wraps a [`BasicBlockNode`]; panics
174    /// otherwise.
175    ///
176    /// # Panics
177    /// Panics if the [`MastNode`] does not wrap a [`BasicBlockNode`].
178    pub fn unwrap_basic_block(&self) -> &BasicBlockNode {
179        match self {
180            Self::Block(basic_block_node) => basic_block_node,
181            other => unwrap_failed(other, "basic block"),
182        }
183    }
184
185    /// Unwraps the inner join node if the [`MastNode`] wraps a [`JoinNode`]; panics otherwise.
186    ///
187    /// # Panics
188    /// - if the [`MastNode`] does not wrap a [`JoinNode`].
189    pub fn unwrap_join(&self) -> &JoinNode {
190        match self {
191            Self::Join(join_node) => join_node,
192            other => unwrap_failed(other, "join"),
193        }
194    }
195
196    /// Unwraps the inner split node if the [`MastNode`] wraps a [`SplitNode`]; panics otherwise.
197    ///
198    /// # Panics
199    /// - if the [`MastNode`] does not wrap a [`SplitNode`].
200    pub fn unwrap_split(&self) -> &SplitNode {
201        match self {
202            Self::Split(split_node) => split_node,
203            other => unwrap_failed(other, "split"),
204        }
205    }
206
207    /// Unwraps the inner loop node if the [`MastNode`] wraps a [`LoopNode`]; panics otherwise.
208    ///
209    /// # Panics
210    /// - if the [`MastNode`] does not wrap a [`LoopNode`].
211    pub fn unwrap_loop(&self) -> &LoopNode {
212        match self {
213            Self::Loop(loop_node) => loop_node,
214            other => unwrap_failed(other, "loop"),
215        }
216    }
217
218    /// Unwraps the inner call node if the [`MastNode`] wraps a [`CallNode`]; panics otherwise.
219    ///
220    /// # Panics
221    /// - if the [`MastNode`] does not wrap a [`CallNode`].
222    pub fn unwrap_call(&self) -> &CallNode {
223        match self {
224            Self::Call(call_node) => call_node,
225            other => unwrap_failed(other, "call"),
226        }
227    }
228
229    /// Unwraps the inner dynamic node if the [`MastNode`] wraps a [`DynNode`]; panics otherwise.
230    ///
231    /// # Panics
232    /// - if the [`MastNode`] does not wrap a [`DynNode`].
233    pub fn unwrap_dyn(&self) -> &DynNode {
234        match self {
235            Self::Dyn(dyn_node) => dyn_node,
236            other => unwrap_failed(other, "dyn"),
237        }
238    }
239
240    /// Unwraps the inner external node if the [`MastNode`] wraps a [`ExternalNode`]; panics
241    /// otherwise.
242    ///
243    /// # Panics
244    /// - if the [`MastNode`] does not wrap a [`ExternalNode`].
245    pub fn unwrap_external(&self) -> &ExternalNode {
246        match self {
247            Self::External(external_node) => external_node,
248            other => unwrap_failed(other, "external"),
249        }
250    }
251}
252
253// HELPERS
254// ===============================================================================================
255
256/// This function is analogous to the `unwrap_failed()` function used in the implementation of
257/// `core::result::Result` `unwrap_*()` methods.
258#[cold]
259#[inline(never)]
260#[track_caller]
261fn unwrap_failed(node: &MastNode, expected: &str) -> ! {
262    let actual = match node {
263        MastNode::Block(_) => "basic block",
264        MastNode::Join(_) => "join",
265        MastNode::Split(_) => "split",
266        MastNode::Loop(_) => "loop",
267        MastNode::Call(_) => "call",
268        MastNode::Dyn(_) => "dynamic",
269        MastNode::External(_) => "external",
270    };
271    panic!("tried to unwrap {expected} node, but got {actual}");
272}