Skip to main content

miden_assembly_syntax/ast/instruction/
print.rs

1use crate::{
2    DisplayHex,
3    ast::{Immediate, Instruction, InvocationTarget},
4    prettier::{Document, PrettyPrint},
5};
6
7impl PrettyPrint for Instruction {
8    fn render(&self) -> Document {
9        use crate::prettier::*;
10
11        match self {
12            Self::Nop => const_text("nop"),
13            Self::Assert => const_text("assert"),
14            Self::AssertWithError(err_code) => flatten(
15                const_text("assert.err") + const_text("=") + text(format!("\"{err_code}\"")),
16            ),
17            Self::AssertEq => const_text("assert_eq"),
18            Self::AssertEqWithError(err_code) => flatten(
19                const_text("assert_eq.err") + const_text("=") + text(format!("\"{err_code}\"")),
20            ),
21            Self::AssertEqw => const_text("assert_eqw"),
22            Self::AssertEqwWithError(err_code) => flatten(
23                const_text("assert_eqw.err") + const_text("=") + text(format!("\"{err_code}\"")),
24            ),
25            Self::Assertz => const_text("assertz"),
26            Self::AssertzWithError(err_code) => flatten(
27                const_text("assertz.err") + const_text("=") + text(format!("\"{err_code}\"")),
28            ),
29            Self::Add => const_text("add"),
30            Self::AddImm(value) => inst_with_felt_imm("add", value),
31            Self::Sub => const_text("sub"),
32            Self::SubImm(value) => inst_with_felt_imm("sub", value),
33            Self::Mul => const_text("mul"),
34            Self::MulImm(value) => inst_with_felt_imm("mul", value),
35            Self::Div => const_text("div"),
36            Self::DivImm(value) => inst_with_felt_imm("div", value),
37            Self::Neg => const_text("neg"),
38            Self::ILog2 => const_text("ilog2"),
39            Self::Inv => const_text("inv"),
40            Self::Incr => const_text("add.1"),
41            Self::Pow2 => const_text("pow2"),
42            Self::Exp => const_text("exp"),
43            Self::ExpImm(value) => inst_with_felt_imm("exp", value),
44            Self::ExpBitLength(value) => text(format!("exp.u{value}")),
45            Self::Not => const_text("not"),
46            Self::And => const_text("and"),
47            Self::Or => const_text("or"),
48            Self::Xor => const_text("xor"),
49            Self::Eq => const_text("eq"),
50            Self::EqImm(value) => inst_with_felt_imm("eq", value),
51            Self::Neq => const_text("neq"),
52            Self::NeqImm(value) => inst_with_felt_imm("neq", value),
53            Self::Eqw => const_text("eqw"),
54            Self::Lt => const_text("lt"),
55            Self::Lte => const_text("lte"),
56            Self::Gt => const_text("gt"),
57            Self::Gte => const_text("gte"),
58            Self::IsOdd => const_text("is_odd"),
59
60            // ----- ext2 operations --------------------------------------------------------------
61            Self::Ext2Add => const_text("ext2add"),
62            Self::Ext2Sub => const_text("ext2sub"),
63            Self::Ext2Mul => const_text("ext2mul"),
64            Self::Ext2Div => const_text("ext2div"),
65            Self::Ext2Neg => const_text("ext2neg"),
66            Self::Ext2Inv => const_text("ext2inv"),
67
68            // ----- u32 manipulation -------------------------------------------------------------
69            Self::U32Test => const_text("u32test"),
70            Self::U32TestW => const_text("u32testw"),
71            Self::U32Assert => const_text("u32assert"),
72            Self::U32AssertWithError(err_code) => flatten(
73                const_text("u32assert.err") + const_text("=") + text(format!("\"{err_code}\"")),
74            ),
75            Self::U32Assert2 => const_text("u32assert2"),
76            Self::U32Assert2WithError(err_code) => flatten(
77                const_text("u32assert2.err") + const_text("=") + text(format!("\"{err_code}\"")),
78            ),
79            Self::U32AssertW => const_text("u32assertw"),
80            Self::U32AssertWWithError(err_code) => flatten(
81                const_text("u32assertw.err") + const_text("=") + text(format!("\"{err_code}\"")),
82            ),
83            Self::U32Split => const_text("u32split"),
84            Self::U32Cast => const_text("u32cast"),
85            Self::U32WrappingAdd => const_text("u32wrapping_add"),
86            Self::U32WrappingAddImm(value) => inst_with_imm("u32wrapping_add", value),
87            Self::U32OverflowingAdd => const_text("u32overflowing_add"),
88            Self::U32OverflowingAddImm(value) => inst_with_imm("u32overflowing_add", value),
89            Self::U32WideningAdd => const_text("u32widening_add"),
90            Self::U32WideningAddImm(value) => inst_with_imm("u32widening_add", value),
91            Self::U32OverflowingAdd3 => const_text("u32overflowing_add3"),
92            Self::U32WideningAdd3 => const_text("u32widening_add3"),
93            Self::U32WrappingAdd3 => const_text("u32wrapping_add3"),
94            Self::U32WrappingSub => const_text("u32wrapping_sub"),
95            Self::U32WrappingSubImm(value) => inst_with_imm("u32wrapping_sub", value),
96            Self::U32OverflowingSub => const_text("u32overflowing_sub"),
97            Self::U32OverflowingSubImm(value) => inst_with_imm("u32overflowing_sub", value),
98            Self::U32WrappingMul => const_text("u32wrapping_mul"),
99            Self::U32WrappingMulImm(value) => inst_with_imm("u32wrapping_mul", value),
100            Self::U32WideningMul => const_text("u32widening_mul"),
101            Self::U32WideningMulImm(value) => inst_with_imm("u32widening_mul", value),
102            Self::U32WideningMadd => const_text("u32widening_madd"),
103            Self::U32WrappingMadd => const_text("u32wrapping_madd"),
104            Self::U32Div => const_text("u32div"),
105            Self::U32DivImm(value) => inst_with_imm("u32div", value),
106            Self::U32Mod => const_text("u32mod"),
107            Self::U32ModImm(value) => inst_with_imm("u32mod", value),
108            Self::U32DivMod => const_text("u32divmod"),
109            Self::U32DivModImm(value) => inst_with_imm("u32divmod", value),
110            Self::U32And => const_text("u32and"),
111            Self::U32Or => const_text("u32or"),
112            Self::U32Xor => const_text("u32xor"),
113            Self::U32Not => const_text("u32not"),
114            Self::U32Shr => const_text("u32shr"),
115            Self::U32ShrImm(value) => inst_with_imm("u32shr", value),
116            Self::U32Shl => const_text("u32shl"),
117            Self::U32ShlImm(value) => inst_with_imm("u32shl", value),
118            Self::U32Rotr => const_text("u32rotr"),
119            Self::U32RotrImm(value) => inst_with_imm("u32rotr", value),
120            Self::U32Rotl => const_text("u32rotl"),
121            Self::U32RotlImm(value) => inst_with_imm("u32rotl", value),
122            Self::U32Popcnt => const_text("u32popcnt"),
123            Self::U32Clz => const_text("u32clz"),
124            Self::U32Ctz => const_text("u32ctz"),
125            Self::U32Clo => const_text("u32clo"),
126            Self::U32Cto => const_text("u32cto"),
127            Self::U32Lt => const_text("u32lt"),
128            Self::U32Lte => const_text("u32lte"),
129            Self::U32Gt => const_text("u32gt"),
130            Self::U32Gte => const_text("u32gte"),
131            Self::U32Min => const_text("u32min"),
132            Self::U32Max => const_text("u32max"),
133
134            // ----- stack manipulation -----------------------------------------------------------
135            Self::Drop => const_text("drop"),
136            Self::DropW => const_text("dropw"),
137            Self::PadW => const_text("padw"),
138            Self::Dup0 => const_text("dup.0"),
139            Self::Dup1 => const_text("dup.1"),
140            Self::Dup2 => const_text("dup.2"),
141            Self::Dup3 => const_text("dup.3"),
142            Self::Dup4 => const_text("dup.4"),
143            Self::Dup5 => const_text("dup.5"),
144            Self::Dup6 => const_text("dup.6"),
145            Self::Dup7 => const_text("dup.7"),
146            Self::Dup8 => const_text("dup.8"),
147            Self::Dup9 => const_text("dup.9"),
148            Self::Dup10 => const_text("dup.10"),
149            Self::Dup11 => const_text("dup.11"),
150            Self::Dup12 => const_text("dup.12"),
151            Self::Dup13 => const_text("dup.13"),
152            Self::Dup14 => const_text("dup.14"),
153            Self::Dup15 => const_text("dup.15"),
154            Self::DupW0 => const_text("dupw.0"),
155            Self::DupW1 => const_text("dupw.1"),
156            Self::DupW2 => const_text("dupw.2"),
157            Self::DupW3 => const_text("dupw.3"),
158            Self::Swap1 => const_text("swap.1"),
159            Self::Swap2 => const_text("swap.2"),
160            Self::Swap3 => const_text("swap.3"),
161            Self::Swap4 => const_text("swap.4"),
162            Self::Swap5 => const_text("swap.5"),
163            Self::Swap6 => const_text("swap.6"),
164            Self::Swap7 => const_text("swap.7"),
165            Self::Swap8 => const_text("swap.8"),
166            Self::Swap9 => const_text("swap.9"),
167            Self::Swap10 => const_text("swap.10"),
168            Self::Swap11 => const_text("swap.11"),
169            Self::Swap12 => const_text("swap.12"),
170            Self::Swap13 => const_text("swap.13"),
171            Self::Swap14 => const_text("swap.14"),
172            Self::Swap15 => const_text("swap.15"),
173            Self::SwapW1 => const_text("swapw.1"),
174            Self::SwapW2 => const_text("swapw.2"),
175            Self::SwapW3 => const_text("swapw.3"),
176            Self::SwapDw => const_text("swapdw"),
177            Self::MovUp2 => const_text("movup.2"),
178            Self::MovUp3 => const_text("movup.3"),
179            Self::MovUp4 => const_text("movup.4"),
180            Self::MovUp5 => const_text("movup.5"),
181            Self::MovUp6 => const_text("movup.6"),
182            Self::MovUp7 => const_text("movup.7"),
183            Self::MovUp8 => const_text("movup.8"),
184            Self::MovUp9 => const_text("movup.9"),
185            Self::MovUp10 => const_text("movup.10"),
186            Self::MovUp11 => const_text("movup.11"),
187            Self::MovUp12 => const_text("movup.12"),
188            Self::MovUp13 => const_text("movup.13"),
189            Self::MovUp14 => const_text("movup.14"),
190            Self::MovUp15 => const_text("movup.15"),
191            Self::MovUpW2 => const_text("movupw.2"),
192            Self::MovUpW3 => const_text("movupw.3"),
193            Self::MovDn2 => const_text("movdn.2"),
194            Self::MovDn3 => const_text("movdn.3"),
195            Self::MovDn4 => const_text("movdn.4"),
196            Self::MovDn5 => const_text("movdn.5"),
197            Self::MovDn6 => const_text("movdn.6"),
198            Self::MovDn7 => const_text("movdn.7"),
199            Self::MovDn8 => const_text("movdn.8"),
200            Self::MovDn9 => const_text("movdn.9"),
201            Self::MovDn10 => const_text("movdn.10"),
202            Self::MovDn11 => const_text("movdn.11"),
203            Self::MovDn12 => const_text("movdn.12"),
204            Self::MovDn13 => const_text("movdn.13"),
205            Self::MovDn14 => const_text("movdn.14"),
206            Self::MovDn15 => const_text("movdn.15"),
207            Self::MovDnW2 => const_text("movdnw.2"),
208            Self::MovDnW3 => const_text("movdnw.3"),
209            Self::Reversew => const_text("reversew"),
210            Self::Reversedw => const_text("reversedw"),
211            Self::CSwap => const_text("cswap"),
212            Self::CSwapW => const_text("cswapw"),
213            Self::CDrop => const_text("cdrop"),
214            Self::CDropW => const_text("cdropw"),
215
216            // ----- input / output operations ----------------------------------------------------
217            Self::Push(value) => inst_with_imm("push", value),
218            Self::PushSlice(value, range) => flatten(
219                const_text("push.")
220                    + value.render()
221                    + const_text("[")
222                    + display(range.start)
223                    + const_text("..")
224                    + display(range.end)
225                    + const_text("]"),
226            ),
227            Self::PushFeltList(values) => inst_with_pretty_felt_params("push", values),
228            Self::Locaddr(value) => inst_with_imm("locaddr", value),
229            Self::Sdepth => const_text("sdepth"),
230            Self::Caller => const_text("caller"),
231            Self::Clk => const_text("clk"),
232
233            Self::MemLoad => const_text("mem_load"),
234            Self::MemLoadImm(value) => inst_with_imm("mem_load", value),
235            Self::MemLoadWBe => const_text("mem_loadw_be"),
236            Self::MemLoadWBeImm(value) => inst_with_imm("mem_loadw_be", value),
237            Self::MemLoadWLe => const_text("mem_loadw_le"),
238            Self::MemLoadWLeImm(value) => inst_with_imm("mem_loadw_le", value),
239            Self::LocLoad(value) => inst_with_imm("loc_load", value),
240            Self::LocLoadWBe(value) => inst_with_imm("loc_loadw_be", value),
241            Self::LocLoadWLe(value) => inst_with_imm("loc_loadw_le", value),
242
243            Self::MemStore => const_text("mem_store"),
244            Self::MemStoreImm(value) => inst_with_imm("mem_store", value),
245            Self::MemStoreWBe => const_text("mem_storew_be"),
246            Self::MemStoreWBeImm(value) => inst_with_imm("mem_storew_be", value),
247            Self::MemStoreWLe => const_text("mem_storew_le"),
248            Self::MemStoreWLeImm(value) => inst_with_imm("mem_storew_le", value),
249            Self::LocStore(value) => inst_with_imm("loc_store", value),
250            Self::LocStoreWBe(value) => inst_with_imm("loc_storew_be", value),
251            Self::LocStoreWLe(value) => inst_with_imm("loc_storew_le", value),
252
253            Self::MemStream => const_text("mem_stream"),
254            Self::AdvPipe => const_text("adv_pipe"),
255
256            Self::AdvPush(value) => inst_with_imm("adv_push", value),
257            Self::AdvLoadW => const_text("adv_loadw"),
258
259            Self::SysEvent(sys_event) => inst_with_imm("adv", sys_event),
260
261            // ----- cryptographic operations -----------------------------------------------------
262            Self::Hash => const_text("hash"),
263            Self::HMerge => const_text("hmerge"),
264            Self::HPerm => const_text("hperm"),
265            Self::MTreeGet => const_text("mtree_get"),
266            Self::MTreeSet => const_text("mtree_set"),
267            Self::MTreeMerge => const_text("mtree_merge"),
268            Self::MTreeVerify => const_text("mtree_verify"),
269            Self::MTreeVerifyWithError(err_code) => flatten(
270                const_text("mtree_verify.err") + const_text("=") + text(format!("\"{err_code}\"")),
271            ),
272            Self::CryptoStream => const_text("crypto_stream"),
273
274            // ----- STARK proof verification -----------------------------------------------------
275            Self::FriExt2Fold4 => const_text("fri_ext2fold4"),
276            Self::HornerBase => const_text("horner_eval_base"),
277            Self::HornerExt => const_text("horner_eval_ext"),
278            Self::EvalCircuit => const_text("eval_circuit"),
279            Self::LogPrecompile => const_text("log_precompile"),
280
281            // ----- exec / call ------------------------------------------------------------------
282            Self::Exec(InvocationTarget::MastRoot(root)) => flatten(
283                const_text("exec")
284                    + const_text(".")
285                    + text(format!("{:#x}", DisplayHex(root.as_bytes().as_slice()))),
286            ),
287            Self::Exec(InvocationTarget::Symbol(name)) => {
288                flatten(const_text("exec") + const_text(".") + text(name))
289            },
290            Self::Exec(InvocationTarget::Path(path)) => {
291                const_text("exec") + const_text(".") + display(path)
292            },
293            Self::Call(InvocationTarget::MastRoot(root)) => {
294                const_text("call")
295                    + const_text(".")
296                    + text(format!("{:#x}", DisplayHex(root.as_bytes().as_slice())))
297            },
298            Self::Call(InvocationTarget::Symbol(name)) => {
299                flatten(const_text("call") + const_text(".") + text(name))
300            },
301            Self::Call(InvocationTarget::Path(path)) => {
302                const_text("call") + const_text(".") + display(path)
303            },
304            Self::SysCall(InvocationTarget::MastRoot(root)) => {
305                const_text("syscall")
306                    + const_text(".")
307                    + text(format!("{:#x}", DisplayHex(root.as_bytes().as_slice())))
308            },
309            Self::SysCall(InvocationTarget::Symbol(name)) => {
310                flatten(const_text("syscall") + const_text(".") + text(format!("{name}")))
311            },
312            Self::SysCall(InvocationTarget::Path(path)) => {
313                const_text("syscall") + const_text(".") + display(path)
314            },
315            Self::DynExec => const_text("dynexec"),
316            Self::DynCall => const_text("dyncall"),
317            Self::ProcRef(InvocationTarget::MastRoot(_)) => {
318                panic!("invalid procref instruction: expected name not MAST root")
319            },
320            Self::ProcRef(InvocationTarget::Symbol(name)) => {
321                flatten(const_text("procref") + const_text(".") + text(name))
322            },
323            Self::ProcRef(InvocationTarget::Path(path)) => {
324                flatten(const_text("procref") + const_text(".") + display(path))
325            },
326
327            // ----- debug decorators -------------------------------------------------------------
328            Self::Debug(options) => inst_with_imm("debug", options),
329
330            // ----- event decorators -------------------------------------------------------------
331            Self::Emit => const_text("emit"),
332            Self::EmitImm(value) => inst_with_felt_imm("emit", value),
333            Self::Trace(value) => inst_with_imm("trace", value),
334        }
335    }
336}
337
338fn inst_with_imm(name: &'static str, imm: &dyn PrettyPrint) -> Document {
339    use crate::prettier::*;
340
341    let imm = imm.render();
342
343    flatten(const_text(name) + const_text(".") + imm)
344}
345
346fn inst_with_felt_imm(name: &'static str, imm: &Immediate<crate::Felt>) -> Document {
347    use crate::prettier::*;
348
349    let value = match imm {
350        Immediate::Value(value) => display(*value),
351        Immediate::Constant(name) => text(name),
352    };
353
354    flatten(const_text(name) + const_text(".") + value)
355}
356
357fn inst_with_pretty_felt_params(inst: &'static str, params: &[crate::Felt]) -> Document {
358    use crate::prettier::*;
359
360    let single_line = text(inst)
361        + const_text(".")
362        + params
363            .iter()
364            .copied()
365            .map(display)
366            .reduce(|acc, doc| acc + const_text(".") + doc)
367            .unwrap_or_default();
368
369    let multi_line = params
370        .iter()
371        .copied()
372        .map(|v| text(inst) + const_text(".") + display(v))
373        .reduce(|acc, doc| acc + nl() + doc)
374        .unwrap_or_default();
375    single_line | multi_line
376}
377
378// TESTS
379// ================================================================================================
380
381#[cfg(test)]
382mod tests {
383    use miden_core::crypto::hash::Poseidon2;
384    use miden_debug_types::Span;
385
386    use crate::{Felt, ast::*};
387
388    #[test]
389    fn test_instruction_display() {
390        let instruction = format!("{}", Instruction::Assert);
391        assert_eq!("assert", instruction);
392
393        let instruction = format!("{}", Instruction::Add);
394        assert_eq!("add", instruction);
395
396        let instruction = format!("{}", Instruction::AddImm(Felt::new(5).into()));
397        assert_eq!("add.5", instruction);
398
399        let instruction = format!("{}", Instruction::ExpBitLength(32));
400        assert_eq!("exp.u32", instruction);
401
402        let instruction = format!(
403            "{}",
404            Instruction::PushFeltList(vec![Felt::new(3), Felt::new(4), Felt::new(8), Felt::new(9)])
405        );
406        assert_eq!("push.3.4.8.9", instruction);
407        let instruction = format!(
408            "{}",
409            Instruction::Push(Immediate::Value(miden_debug_types::Span::unknown(
410                crate::parser::PushValue::Int(crate::parser::IntValue::U8(3))
411            )))
412        );
413        assert_eq!("push.3", instruction);
414
415        let digest = Poseidon2::hash(b"miden::core::math::u64::add");
416        let target = InvocationTarget::MastRoot(Span::unknown(digest));
417        let instruction = format!("{}", Instruction::Exec(target));
418        assert_eq!(
419            "exec.0x065c394c00227acff3545da5493cf1b79d9a9f5628db553d240edf8ef0cca04a",
420            instruction
421        );
422    }
423}