miden-core-lib 0.24.0

Miden VM core library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! Tests for the `miden::core::debug` print-debugging module.
//!
//! Each test runs a small program through the VM with a [`DebugPrinter`] writing into an in-memory
//! buffer (instead of stdout). The capture tests assert on the printed text; the stack-effect
//! tests assert on the resulting operand stack.

use std::{
    fmt,
    sync::{Arc, Mutex},
};

use miden_assembly::{Assembler, Linkage};
use miden_core::{Felt, Word};
use miden_core_lib::{
    CoreLibrary,
    handlers::debug::{
        DebugPrinter, PRINT_ADV_MAP_EVENT_NAME, PRINT_ADV_MAP_ITEM_EVENT_NAME,
        PRINT_ADV_STACK_EVENT_NAME, PRINT_MEM_ALL_EVENT_NAME, PRINT_MEM_EVENT_NAME,
        PRINT_STACK_EVENT_NAME, advice_debug_handlers, debug_handlers, noop_debug_handlers,
    },
};
use miden_processor::{
    DefaultHost, ExecutionError, ExecutionOptions, ExecutionOutput, HostLibrary, MemoryError,
    StackInputs,
    advice::AdviceInputs,
    event::{EventHandler, EventName},
    execute_sync,
};

// HARNESS
// ================================================================================================

/// A [`fmt::Write`] that appends into a shared, thread-safe string buffer.
#[derive(Clone)]
struct SharedBuf(Arc<Mutex<String>>);

impl fmt::Write for SharedBuf {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.0.lock().unwrap().push_str(s);
        Ok(())
    }
}

fn debug_handlers_with_writer(writer: SharedBuf) -> Vec<(EventName, Arc<dyn EventHandler>)> {
    let printer: Arc<dyn EventHandler> = Arc::new(DebugPrinter::new(writer));
    vec![
        (PRINT_STACK_EVENT_NAME, printer.clone()),
        (PRINT_MEM_EVENT_NAME, printer.clone()),
        (PRINT_MEM_ALL_EVENT_NAME, printer.clone()),
        (PRINT_ADV_STACK_EVENT_NAME, printer.clone()),
        (PRINT_ADV_MAP_EVENT_NAME, printer.clone()),
        (PRINT_ADV_MAP_ITEM_EVENT_NAME, printer),
    ]
}

/// Assembles `source` against the core library and executes it with a [`DebugPrinter`] writing
/// into an in-memory buffer (rather than the default stdout one), returning everything printed by
/// the `print_*` events along with the execution output.
fn run(source: &str, advice: AdviceInputs) -> (String, ExecutionOutput) {
    let core_lib = CoreLibrary::default();
    let assembler = Assembler::default()
        .with_package(core_lib.package(), Linkage::Dynamic)
        .expect("failed to load core library");
    let program = assembler
        .assemble_program("program", source)
        .expect("failed to assemble program")
        .unwrap_program();

    let buf = Arc::new(Mutex::new(String::new()));
    let host_lib = HostLibrary {
        mast_forest: core_lib.mast_forest().clone(),
        package_debug_info: Ok(None),
        handlers: debug_handlers_with_writer(SharedBuf(buf.clone())),
    };
    let mut host = DefaultHost::default().with_library(host_lib).expect("failed to load host lib");

    let output = execute_sync(
        &program,
        StackInputs::default(),
        advice,
        &mut host,
        ExecutionOptions::default(),
    )
    .expect("execution failed");

    let captured = buf.lock().unwrap().clone();
    // Echo to stdout so the debug output is visible when running with `cargo test -- --nocapture`
    // (cargo hides stdout for passing tests otherwise).
    print!("{captured}");
    (captured, output)
}

/// Convenience wrapper returning only the captured text.
fn run_and_capture(source: &str, advice: AdviceInputs) -> String {
    run(source, advice).0
}

/// Executes `source` against the core library's default host-library conversion. This exercises
/// the production handler registration path, while capture tests use a custom in-memory printer.
fn run_with_default_core_handlers(source: &str, advice: AdviceInputs) -> ExecutionOutput {
    let core_lib = CoreLibrary::default();
    let assembler = Assembler::default()
        .with_package(core_lib.package(), Linkage::Dynamic)
        .expect("failed to load core library");
    let program = assembler
        .assemble_program("program", source)
        .expect("failed to assemble program")
        .unwrap_program();
    let mut host = DefaultHost::default()
        .with_library(&core_lib)
        .expect("failed to load core library handlers");

    execute_sync(&program, StackInputs::default(), advice, &mut host, ExecutionOptions::default())
        .expect("execution failed")
}

// CAPTURE TESTS
// ================================================================================================

#[test]
fn print_stack_outputs_operand_stack() {
    let source = "
    use miden::core::debug
    begin
        push.1 push.2 push.3
        exec.debug::print_stack
        drop drop drop
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("Stack state"), "missing header; got:\n{out}");
    // top three elements are 3, 2, 1 (the event id must NOT be shown)
    assert!(
        out.contains(": 3") && out.contains(": 2") && out.contains(": 1"),
        "missing operand values; got:\n{out}"
    );
}

#[test]
fn print_mem_outputs_range() {
    let source = "
    use miden::core::debug
    begin
        push.42 push.100 mem_store
        push.43 push.101 mem_store
        push.102 push.100   # [start=100, end=102]
        exec.debug::print_mem
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("Memory state"), "missing header; got:\n{out}");
    assert!(out.contains("42") && out.contains("43"), "missing memory values; got:\n{out}");
}

#[test]
fn print_mem_reports_empty_range() {
    // An explicit empty range (`start == end`) hits the empty branch and must not panic; this
    // guards the `start == end == 0` underflow path when converting to the inclusive range.
    let source = "
    use miden::core::debug
    begin
        push.0 push.0   # [start=0, end=0]
        exec.debug::print_mem
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("range is empty"), "expected empty-range message; got:\n{out}");
}

#[test]
fn print_mem_addr_outputs_procedure_local() {
    // Exercises the intended use case: `locaddr` turns a procedure local into an absolute
    // address that `print_mem_addr` can print.
    let source = "
    use miden::core::debug
    @locals(1)
    proc with_local
        push.42 loc_store.0
        locaddr.0
        exec.debug::print_mem_addr
    end
    begin
        exec.with_local
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("Memory state"), "missing header; got:\n{out}");
    assert!(out.contains("42"), "missing memory value; got:\n{out}");
}

#[test]
fn print_mem_addr_reports_uninitialized_cell() {
    let source = "
    use miden::core::debug
    begin
        push.100
        exec.debug::print_mem_addr
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("Memory state"), "missing header; got:\n{out}");
    assert!(out.contains("0x00000064: EMPTY"), "expected EMPTY cell; got:\n{out}");
}

#[test]
fn print_mem_shows_uninitialized_cells_as_empty() {
    // Every address in an explicit range is enumerated, with uninitialized cells shown as EMPTY,
    // so gaps in the range don't silently disappear.
    let source = "
    use miden::core::debug
    begin
        push.42 push.100 mem_store
        push.110 push.100   # [start=100, end=110)
        exec.debug::print_mem
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("0x00000064: 42"), "missing stored value; got:\n{out}");
    // The `mem_store` initialized the whole word at addresses 100..104; the rest of the requested
    // range is untouched and must still be listed, as EMPTY.
    for addr in 104..110u32 {
        assert!(
            out.contains(&format!("{addr:#010x}: EMPTY")),
            "missing EMPTY cell at {addr}; got:\n{out}"
        );
    }
}

#[test]
fn print_mem_all_outputs_memory() {
    let source = "
    use miden::core::debug
    begin
        push.7 push.200 mem_store
        exec.debug::print_mem_all
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("Memory state"), "missing header; got:\n{out}");
    assert!(out.contains(": 7"), "missing stored value; got:\n{out}");
}

#[test]
fn print_mem_addr_prints_max_u32_cell() {
    // Regression: `print_mem_addr` builds the range `[addr, addr+1)`. At `addr == u32::MAX` the
    // exclusive end is `2^32`, which used to be rejected and aborted execution. It must now print
    // the cell.
    let source = "
    use miden::core::debug
    begin
        push.42 push.4294967295 mem_store
        push.4294967295
        exec.debug::print_mem_addr
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("Memory state"), "missing header; got:\n{out}");
    assert!(out.contains("42"), "missing memory value at u32::MAX; got:\n{out}");
}

#[test]
fn print_mem_all_includes_max_u32_cell() {
    // Regression: `print_mem_all` lists every initialized cell, so the cell at `u32::MAX` is no
    // longer silently excluded.
    let source = "
    use miden::core::debug
    begin
        push.42 push.4294967295 mem_store
        exec.debug::print_mem_all
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("Memory state"), "missing header; got:\n{out}");
    assert!(out.contains("42"), "missing memory value at u32::MAX; got:\n{out}");
}

#[test]
fn print_mem_rejects_out_of_bounds_range_end() {
    let source = "
    use miden::core::debug
    begin
        push.18446744069414584320 push.0
        exec.debug::print_mem
    end
    ";

    let core_lib = CoreLibrary::default();
    let assembler = Assembler::default()
        .with_package(core_lib.package(), Linkage::Dynamic)
        .expect("failed to load core library");
    let program = assembler
        .assemble_program("program", source)
        .expect("failed to assemble program")
        .unwrap_program();
    let host_lib = HostLibrary {
        mast_forest: core_lib.mast_forest().clone(),
        package_debug_info: Ok(None),
        handlers: debug_handlers_with_writer(SharedBuf(Arc::new(Mutex::new(String::new())))),
    };
    let mut host = DefaultHost::default().with_library(host_lib).expect("failed to load host lib");

    match execute_sync(
        &program,
        StackInputs::default(),
        AdviceInputs::default(),
        &mut host,
        ExecutionOptions::default(),
    ) {
        Err(ExecutionError::EventError { error, .. }) => {
            let err = error.downcast_ref::<MemoryError>().expect("expected a MemoryError");
            assert!(matches!(err, MemoryError::AddressOutOfBounds { .. }));
        },
        Err(err) => panic!("unexpected error type: {err:?}"),
        Ok(_) => panic!("out-of-bounds print_mem range should fail"),
    }
}

#[test]
fn print_mem_rejects_oversized_range() {
    // An explicit range wider than the 1024-address cap is rejected, catching a caller that passes
    // a huge range by accident. Use `print_mem_all` to print the entire memory.
    let source = "
    use miden::core::debug
    begin
        push.1025 push.0
        exec.debug::print_mem
    end
    ";

    let core_lib = CoreLibrary::default();
    let assembler = Assembler::default()
        .with_package(core_lib.package(), Linkage::Dynamic)
        .expect("failed to load core library");
    let program = assembler
        .assemble_program("program", source)
        .expect("failed to assemble program")
        .unwrap_program();
    let host_lib = HostLibrary {
        mast_forest: core_lib.mast_forest().clone(),
        package_debug_info: Ok(None),
        handlers: debug_handlers_with_writer(SharedBuf(Arc::new(Mutex::new(String::new())))),
    };
    let mut host = DefaultHost::default().with_library(host_lib).expect("failed to load host lib");

    match execute_sync(
        &program,
        StackInputs::default(),
        AdviceInputs::default(),
        &mut host,
        ExecutionOptions::default(),
    ) {
        Err(ExecutionError::EventError { error, .. }) => {
            assert_eq!(error.to_string(), "print_mem range length 1025 exceeds maximum of 1024");
        },
        Err(err) => panic!("unexpected error type: {err:?}"),
        Ok(_) => panic!("oversized print_mem range should fail"),
    }
}

#[test]
fn print_mem_rejects_full_range() {
    // The cap has no exemption: the full `[0, 2^32)` range is rejected like any other oversized
    // range, so `print_mem` can't be used to bypass the documented 1024-address limit. Printing
    // the entire memory is `print_mem_all`'s job (it uses a dedicated event).
    let source = "
    use miden::core::debug
    begin
        push.4294967296 push.0
        exec.debug::print_mem
    end
    ";

    let core_lib = CoreLibrary::default();
    let assembler = Assembler::default()
        .with_package(core_lib.package(), Linkage::Dynamic)
        .expect("failed to load core library");
    let program = assembler
        .assemble_program("program", source)
        .expect("failed to assemble program")
        .unwrap_program();
    let host_lib = HostLibrary {
        mast_forest: core_lib.mast_forest().clone(),
        package_debug_info: Ok(None),
        handlers: debug_handlers_with_writer(SharedBuf(Arc::new(Mutex::new(String::new())))),
    };
    let mut host = DefaultHost::default().with_library(host_lib).expect("failed to load host lib");

    match execute_sync(
        &program,
        StackInputs::default(),
        AdviceInputs::default(),
        &mut host,
        ExecutionOptions::default(),
    ) {
        Err(ExecutionError::EventError { error, .. }) => {
            assert_eq!(
                error.to_string(),
                "print_mem range length 4294967296 exceeds maximum of 1024"
            );
        },
        Err(err) => panic!("unexpected error type: {err:?}"),
        Ok(_) => panic!("full-range print_mem should fail"),
    }
}

#[test]
fn print_adv_stack_all_outputs_advice_stack() {
    let advice = AdviceInputs::default().with_stack([
        Felt::new_unchecked(7),
        Felt::new_unchecked(8),
        Felt::new_unchecked(9),
    ]);
    let source = "
    use miden::core::debug
    begin
        exec.debug::print_adv_stack_all
    end
    ";
    let out = run_and_capture(source, advice);
    assert!(out.contains("Advice stack state"), "missing header; got:\n{out}");
    assert!(
        out.contains(": 7") && out.contains(": 8") && out.contains(": 9"),
        "missing advice stack values; got:\n{out}"
    );
}

#[test]
fn print_adv_stack_outputs_range() {
    let advice = AdviceInputs::default().with_stack([
        Felt::new_unchecked(7),
        Felt::new_unchecked(8),
        Felt::new_unchecked(9),
        Felt::new_unchecked(10),
    ]);
    let source = "
    use miden::core::debug
    begin
        push.3 push.1   # [start=1, end=3]
        exec.debug::print_adv_stack
    end
    ";
    let out = run_and_capture(source, advice);
    assert!(out.contains("Advice stack state"), "missing header; got:\n{out}");
    assert!(
        out.contains(": 8") && out.contains(": 9") && !out.contains(": 7") && !out.contains(": 10"),
        "unexpected advice stack range; got:\n{out}"
    );
}

#[test]
fn print_adv_map_all_outputs_entries() {
    let key_a = Word::new([
        Felt::new_unchecked(1),
        Felt::new_unchecked(2),
        Felt::new_unchecked(3),
        Felt::new_unchecked(4),
    ]);
    let key_b = Word::new([
        Felt::new_unchecked(5),
        Felt::new_unchecked(6),
        Felt::new_unchecked(7),
        Felt::new_unchecked(8),
    ]);
    let advice = AdviceInputs::default().with_map([
        (key_a, vec![Felt::new_unchecked(10), Felt::new_unchecked(20)]),
        (key_b, vec![Felt::new_unchecked(30)]),
    ]);
    let source = "
    use miden::core::debug
    begin
        exec.debug::print_adv_map_all
    end
    ";
    let out = run_and_capture(source, advice);
    assert!(out.contains("Advice map before step"), "missing header; got:\n{out}");
    assert!(out.contains("[1, 2, 3, 4]"), "missing first key; got:\n{out}");
    assert!(out.contains("[5, 6, 7, 8]"), "missing second key; got:\n{out}");
    assert!(out.contains("[10, 20]") && out.contains("[30]"), "missing values; got:\n{out}");
}

#[test]
fn print_adv_map_item_outputs_values() {
    let key = Word::new([
        Felt::new_unchecked(1),
        Felt::new_unchecked(2),
        Felt::new_unchecked(3),
        Felt::new_unchecked(4),
    ]);
    let values = vec![Felt::new_unchecked(10), Felt::new_unchecked(20), Felt::new_unchecked(30)];
    let advice = AdviceInputs::default().with_map([(key, values)]);
    let source = "
    use miden::core::debug
    begin
        push.4 push.3 push.2 push.1   # KEY = [1, 2, 3, 4]
        exec.debug::print_adv_map_item
    end
    ";
    let out = run_and_capture(source, advice);
    assert!(out.contains("Advice map entry"), "missing header; got:\n{out}");
    assert!(
        out.contains(": 10") && out.contains(": 20") && out.contains(": 30"),
        "missing advice map values; got:\n{out}"
    );
}

#[test]
fn print_adv_map_item_reports_missing_key() {
    let source = "
    use miden::core::debug
    begin
        push.4 push.3 push.2 push.1
        exec.debug::print_adv_map_item
    end
    ";
    let out = run_and_capture(source, AdviceInputs::default());
    assert!(out.contains("No advice map entry"), "expected missing-key message; got:\n{out}");
}

// STACK-EFFECT TESTS
// ================================================================================================

// The VM requires the final operand stack to be at the minimum depth (16). A program that pushes
// exactly the procedure's arguments and then returns to that depth therefore proves the procedure
// consumed exactly those arguments — consuming a different number would either overflow the output
// stack or fail to balance.

#[test]
fn print_stack_is_stack_neutral() {
    // No arguments are pushed: `print_stack` must leave the stack untouched.
    let source = "
    use miden::core::debug
    begin
        exec.debug::print_stack
    end
    ";
    let (_, output) = run(source, AdviceInputs::default());
    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}

#[test]
fn default_core_handlers_include_debug_printers() {
    let core_lib = CoreLibrary::default();
    let handlers = core_lib.handlers();

    for debug_event in [PRINT_STACK_EVENT_NAME, PRINT_MEM_EVENT_NAME, PRINT_MEM_ALL_EVENT_NAME] {
        assert!(
            handlers.iter().any(|(event, _)| event == &debug_event),
            "{debug_event:?} should be registered by default"
        );
    }

    for debug_event in [
        PRINT_ADV_STACK_EVENT_NAME,
        PRINT_ADV_MAP_EVENT_NAME,
        PRINT_ADV_MAP_ITEM_EVENT_NAME,
    ] {
        assert!(
            !handlers.iter().any(|(event, _)| event == &debug_event),
            "{debug_event:?} should be registered explicitly by the host"
        );
    }
}

#[test]
fn debug_handlers_compose_with_default_core_handlers() {
    let source = "
    use miden::core::debug
    begin
        exec.debug::print_adv_stack_all
    end
    ";
    let advice = AdviceInputs::default().with_stack([Felt::new_unchecked(7)]);

    let core_lib = CoreLibrary::default();
    let assembler = Assembler::default()
        .with_package(core_lib.package(), Linkage::Dynamic)
        .expect("failed to load core library");
    let program = assembler
        .assemble_program("program", source)
        .expect("failed to assemble program")
        .unwrap_program();

    let mut handlers = core_lib.handlers();
    handlers.extend(advice_debug_handlers());
    let host_lib = HostLibrary {
        mast_forest: core_lib.mast_forest().clone(),
        package_debug_info: Ok(None),
        handlers,
    };
    let mut host = DefaultHost::default().with_library(host_lib).expect("failed to load host lib");

    let output = execute_sync(
        &program,
        StackInputs::default(),
        advice,
        &mut host,
        ExecutionOptions::default(),
    )
    .expect("execution failed");
    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}

#[test]
fn debug_handlers_include_all_core_debug_events() {
    let handlers = debug_handlers();

    for debug_event in [
        PRINT_STACK_EVENT_NAME,
        PRINT_MEM_EVENT_NAME,
        PRINT_MEM_ALL_EVENT_NAME,
        PRINT_ADV_STACK_EVENT_NAME,
        PRINT_ADV_MAP_EVENT_NAME,
        PRINT_ADV_MAP_ITEM_EVENT_NAME,
    ] {
        assert!(
            handlers.iter().any(|(event, _)| event == &debug_event),
            "{debug_event:?} should be registered by debug_handlers()"
        );
    }
}

#[test]
fn default_core_handlers_run_print_stack() {
    let source = "
    use miden::core::debug
    begin
        push.1 push.2 push.3
        exec.debug::print_stack
        drop drop drop
    end
    ";
    let output = run_with_default_core_handlers(source, AdviceInputs::default());
    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}

#[test]
fn noop_debug_handlers_run_print_stack_without_output() {
    let source = "
    use miden::core::debug
    begin
        push.1 push.2 push.3
        exec.debug::print_stack
        drop drop drop
    end
    ";

    let core_lib = CoreLibrary::default();
    let assembler = Assembler::default()
        .with_package(core_lib.package(), Linkage::Dynamic)
        .expect("failed to load core library");
    let program = assembler
        .assemble_program("program", source)
        .expect("failed to assemble program")
        .unwrap_program();
    let host_lib = HostLibrary {
        mast_forest: core_lib.mast_forest().clone(),
        package_debug_info: Ok(None),
        handlers: noop_debug_handlers(),
    };
    let mut host = DefaultHost::default().with_library(host_lib).expect("failed to load host lib");

    let output = execute_sync(
        &program,
        StackInputs::default(),
        AdviceInputs::default(),
        &mut host,
        ExecutionOptions::default(),
    )
    .expect("execution failed");

    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}

#[test]
fn print_mem_consumes_range_args() {
    // Pushes exactly two range args; clean termination proves both are consumed.
    let source = "
    use miden::core::debug
    begin
        push.8 push.0   # [start=0, end=8, ...]
        exec.debug::print_mem
    end
    ";
    let (_, output) = run(source, AdviceInputs::default());
    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}

#[test]
fn print_mem_addr_consumes_addr_arg() {
    // Pushes exactly one address arg; clean termination proves it is consumed.
    let source = "
    use miden::core::debug
    begin
        push.0   # [addr=0, ...]
        exec.debug::print_mem_addr
    end
    ";
    let (_, output) = run(source, AdviceInputs::default());
    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}

#[test]
fn print_adv_map_all_is_stack_neutral() {
    let source = "
    use miden::core::debug
    begin
        exec.debug::print_adv_map_all
    end
    ";
    let (_, output) = run(source, AdviceInputs::default());
    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}

#[test]
fn print_adv_map_item_consumes_key() {
    // Pushes exactly a 4-element key; clean termination proves the key is consumed.
    let source = "
    use miden::core::debug
    begin
        push.4 push.3 push.2 push.1   # KEY = [1, 2, 3, 4]
        exec.debug::print_adv_map_item
    end
    ";
    let (_, output) = run(source, AdviceInputs::default());
    assert_eq!(output.stack.get_element(0), Some(Felt::new_unchecked(0)));
}