miden-debug 0.15.0

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
use std::{
    boxed::Box,
    io::Write,
    string::{String, ToString},
};

use miden_assembly_syntax::diagnostics::Report;

use super::commands::ReplCommand;
use crate::{config::DebuggerConfig, debug::BreakpointType, ui::state::State};

/// The result of executing a single REPL line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    /// Continue reading commands.
    Continue,
    /// The user requested to quit the session.
    Quit,
}

/// The core debugger REPL logic, decoupled from any particular I/O frontend.
///
/// Command output is written to a caller-provided [`Write`] sink rather than
/// directly to stdout. This lets the same command set drive both the
/// interactive session (writing to stdout, see [`super::session::ReplSession`])
/// and the scriptable test harness (writing to an in-memory buffer, see
/// [`super::script::run_script`]).
pub struct ReplEngine {
    state: State,
    selected_frame: usize,
}

impl ReplEngine {
    /// Create an engine from a debugger configuration (loads a program package).
    pub fn new(config: Box<DebuggerConfig>) -> Result<Self, Report> {
        Ok(Self {
            state: State::new(config)?,
            selected_frame: 0,
        })
    }

    /// Create an engine from a debugger configuration.
    pub fn from_config(config: Box<DebuggerConfig>) -> Result<Self, Report> {
        Self::new(config)
    }

    /// Borrow the current debugger state.
    pub fn state(&self) -> &State {
        &self.state
    }

    /// Mutably borrow the current debugger state.
    pub fn state_mut(&mut self) -> &mut State {
        &mut self.state
    }

    /// Render the prompt for the current execution state.
    ///
    /// When `color` is true, ANSI escape codes are emitted (for interactive
    /// use). When false, the prompt is plain text, which keeps scripted
    /// transcripts stable and matchable.
    #[cfg(feature = "repl")]
    pub fn make_prompt(&self, color: bool) -> String {
        let cycle = self.state.executor().cycle;

        let (status, fg) = if self.state.executor().stopped {
            if self.state.execution_failed().is_some() {
                ("ERR", "1;31")
            } else {
                ("END", "1;32")
            }
        } else if self.state.stopped {
            ("STOP", "1;33")
        } else {
            ("", "")
        };

        if !color {
            return if status.is_empty() {
                format!("[cycle {cycle}] > ")
            } else {
                format!("[cycle {cycle} {status}] > ")
            };
        }

        if status.is_empty() {
            format!("\x1b[36m[\x1b[0mcycle {cycle}\x1b[36m]\x1b[0m > ")
        } else {
            format!("\x1b[36m[\x1b[0mcycle {cycle} \x1b[{fg}m{status}\x1b[0m\x1b[36m]\x1b[0m > ")
        }
    }

    /// Print the current source location / procedure to `out`.
    pub fn print_location(&self, out: &mut dyn Write) {
        let frames = self.state.executor().callstack.logical_frames("");
        if let Some(frame) = frames.iter().rev().nth(self.selected_frame) {
            let name = frame.display_name();
            if let Some(resolved) = frame.resolved(&*self.state.source_manager) {
                let _ = writeln!(out, "at {} in {}", resolved, name);
            } else {
                let _ = writeln!(out, "in {}", name);
            }
        }
    }

    /// Parse and execute a single command line, writing any output to `out`.
    ///
    /// Returns [`Outcome::Quit`] when the user asked to exit. Parse errors and
    /// command errors are returned as `Err` for the caller to surface.
    pub fn execute_line(&mut self, line: &str, out: &mut dyn Write) -> Result<Outcome, String> {
        let cmd = line.parse::<ReplCommand>()?;
        if matches!(cmd, ReplCommand::Quit) {
            return Ok(Outcome::Quit);
        }
        self.execute_command(cmd, out)?;
        Ok(Outcome::Continue)
    }

    fn execute_command(&mut self, cmd: ReplCommand, out: &mut dyn Write) -> Result<(), String> {
        match cmd {
            ReplCommand::Step => self.cmd_step(1, out),
            ReplCommand::StepN(n) => self.cmd_step(n, out),
            ReplCommand::Next => self.cmd_next(out),
            ReplCommand::NextLine => self.cmd_next_line(out),
            ReplCommand::Continue => self.cmd_continue(out),
            ReplCommand::Finish => self.cmd_finish(out),
            ReplCommand::Break(bp_type) => self.cmd_break(bp_type, out),
            ReplCommand::Breakpoints => self.cmd_breakpoints(out),
            ReplCommand::Delete(id) => self.cmd_delete(id, out),
            ReplCommand::Stack => self.cmd_stack(out),
            ReplCommand::Memory(expr) => self.cmd_memory(&expr, out),
            ReplCommand::Locals => self.cmd_locals(out),
            ReplCommand::Vars(show_all) => self.cmd_vars(show_all, out),
            ReplCommand::Where => self.cmd_where(out),
            ReplCommand::List => self.cmd_list(out),
            ReplCommand::Backtrace => self.cmd_backtrace(out),
            ReplCommand::Frame(index) => self.cmd_frame(index, out),
            ReplCommand::Reload => self.cmd_reload(out),
            ReplCommand::Help => self.cmd_help(out),
            ReplCommand::Quit => unreachable!("quit handled in execute_line"),
        }
    }

    fn cmd_step(&mut self, n: usize, out: &mut dyn Write) -> Result<(), String> {
        if self.state.executor().stopped {
            return Err("program has terminated, cannot step".into());
        }

        for _ in 0..n {
            if self.state.executor().stopped {
                break;
            }
            match self.state.executor_mut().step() {
                Ok(_) => {}
                Err(err) => {
                    self.state.set_execution_failed(err);
                    break;
                }
            }
        }

        self.selected_frame = 0;
        self.report_execution_state(out);
        Ok(())
    }

    fn cmd_next(&mut self, out: &mut dyn Write) -> Result<(), String> {
        self.cmd_resume_with_breakpoint(BreakpointType::Next, out)
    }

    fn cmd_next_line(&mut self, out: &mut dyn Write) -> Result<(), String> {
        self.cmd_resume_with_breakpoint(BreakpointType::NextLine, out)
    }

    fn cmd_continue(&mut self, out: &mut dyn Write) -> Result<(), String> {
        self.ensure_can_continue()?;

        self.state.run_until_stopped();
        self.selected_frame = 0;

        self.report_execution_state(out);

        Ok(())
    }

    fn cmd_finish(&mut self, out: &mut dyn Write) -> Result<(), String> {
        self.cmd_resume_with_breakpoint(BreakpointType::Finish, out)
    }

    fn cmd_resume_with_breakpoint(
        &mut self,
        bp_type: BreakpointType,
        out: &mut dyn Write,
    ) -> Result<(), String> {
        self.ensure_can_continue()?;

        self.state.create_breakpoint(bp_type);
        self.state.run_until_stopped();
        self.selected_frame = 0;
        self.report_execution_state(out);
        Ok(())
    }

    fn report_execution_state(&self, out: &mut dyn Write) {
        if !self.state.executor().stopped {
            self.print_location(out);
            return;
        }

        if let Some(err) = self.state.execution_failed() {
            let _ = writeln!(out, "Program terminated with error: {}", err);
            return;
        }

        let _ = writeln!(out, "Program terminated successfully");
        match self.state.typed_result() {
            Ok(Some(result)) => {
                let _ = writeln!(out, "Result: {result}");
            }
            Ok(None) => {}
            Err(err) => {
                let _ = writeln!(out, "Result unavailable: {err}");
            }
        }
    }

    fn ensure_can_continue(&self) -> Result<(), String> {
        if self.state.executor().stopped {
            return Err("program has terminated, cannot continue".into());
        }

        Ok(())
    }

    fn cmd_break(&mut self, bp_type: BreakpointType, out: &mut dyn Write) -> Result<(), String> {
        self.state.create_breakpoint(bp_type.clone());
        let id = self.state.breakpoints.last().map(|bp| bp.id).unwrap_or(0);
        let _ = writeln!(out, "Breakpoint {} set: {}", id, format_bp_type(&bp_type));
        Ok(())
    }

    fn cmd_breakpoints(&mut self, out: &mut dyn Write) -> Result<(), String> {
        if self.state.breakpoints.is_empty() {
            let _ = writeln!(out, "No breakpoints set");
            return Ok(());
        }

        let _ = writeln!(out, "Breakpoints:");
        for bp in &self.state.breakpoints {
            if !bp.is_internal() {
                let _ = writeln!(out, "  [{}] {}", bp.id, format_bp_type(&bp.ty));
            }
        }
        Ok(())
    }

    fn cmd_delete(&mut self, id: Option<u8>, out: &mut dyn Write) -> Result<(), String> {
        match id {
            Some(id) => {
                let count_before = self.state.breakpoints.len();
                self.state.breakpoints.retain(|bp| bp.id != id);
                if self.state.breakpoints.len() < count_before {
                    let _ = writeln!(out, "Deleted breakpoint {}", id);
                } else {
                    return Err(format!("no breakpoint with id {}", id));
                }
            }
            None => {
                // Delete only user-created (non-internal) breakpoints
                self.state.breakpoints.retain(|bp| bp.is_internal());
                let _ = writeln!(out, "Deleted all breakpoints");
            }
        }
        Ok(())
    }

    fn cmd_stack(&mut self, out: &mut dyn Write) -> Result<(), String> {
        let stack = &self.state.executor().current_stack;

        if stack.is_empty() {
            let _ = writeln!(out, "Stack is empty");
            return Ok(());
        }

        let _ = writeln!(out, "Operand Stack ({} elements):", stack.len());
        for (i, elem) in stack.iter().enumerate() {
            let val = elem.as_canonical_u64();
            let marker = if i == 0 { ">" } else { " " };
            let _ = writeln!(out, "  {} [{}] {} (0x{:x})", marker, i, val, val);
        }
        Ok(())
    }

    fn cmd_memory(
        &mut self,
        expr: &crate::debug::ReadMemoryExpr,
        out: &mut dyn Write,
    ) -> Result<(), String> {
        let result = self.state.read_memory(expr)?;
        let _ = writeln!(out, "{}", result);
        Ok(())
    }

    fn cmd_locals(&mut self, out: &mut dyn Write) -> Result<(), String> {
        let output = self.state.format_variables(false);
        let _ = writeln!(out, "{}", output);
        Ok(())
    }

    fn cmd_vars(&mut self, show_all: bool, out: &mut dyn Write) -> Result<(), String> {
        let output = self.state.format_variables(show_all);
        let _ = writeln!(out, "{}", output);
        Ok(())
    }

    fn cmd_where(&mut self, out: &mut dyn Write) -> Result<(), String> {
        let frames = self.state.executor().callstack.logical_frames("");
        if let Some(frame) = frames.iter().rev().nth(self.selected_frame) {
            let name = frame.display_name();
            if let Some(resolved) = frame.resolved(&*self.state.source_manager) {
                let _ = writeln!(
                    out,
                    "{}:{}:{} in {}",
                    resolved.source_file.uri().as_str(),
                    resolved.line,
                    resolved.col,
                    name
                );
            } else {
                let _ = writeln!(out, "in {} (no source location available)", name);
            }
        } else {
            let _ = writeln!(out, "No current frame");
        }
        Ok(())
    }

    fn cmd_list(&mut self, out: &mut dyn Write) -> Result<(), String> {
        if let Some(frame) = self.state.executor().callstack.current_frame() {
            let recent = frame.recent();
            if recent.is_empty() {
                let _ = writeln!(out, "No recent instructions");
                return Ok(());
            }

            let _ = writeln!(out, "Recent instructions:");
            for (i, op) in recent.iter().enumerate() {
                let marker = if i == recent.len() - 1 { ">" } else { " " };
                let _ = writeln!(out, "  {} {}", marker, op.display());
            }
        } else {
            let _ = writeln!(out, "No current frame");
        }
        Ok(())
    }

    fn cmd_backtrace(&mut self, out: &mut dyn Write) -> Result<(), String> {
        let frames = self.state.executor().callstack.logical_frames("");
        if frames.is_empty() {
            let _ = writeln!(out, "No call stack");
            return Ok(());
        }

        let _ = writeln!(out, "Backtrace ({} frames):", frames.len());
        for (i, frame) in frames.iter().rev().enumerate() {
            let loc_str = frame
                .resolved(&*self.state.source_manager)
                .map(|r| format!(" at {}", r))
                .unwrap_or_default();
            let marker = if i == self.selected_frame { "*" } else { " " };

            let _ = writeln!(out, "{} #{} {}{}", marker, i, frame.display_name(), loc_str);
        }
        Ok(())
    }

    fn cmd_frame(&mut self, index: usize, out: &mut dyn Write) -> Result<(), String> {
        let num_frames = self.state.executor().callstack.logical_frames("").len();
        if index >= num_frames {
            return Err(format!("invalid frame index {index}; backtrace has {num_frames} frames"));
        }
        self.selected_frame = index;
        self.print_location(out);
        Ok(())
    }

    fn cmd_reload(&mut self, out: &mut dyn Write) -> Result<(), String> {
        self.state.reload().map_err(|e| format!("reload failed: {e}"))?;
        self.selected_frame = 0;
        let _ = writeln!(out, "Program reloaded");
        self.report_execution_state(out);
        Ok(())
    }

    fn cmd_help(&mut self, out: &mut dyn Write) -> Result<(), String> {
        let _ = writeln!(out, "{}", ReplCommand::help_text());
        Ok(())
    }
}

pub(crate) fn format_bp_type(ty: &BreakpointType) -> String {
    match ty {
        BreakpointType::Step => "next cycle".into(),
        BreakpointType::StepN(n) => format!("after {} cycles", n),
        BreakpointType::StepTo(c) => format!("at cycle {}", c),
        BreakpointType::Next => "next instruction".into(),
        BreakpointType::NextLine => "next source line".into(),
        BreakpointType::Finish => "function return".into(),
        BreakpointType::File(pattern) => pattern.glob().to_string(),
        BreakpointType::Line { pattern, line } => format!("{}:{}", pattern.glob(), line),
        BreakpointType::Opcode(matcher) => format!("opcode {matcher}"),
        BreakpointType::Called(pat) => format!("call {}", pat.glob()),
        BreakpointType::Event(event) => format!("event {event:?}"),
    }
}