miden-assembly 0.32.0

Miden VM assembly language
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
// DEBUG INFO
// ================================================================================================

use super::*;

fn replace_nops_with_named_inline_call_markers(
    context: &TestContext,
    procedure: &mut Procedure,
    markers: &[Option<&str>],
) -> Result<(), Report> {
    use miden_assembly_syntax::ast::DebugInlineCallInfo;

    let mut markers = markers.iter();
    for op in procedure.body_mut().iter_mut() {
        let Op::Inst(instruction) = op else {
            continue;
        };
        if !matches!(instruction.inner(), Instruction::Nop) {
            continue;
        }
        let Some(marker) = markers.next() else {
            break;
        };

        let span = instruction.span();
        let replacement = match marker {
            Some(name) => {
                let source_location = context
                    .source_manager()
                    .file_line_col(span)
                    .map_err(|error| Report::msg(error.to_string()))?;
                Instruction::DebugInlineCall(DebugInlineCallInfo::new(
                    *name,
                    source_location.clone(),
                    source_location,
                ))
            },
            None => Instruction::DebugInlineCallClear,
        };
        *op = Op::Inst(Span::new(span, replacement));
    }

    assert!(markers.next().is_none(), "test fixture has too few marker placeholders");
    Ok(())
}

fn reachable_source_nodes(
    debug_info: &miden_mast_package::debug_info::PackageDebugInfo,
    root: miden_mast_package::debug_info::DebugSourceNodeId,
) -> BTreeSet<miden_mast_package::debug_info::DebugSourceNodeId> {
    let mut reachable = BTreeSet::new();
    let mut worklist = vec![root];
    while let Some(source_node_id) = worklist.pop() {
        if reachable.insert(source_node_id) {
            worklist.extend(debug_info[source_node_id].children.iter().copied());
        }
    }
    reachable
}

#[test]
fn inline_call_chains_are_recorded_on_call_and_structured_control_occurrences() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "
        proc callee
            add
        end

        begin
            nop
            nop
            call.callee
            nop
            nop
            if.true
                add
            else
                mul
            end
        end
        "
    );
    let mut module = context.parse_module(source)?;
    let entrypoint = module
        .procedures_mut()
        .find(|procedure| procedure.is_entrypoint())
        .expect("executable module should contain an entrypoint");
    replace_nops_with_named_inline_call_markers(
        &context,
        entrypoint,
        &[None, Some("source::inlined"), None, Some("source::inlined")],
    )?;

    let package = Assembler::new(context.source_manager()).assemble_program("test", module)?;
    let debug_info = package
        .debug_info()
        .into_diagnostic()?
        .expect("assembled package should contain debug info");

    for expected_op in ["call.", "if.true"] {
        let source_node = debug_info
            .nodes()
            .iter()
            .find(|source_node| {
                source_node
                    .asm_ops
                    .iter()
                    .any(|asm_op| debug_info[asm_op.op_name_idx].starts_with(expected_op))
            })
            .unwrap_or_else(|| panic!("missing source occurrence for {expected_op}"));
        let inline_calls = source_node
            .inline_calls
            .iter()
            .filter(|inline_call| inline_call.op_idx == 0)
            .collect::<Vec<_>>();

        assert_eq!(inline_calls.len(), 1, "{expected_op} should retain its inline chain");
        let function = debug_info
            .get_function(inline_calls[0].callee_idx)
            .expect("inline callee should be registered");
        assert_eq!(debug_info[function.name_idx].as_ref(), "source::inlined");
    }

    Ok(())
}

#[test]
fn inline_call_chains_cover_exec_source_occurrences() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "
        proc callee
            add
            mul
        end

        begin
            nop
            nop
            exec.callee
            nop
            nop
            exec.callee
        end
        "
    );
    let mut module = context.parse_module(source)?;
    let entrypoint = module
        .procedures_mut()
        .find(|procedure| procedure.is_entrypoint())
        .expect("executable module should contain an entrypoint");
    replace_nops_with_named_inline_call_markers(
        &context,
        entrypoint,
        &[None, Some("source::inlined"), None, Some("source::inlined")],
    )?;

    let package = Assembler::new(context.source_manager()).assemble_program("test", module)?;
    let debug_info = package
        .debug_info()
        .into_diagnostic()?
        .expect("assembled package should contain debug info");

    let callee_source = debug_info
        .nodes()
        .iter()
        .find(|source_node| {
            source_node
                .asm_ops
                .iter()
                .any(|asm_op| debug_info[asm_op.context_name_idx].contains("callee"))
                && !source_node.inline_calls.is_empty()
        })
        .expect("exec target should have a decorated source occurrence");
    for asm_op in callee_source
        .asm_ops
        .iter()
        .filter(|asm_op| debug_info[asm_op.context_name_idx].contains("callee"))
    {
        assert_eq!(
            callee_source
                .inline_calls
                .iter()
                .filter(|inline_call| inline_call.op_idx == asm_op.op_idx)
                .count(),
            1,
            "every operation in the exec target should retain the active inline chain",
        );
    }

    Ok(())
}

#[test]
fn exec_occurrences_do_not_reuse_stale_inline_chains() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "
        proc callee
            add
            mul
        end

        begin
            nop
            nop
            exec.callee
            nop
            exec.callee
        end
        "
    );
    let mut module = context.parse_module(source)?;
    let entrypoint = module
        .procedures_mut()
        .find(|procedure| procedure.is_entrypoint())
        .expect("executable module should contain an entrypoint");
    replace_nops_with_named_inline_call_markers(
        &context,
        entrypoint,
        &[None, Some("source::decorated"), None],
    )?;

    let package = Assembler::new(context.source_manager()).assemble_program("test", module)?;
    let debug_info = package
        .debug_info()
        .into_diagnostic()?
        .expect("assembled package should contain debug info");
    let entrypoint_source = package
        .entrypoint_source_node()
        .expect("executable should identify its entrypoint source occurrence");
    let reachable = reachable_source_nodes(&debug_info, entrypoint_source);
    let mut inline_counts = Vec::new();
    for source_node_id in reachable {
        for asm_op in &debug_info[source_node_id].asm_ops {
            if debug_info[asm_op.context_name_idx].contains("callee") {
                inline_counts.push(
                    debug_info.inline_calls_for_operation(source_node_id, asm_op.op_idx).count(),
                );
            }
        }
    }
    assert_eq!(
        inline_counts,
        [1, 1, 0, 0],
        "the plain exec must not inherit the earlier inline chain",
    );

    Ok(())
}

#[test]
fn nested_exec_inline_chains_are_innermost_first() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "
        proc inner
            add
        end

        proc outer_target
            nop
            nop
            exec.inner
        end

        begin
            nop
            nop
            exec.outer_target
        end
        "
    );
    let mut module = context.parse_module(source)?;
    for procedure in module.procedures_mut() {
        if procedure.is_entrypoint() {
            replace_nops_with_named_inline_call_markers(
                &context,
                procedure,
                &[None, Some("source::outer")],
            )?;
        } else if procedure.name().as_str() == "outer_target" {
            replace_nops_with_named_inline_call_markers(
                &context,
                procedure,
                &[None, Some("source::inner")],
            )?;
        }
    }

    let package = Assembler::new(context.source_manager()).assemble_program("test", module)?;
    let debug_info = package
        .debug_info()
        .into_diagnostic()?
        .expect("assembled package should contain debug info");
    let entrypoint_source = package
        .entrypoint_source_node()
        .expect("executable should identify its entrypoint source occurrence");
    let reachable = reachable_source_nodes(&debug_info, entrypoint_source);
    let inner_source = reachable
        .into_iter()
        .find(|source_node_id| {
            debug_info[*source_node_id].asm_ops.iter().any(|asm_op| {
                debug_info[asm_op.context_name_idx].contains("inner")
                    && debug_info[asm_op.op_name_idx].as_ref() == "add"
            })
        })
        .expect("nested exec target should be reachable from the entrypoint");
    let inner_op = debug_info[inner_source]
        .asm_ops
        .iter()
        .find(|asm_op| debug_info[asm_op.op_name_idx].as_ref() == "add")
        .expect("inner target should contain add");
    let names = debug_info
        .inline_calls_for_operation(inner_source, inner_op.op_idx)
        .map(|inline_call| {
            let function = debug_info
                .get_function(inline_call.callee_idx)
                .expect("inline callee should be registered");
            debug_info[function.name_idx].to_string()
        })
        .collect::<Vec<_>>();

    assert_eq!(names, ["source::inner", "source::outer"]);
    Ok(())
}

#[test]
fn external_exec_records_inline_context_at_the_boundary() -> TestResult {
    let context = TestContext::default();
    let library_module = context.parse_module(
        "
        namespace dep::math

        pub proc callee
            add
        end
        ",
    )?;
    let library = Assembler::new(context.source_manager()).assemble_library(
        "dep",
        library_module,
        None::<Box<Module>>,
    )?;
    let assembler = Assembler::new(context.source_manager())
        .with_package(Arc::from(library), Linkage::Dynamic)?;
    let source = source_file!(
        &context,
        "
        use dep::math

        begin
            nop
            nop
            exec.math::callee
        end
        "
    );
    let mut module = context.parse_module(source)?;
    let entrypoint = module
        .procedures_mut()
        .find(|procedure| procedure.is_entrypoint())
        .expect("executable module should contain an entrypoint");
    replace_nops_with_named_inline_call_markers(
        &context,
        entrypoint,
        &[None, Some("source::external")],
    )?;

    let package = assembler.assemble_program("test", module)?;
    let debug_info = package
        .debug_info()
        .into_diagnostic()?
        .expect("assembled package should contain debug info");
    let external_source = debug_info
        .nodes()
        .iter()
        .find(|source_node| {
            package.mast_forest()[source_node.exec_node].is_external()
                && !source_node.inline_calls.is_empty()
        })
        .expect("decorated external exec should carry boundary inline context");

    assert_eq!(external_source.op_start, external_source.op_end);
    assert!(
        external_source
            .inline_calls
            .iter()
            .all(|inline_call| inline_call.op_idx == external_source.op_start)
    );
    Ok(())
}

#[test]
fn source_name_attribute_sets_debug_name_and_linkage_name() -> TestResult {
    let context = TestContext::default();
    let module = context.parse_module(source_file!(
        &context,
        r#"
        namespace debug::names

        @source_name("duplicate")
        pub proc first
            push.1
        end

        @source_name("duplicate")
        pub proc second
            push.2
        end

        pub proc normal
            push.3
        end
        "#
    ))?;
    let package = Assembler::new(context.source_manager()).assemble_library(
        "debug-names",
        module,
        None::<Box<Module>>,
    )?;

    let assert_function_names = |package: &Package| {
        let debug_info = package
            .debug_info()
            .expect("package debug info should decode")
            .expect("package should contain debug info");
        let duplicate_functions = debug_info
            .functions()
            .iter()
            .filter(|function| {
                debug_info[function.name_idx].as_ref() == "::debug::names::duplicate"
            })
            .collect::<Vec<_>>();

        assert_eq!(duplicate_functions.len(), 2);
        assert_eq!(duplicate_functions[0].name_idx, duplicate_functions[1].name_idx);
        let linkage_names = duplicate_functions
            .iter()
            .map(|function| {
                let linkage_name_idx = function
                    .linkage_name_idx
                    .into_option()
                    .expect("source-named function should have a linkage name");
                debug_info[linkage_name_idx].to_string()
            })
            .collect::<BTreeSet<_>>();
        assert_eq!(linkage_names.len(), 2);
        assert!(linkage_names.iter().any(|name| name.ends_with("::first")));
        assert!(linkage_names.iter().any(|name| name.ends_with("::second")));

        let normal = debug_info
            .functions()
            .iter()
            .find(|function| debug_info[function.name_idx].ends_with("::normal"))
            .expect("normal function should retain its assembler path as its name");
        assert_eq!(normal.linkage_name_idx.into_option(), None);
    };

    assert_function_names(&package);
    let round_tripped = Package::read_from_bytes(&package.to_bytes())
        .expect("package with source-named functions should round trip");
    assert_function_names(&round_tripped);

    Ok(())
}

#[test]
fn malformed_source_name_attributes_are_rejected() -> TestResult {
    let context = TestContext::default();

    for attribute in [
        "@source_name",
        "@source_name(unquoted)",
        "@source_name(\"one\", \"two\")",
        "@source_name(value = \"named\")",
    ] {
        let source = source_file!(
            &context,
            format!(
                r#"
                namespace debug::invalid

                {attribute}
                pub proc test
                    nop
                end
                "#
            )
        );
        let module = context.parse_module(source)?;
        let error = Assembler::new(context.source_manager())
            .assemble_library("invalid-source-name", module, None::<Box<Module>>)
            .expect_err("malformed @source_name should be rejected");
        assert_diagnostic!(&error, "invalid `@source_name` procedure attribute");
        assert_diagnostic!(&error, "expected exactly one quoted string");
    }

    Ok(())
}