miden-debug 0.10.1

An interactive debugger for Miden VM programs
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
use std::{io::Write, path::PathBuf};

use super::engine::Outcome;
use crate::{
    config::DebuggerConfig,
    script::{PythonScriptSession, ScriptDebugger},
};

pub(crate) fn project_init_file(config: &DebuggerConfig) -> Option<PathBuf> {
    if config.no_user_python_init {
        return None;
    }

    let path = config.working_dir().join(".miden-debug.py");
    path.try_exists().ok().is_some_and(|exists| exists).then_some(path)
}

pub(crate) fn execute_line(
    debugger: &ScriptDebugger,
    python: &mut PythonScriptSession,
    line: &str,
    out: &mut dyn Write,
) -> Result<Outcome, String> {
    match parse_script_command(line) {
        Some(ScriptCommand::Snippet(code)) => {
            let output = python.execute_snippet(code)?;
            write!(out, "{output}").map_err(|err| format!("failed to write output: {err}"))?;
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::InteractiveConsole) => {
            python.interact()?;
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::Import(path)) => {
            python.import_file(path)?;
            writeln!(out, "Imported Python script: {path}")
                .map_err(|err| format!("failed to write output: {err}"))?;
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::AddCommand { name, function }) => {
            python.add_custom_command(name, function)?;
            writeln!(out, "Added Python command: {name}")
                .map_err(|err| format!("failed to write output: {err}"))?;
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::ListCommands) => {
            let commands = python.custom_commands();
            if commands.is_empty() {
                writeln!(out, "No Python commands registered")
                    .map_err(|err| format!("failed to write output: {err}"))?;
            } else {
                writeln!(out, "Python commands:")
                    .map_err(|err| format!("failed to write output: {err}"))?;
                for command in commands {
                    writeln!(out, "  {command}")
                        .map_err(|err| format!("failed to write output: {err}"))?;
                }
            }
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::DeleteCommand(name)) => {
            python.delete_custom_command(name)?;
            writeln!(out, "Deleted Python command: {name}")
                .map_err(|err| format!("failed to write output: {err}"))?;
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::AddBreakpointCallback { id, function }) => {
            python.add_breakpoint_callback(id, function)?;
            writeln!(out, "Added Python callback for breakpoint {id}")
                .map_err(|err| format!("failed to write output: {err}"))?;
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::ListBreakpointCallbacks) => {
            let callbacks = python.breakpoint_callbacks();
            if callbacks.is_empty() {
                writeln!(out, "No Python breakpoint callbacks registered")
                    .map_err(|err| format!("failed to write output: {err}"))?;
            } else {
                writeln!(out, "Python breakpoint callbacks:")
                    .map_err(|err| format!("failed to write output: {err}"))?;
                for id in callbacks {
                    writeln!(out, "  breakpoint {id}")
                        .map_err(|err| format!("failed to write output: {err}"))?;
                }
            }
            Ok(Outcome::Continue)
        }
        Some(ScriptCommand::DeleteBreakpointCallback(id)) => {
            python.delete_breakpoint_callback(id)?;
            match id {
                Some(id) => writeln!(out, "Deleted Python callback for breakpoint {id}"),
                None => writeln!(out, "Deleted all Python breakpoint callbacks"),
            }
            .map_err(|err| format!("failed to write output: {err}"))?;
            Ok(Outcome::Continue)
        }
        None if is_resume_command(line) => execute_resume_command(debugger, python, line, out),
        None => match debugger.execute_repl_line(line, out) {
            Err(err) if is_unknown_command_error(line, &err) => {
                let (name, args) = split_command(line);
                match python.execute_custom_command(name, args)? {
                    Some(output) => {
                        write!(out, "{output}")
                            .map_err(|err| format!("failed to write output: {err}"))?;
                        Ok(Outcome::Continue)
                    }
                    None => Err(err),
                }
            }
            outcome => outcome,
        },
    }
}

enum ScriptCommand<'a> {
    Snippet(&'a str),
    InteractiveConsole,
    Import(&'a str),
    AddCommand { name: &'a str, function: &'a str },
    ListCommands,
    DeleteCommand(&'a str),
    AddBreakpointCallback { id: u8, function: &'a str },
    ListBreakpointCallbacks,
    DeleteBreakpointCallback(Option<u8>),
}

fn parse_script_command(line: &str) -> Option<ScriptCommand<'_>> {
    let line = line.trim();
    if let Some(command) = parse_command_script_command(line) {
        return Some(command);
    }
    if let Some(command) = parse_breakpoint_command(line) {
        return Some(command);
    }

    if line == "script" {
        return Some(ScriptCommand::InteractiveConsole);
    }

    let code = line.strip_prefix("script")?;
    if code.chars().next().is_some_and(char::is_whitespace) {
        let code = code.trim_start();
        if code.is_empty() {
            Some(ScriptCommand::InteractiveConsole)
        } else {
            Some(ScriptCommand::Snippet(code))
        }
    } else {
        None
    }
}

fn execute_resume_command(
    debugger: &ScriptDebugger,
    python: &mut PythonScriptSession,
    line: &str,
    out: &mut dyn Write,
) -> Result<Outcome, String> {
    let mut command = line.to_string();
    loop {
        let mut buffered_output = Vec::new();
        let outcome = debugger.execute_repl_line(&command, &mut buffered_output)?;
        if outcome == Outcome::Quit || debugger.terminated() {
            out.write_all(&buffered_output)
                .map_err(|err| format!("failed to write output: {err}"))?;
            return Ok(outcome);
        }

        if python.should_continue_after_breakpoint_callbacks()? {
            debugger.clear_hit_breakpoints();
            command = "continue".into();
            continue;
        }

        out.write_all(&buffered_output)
            .map_err(|err| format!("failed to write output: {err}"))?;
        return Ok(outcome);
    }
}

fn parse_breakpoint_command(line: &str) -> Option<ScriptCommand<'_>> {
    if let Some(rest) = line.strip_prefix("breakpoint command add")
        && rest.chars().next().is_some_and(char::is_whitespace)
        && let Some((id, function)) = parse_breakpoint_command_add_args(rest.trim_start())
    {
        return Some(ScriptCommand::AddBreakpointCallback { id, function });
    }

    if let Some(rest) = line.strip_prefix("breakpoint command list")
        && rest.trim().is_empty()
    {
        return Some(ScriptCommand::ListBreakpointCallbacks);
    }

    if let Some(rest) = line.strip_prefix("breakpoint command delete") {
        let rest = rest.trim();
        if rest.is_empty() {
            return Some(ScriptCommand::DeleteBreakpointCallback(None));
        }
        if let Ok(id) = rest.parse::<u8>() {
            return Some(ScriptCommand::DeleteBreakpointCallback(Some(id)));
        }
    }

    None
}

fn parse_breakpoint_command_add_args(args: &str) -> Option<(u8, &str)> {
    let (id, rest) = split_command(args);
    let id = id.parse::<u8>().ok()?;
    let rest = rest.trim();
    let function = rest.strip_prefix("-f")?.trim_start();
    if function.is_empty() {
        None
    } else {
        Some((id, function))
    }
}

fn parse_command_script_command(line: &str) -> Option<ScriptCommand<'_>> {
    if let Some(path) = line.strip_prefix("command script import")
        && path.chars().next().is_some_and(char::is_whitespace)
    {
        let path = path.trim_start();
        if !path.is_empty() {
            return Some(ScriptCommand::Import(path));
        }
    }

    if let Some(rest) = line.strip_prefix("command script list")
        && rest.trim().is_empty()
    {
        return Some(ScriptCommand::ListCommands);
    }

    if let Some(name) = line.strip_prefix("command script delete")
        && name.chars().next().is_some_and(char::is_whitespace)
    {
        let name = name.trim_start();
        if !name.is_empty() {
            return Some(ScriptCommand::DeleteCommand(name));
        }
    }

    if let Some(rest) = line.strip_prefix("command script add")
        && rest.chars().next().is_some_and(char::is_whitespace)
        && let Some((name, function)) = parse_command_script_add_args(rest.trim_start())
    {
        return Some(ScriptCommand::AddCommand { name, function });
    }

    None
}

fn parse_command_script_add_args(args: &str) -> Option<(&str, &str)> {
    let (name, rest) = split_command(args);
    let rest = rest.trim();
    let function = rest.strip_prefix("-f")?.trim_start();
    if name.is_empty() || function.is_empty() {
        None
    } else {
        Some((name, function))
    }
}

fn split_command(line: &str) -> (&str, &str) {
    match line.trim().split_once(char::is_whitespace) {
        Some((name, args)) => (name, args.trim_start()),
        None => (line.trim(), ""),
    }
}

fn is_unknown_command_error(line: &str, err: &str) -> bool {
    let (name, _) = split_command(line);
    err == format!("unknown command: {name}")
}

fn is_resume_command(line: &str) -> bool {
    let (name, _) = split_command(line);
    matches!(
        name,
        "c" | "continue" | "n" | "next" | "nl" | "next-line" | "nextline" | "e" | "finish"
    )
}

#[cfg(test)]
mod tests {
    use miden_core::Felt;

    use super::*;

    fn test_debugger() -> ScriptDebugger {
        ScriptDebugger::from_masm_source(
            r#"
begin
    push.3
end
"#,
            Vec::<Felt>::new(),
        )
        .unwrap()
    }

    #[test]
    fn parses_script_commands_only() {
        assert!(matches!(
            parse_script_command("script"),
            Some(ScriptCommand::InteractiveConsole)
        ));
        assert!(matches!(
            parse_script_command("script 1 + 1"),
            Some(ScriptCommand::Snippet("1 + 1"))
        ));
        assert!(matches!(
            parse_script_command("command script import /tmp/demo.py"),
            Some(ScriptCommand::Import("/tmp/demo.py"))
        ));
        assert!(parse_script_command("scripts").is_none());
        assert!(parse_script_command("step").is_none());
    }

    #[test]
    fn executes_script_snippets_through_repl_route() {
        let _guard = crate::script::python::python_test_lock();
        let debugger = test_debugger();
        let mut python = PythonScriptSession::new(debugger.clone()).unwrap();
        let mut output = Vec::new();

        execute_line(&debugger, &mut python, "script x = 1", &mut output).unwrap();
        execute_line(&debugger, &mut python, "script x + 1", &mut output).unwrap();

        assert_eq!(String::from_utf8(output).unwrap(), "2\n");
    }

    #[test]
    fn imports_script_and_runs_initializer() {
        let _guard = crate::script::python::python_test_lock();
        let debugger = test_debugger();
        let mut python = PythonScriptSession::new(debugger.clone()).unwrap();
        let temp_path = std::env::temp_dir().join(format!(
            "miden-debug-python-import-{}-{}.py",
            std::process::id(),
            0
        ));
        std::fs::write(
            &temp_path,
            r#"
def __miden_init_module(debugger, internal_dict):
    internal_dict["loaded_cycle"] = debugger.get_cycle()
"#,
        )
        .unwrap();

        let mut output = Vec::new();
        execute_line(
            &debugger,
            &mut python,
            &format!("command script import {}", temp_path.display()),
            &mut output,
        )
        .unwrap();
        execute_line(&debugger, &mut python, "script internal_dict['loaded_cycle']", &mut output)
            .unwrap();

        let _ = std::fs::remove_file(&temp_path);
        let output = String::from_utf8(output).unwrap();
        assert!(output.contains("Imported Python script:"));
        assert!(output.ends_with("0\n"));
    }

    #[test]
    fn registers_and_executes_custom_python_command() {
        let _guard = crate::script::python::python_test_lock();
        let debugger = test_debugger();
        let mut python = PythonScriptSession::new(debugger.clone()).unwrap();
        let temp_path = std::env::temp_dir()
            .join(format!("miden_debug_python_command_{}.py", std::process::id()));
        std::fs::write(
            &temp_path,
            r#"
def cycle(debugger, command, exe_ctx, result, internal_dict):
    print(f"{debugger.get_cycle()}:{command}", file=result)
"#,
        )
        .unwrap();

        let mut output = Vec::new();
        execute_line(
            &debugger,
            &mut python,
            &format!("command script import {}", temp_path.display()),
            &mut output,
        )
        .unwrap();
        execute_line(
            &debugger,
            &mut python,
            &format!(
                "command script add py-cycle -f {}.cycle",
                temp_path.file_stem().unwrap().to_str().unwrap()
            ),
            &mut output,
        )
        .unwrap();
        execute_line(&debugger, &mut python, "py-cycle hello", &mut output).unwrap();
        execute_line(&debugger, &mut python, "command script list", &mut output).unwrap();
        execute_line(&debugger, &mut python, "command script delete py-cycle", &mut output)
            .unwrap();

        let _ = std::fs::remove_file(&temp_path);
        let output = String::from_utf8(output).unwrap();
        assert!(output.contains("Added Python command: py-cycle"));
        assert!(output.contains("0:hello\n"));
        assert!(output.contains("Python commands:\n  py-cycle\n"));
        assert!(output.contains("Deleted Python command: py-cycle"));
    }

    #[test]
    fn breakpoint_callback_false_continues_execution() {
        let _guard = crate::script::python::python_test_lock();
        let debugger = ScriptDebugger::from_masm_source(
            r#"
begin
    push.1
    drop
    push.2
    drop
    push.3
    drop
end
"#,
            Vec::<Felt>::new(),
        )
        .unwrap();
        let mut python = PythonScriptSession::new(debugger.clone()).unwrap();
        let temp_path =
            std::env::temp_dir().join(format!("miden_debug_bp_callback_{}.py", std::process::id()));
        std::fs::write(
            &temp_path,
            r#"
def never_stop(frame, breakpoint, internal_dict):
    internal_dict["called"] = internal_dict.get("called", 0) + 1
    return False
"#,
        )
        .unwrap();

        let mut output = Vec::new();
        execute_line(&debugger, &mut python, "b after 1", &mut output).unwrap();
        execute_line(
            &debugger,
            &mut python,
            &format!("command script import {}", temp_path.display()),
            &mut output,
        )
        .unwrap();
        execute_line(
            &debugger,
            &mut python,
            &format!(
                "breakpoint command add 0 -f {}.never_stop",
                temp_path.file_stem().unwrap().to_str().unwrap()
            ),
            &mut output,
        )
        .unwrap();
        execute_line(&debugger, &mut python, "continue", &mut output).unwrap();
        execute_line(&debugger, &mut python, "script internal_dict['called']", &mut output)
            .unwrap();

        let _ = std::fs::remove_file(&temp_path);
        let output = String::from_utf8(output).unwrap();
        assert!(output.contains("Added Python callback for breakpoint 0"), "output:\n{output}");
        assert!(output.contains("Program terminated successfully"), "output:\n{output}");
        assert!(output.ends_with("1\n"), "output:\n{output}");
    }
}