Skip to main content

yomi_core/vm/
debug.rs

1//! Debugging by source line: line events, a ready-made debugger and inspection of the call stack (`spec/host/09-debug.md`).
2
3use std::collections::{BTreeSet, HashMap};
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7use super::{Inner, State, Variable, Vm, VmError, VmErrorKind, Yield};
8use crate::program::Program;
9
10/// Whether a line belongs to a label or to a `fn` (including lambdas and the functions the compiler makes).
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum UnitKind {
13    /// A label.
14    Label,
15    /// A `fn`.
16    Fn,
17}
18
19/// What the hook decides at a line event.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum HookAction {
22    /// Run the line.
23    Continue,
24    /// Pause before running the line.
25    Pause,
26}
27
28/// A line is about to run (`spec/host/09-debug.md`, 9.2).
29#[non_exhaustive]
30#[derive(Debug, Clone, Copy)]
31pub struct LineEvent<'a> {
32    /// The module that has the line.
33    pub module: &'a str,
34    /// The name of the label or `fn` that has the line (the functions the compiler makes have names starting with `<`).
35    pub unit: &'a str,
36    /// Whether `unit` is a label or a `fn`.
37    pub kind: UnitKind,
38    /// The line number, counted from 1.
39    pub line: u32,
40    /// The nesting of calls (9.3).
41    pub depth: usize,
42}
43
44/// Decides at each line event whether to pause.
45pub trait DebugHook {
46    /// Called just before the first instruction of a line runs.
47    fn on_line(&mut self, event: &LineEvent<'_>) -> HookAction;
48}
49
50/// Why [`Vm::run_debug`] returned.
51#[non_exhaustive]
52#[derive(Debug, Clone, PartialEq)]
53pub enum DebugYield {
54    /// A stop point or the end, as with [`Vm::run`].
55    Stop(Yield),
56    /// The hook asked to pause. Call [`Vm::run_debug`] or [`Vm::run`] to go on.
57    Paused,
58}
59
60/// One frame of the call stack ([`Vm::call_stack`]).
61#[non_exhaustive]
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct FrameInfo {
64    /// The module of the frame's code.
65    pub module: String,
66    /// The name of the label or `fn`.
67    pub name: String,
68    /// Whether `name` is a label or a `fn`.
69    pub kind: UnitKind,
70    /// The line the frame is running (for outer frames, the line of the call).
71    pub line: u32,
72}
73
74/// The code and line of an instruction.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub(super) struct DbgKey {
77    unit: Unit,
78    line: u32,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82enum Unit {
83    Label(usize),
84    Fn(usize),
85}
86
87impl<'a> Vm<'a> {
88    /// Whether the VM is paused by the debug hook.
89    pub fn is_paused(&self) -> bool {
90        self.state == State::Paused
91    }
92
93    fn dbg_unit(&self) -> Unit {
94        match self.cur_fn {
95            Some(f) => Unit::Fn(f),
96            None => Unit::Label(self.label),
97        }
98    }
99
100    fn unit_lines(program: &Program, unit: Unit) -> &[u32] {
101        match unit {
102            Unit::Label(l) => &program.labels[l].lines,
103            Unit::Fn(f) => &program.fns[f].lines,
104        }
105    }
106
107    /// Like [`Vm::run`], but calls `hook` at each line event, and returns [`DebugYield::Paused`] when it asks to pause.
108    pub fn run_debug(&mut self, hook: &mut dyn DebugHook) -> Result<DebugYield, VmError> {
109        let resuming = match self.state {
110            State::Stopped { .. } => return Err(self.misuse(VmErrorKind::AlreadyStopped)),
111            State::Ended => return Err(self.misuse(VmErrorKind::Ended)),
112            State::Poisoned => return Err(self.misuse(VmErrorKind::Poisoned)),
113            State::Paused => true,
114            State::Ready => false,
115        };
116        if self.total_valid {
117            debug_assert_eq!(self.total, self.recount_total());
118        } else {
119            self.total = self.recount_total();
120            self.total_valid = true;
121        }
122        if !resuming {
123            self.clear_cues();
124        }
125        self.state = State::Ready;
126        let program_ref = self.program.clone();
127        let program: &Program = &program_ref;
128        let limit = self.cfg.max_steps_per_run;
129        let mut executed: u64 = 0;
130        self.dbg_single = true;
131        let result = self.debug_loop(program, hook, limit, &mut executed);
132        self.dbg_single = false;
133        result
134    }
135
136    fn debug_loop(
137        &mut self,
138        program: &Program,
139        hook: &mut dyn DebugHook,
140        limit: Option<u64>,
141        executed: &mut u64,
142    ) -> Result<DebugYield, VmError> {
143        loop {
144            let unit = self.dbg_unit();
145            let line = Self::unit_lines(program, unit)
146                .get(self.pc)
147                .copied()
148                .unwrap_or(0);
149            if line != 0 {
150                let key = DbgKey { unit, line };
151                if self.dbg_last != Some(key) {
152                    let (module, name, kind) = match unit {
153                        Unit::Label(l) => {
154                            let c = &program.labels[l];
155                            (c.module, c.name.as_str(), UnitKind::Label)
156                        }
157                        Unit::Fn(f) => {
158                            let c = &program.fns[f];
159                            (c.module, c.name.as_str(), UnitKind::Fn)
160                        }
161                    };
162                    let event = LineEvent {
163                        module: &program.modules[module as usize],
164                        unit: name,
165                        kind,
166                        line,
167                        depth: self.frames.len() + self.fn_frames.len(),
168                    };
169                    // Remember the line before pausing, so that going on does not report it again
170                    self.dbg_last = Some(key);
171                    if hook.on_line(&event) == HookAction::Pause {
172                        self.state = State::Paused;
173                        return Ok(DebugYield::Paused);
174                    }
175                }
176            }
177            *executed += 1;
178            if limit.is_some_and(|m| *executed > m) {
179                return Err(self.err(VmErrorKind::StepLimitExceeded));
180            }
181            match self.exec(None)? {
182                Inner::Yield(y) => return Ok(DebugYield::Stop(y)),
183                Inner::Stepped => {}
184                Inner::Reached => unreachable!("終点を指定していない"),
185            }
186        }
187    }
188
189    /// The call stack, from the innermost frame (index 0, the code running now) to the outermost. Available while paused or
190    /// at a stop point.
191    pub fn call_stack(&self) -> Result<Vec<FrameInfo>, VmError> {
192        Ok(self
193            .frame_list()?
194            .into_iter()
195            .map(|f| {
196                let (module, name, kind) = self.unit_names(f.unit);
197                FrameInfo {
198                    module,
199                    name,
200                    kind,
201                    line: f.line,
202                }
203            })
204            .collect())
205    }
206
207    /// The local variables (parameters included) of frame `frame` of [`Vm::call_stack`]. Available while paused or at a stop
208    /// point. An index out of range gives an empty list.
209    pub fn frame_variables(&self, frame: usize) -> Result<Vec<Variable>, VmError> {
210        let frames = self.frame_list()?;
211        let Some(f) = frames.get(frame) else {
212            return Ok(Vec::new());
213        };
214        let infos = match f.unit {
215            Unit::Label(l) => &self.program.labels[l].locals,
216            Unit::Fn(i) => &self.program.fns[i].locals,
217        };
218        Ok(infos
219            .iter()
220            .zip(f.locals)
221            .filter(|(l, _)| !l.name.starts_with('$') && !l.ty.contains_fn())
222            .map(|(l, v)| Variable {
223                module: None,
224                name: l.name.clone(),
225                value: v.clone(),
226                local: true,
227                persistent: false,
228            })
229            .collect())
230    }
231
232    fn unit_names(&self, unit: Unit) -> (String, String, UnitKind) {
233        match unit {
234            Unit::Label(l) => {
235                let c = &self.program.labels[l];
236                (
237                    self.program.modules[c.module as usize].clone(),
238                    c.name.clone(),
239                    UnitKind::Label,
240                )
241            }
242            Unit::Fn(f) => {
243                let c = &self.program.fns[f];
244                (
245                    self.program.modules[c.module as usize].clone(),
246                    c.name.clone(),
247                    UnitKind::Fn,
248                )
249            }
250        }
251    }
252
253    fn frame_list(&self) -> Result<Vec<RawFrame<'_>>, VmError> {
254        let current_line = match self.state {
255            State::Paused => Some(self.pc),
256            State::Stopped { .. } => self.pc.checked_sub(1),
257            _ => None,
258        };
259        let Some(at) = current_line else {
260            return Err(self.misuse(VmErrorKind::NotStopped));
261        };
262        let line_of = |unit: Unit, i: usize| {
263            Self::unit_lines(&self.program, unit)
264                .get(i)
265                .copied()
266                .unwrap_or(0)
267        };
268        let unit = self.dbg_unit();
269        let mut out = vec![RawFrame {
270            unit,
271            line: line_of(unit, at),
272            locals: &self.locals,
273        }];
274        for fr in self.fn_frames.iter().rev() {
275            let unit = match fr.caller {
276                Some(f) => Unit::Fn(f),
277                None => Unit::Label(self.label),
278            };
279            out.push(RawFrame {
280                unit,
281                line: line_of(unit, fr.ret_pc.saturating_sub(1)),
282                locals: &fr.locals,
283            });
284        }
285        for f in self.frames.iter().rev() {
286            let unit = Unit::Label(f.label);
287            out.push(RawFrame {
288                unit,
289                line: line_of(unit, f.ret_pc.saturating_sub(1)),
290                locals: &f.locals,
291            });
292        }
293        Ok(out)
294    }
295}
296
297struct RawFrame<'v> {
298    unit: Unit,
299    line: u32,
300    locals: &'v [crate::value::Value],
301}
302
303/// How the [`Debugger`] goes on after a pause.
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum StepMode {
306    /// Run until a breakpoint or a pause request.
307    Continue,
308    /// Pause at the next line.
309    In,
310    /// Pause at the next line that is not deeper than where it paused.
311    Over,
312    /// Pause at the next line that is shallower than where it paused.
313    Out,
314}
315
316/// Asks a [`Debugger`] to pause at the next line, from any thread.
317#[derive(Debug, Clone)]
318pub struct PauseHandle(Arc<AtomicBool>);
319
320impl PauseHandle {
321    /// Asks for a pause. The request is cleared when the debugger pauses.
322    pub fn request(&self) {
323        self.0.store(true, Ordering::Relaxed);
324    }
325}
326
327type TraceFn = Box<dyn FnMut(&LineEvent<'_>) + Send>;
328
329/// A ready-made hook: breakpoints, stepping, pause requests and a trace function (`spec/host/09-debug.md`, 9.6).
330pub struct Debugger {
331    breakpoints: HashMap<String, BTreeSet<u32>>,
332    mode: StepMode,
333    /// The depth where it paused last; `usize::MAX` before the first pause (so that `Over` and `Out` act as `In`).
334    base_depth: usize,
335    pause: Arc<AtomicBool>,
336    trace: Option<TraceFn>,
337}
338
339impl Default for Debugger {
340    fn default() -> Self {
341        Self::new()
342    }
343}
344
345impl std::fmt::Debug for Debugger {
346    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347        f.debug_struct("Debugger")
348            .field("breakpoints", &self.breakpoints)
349            .field("mode", &self.mode)
350            .finish_non_exhaustive()
351    }
352}
353
354impl Debugger {
355    /// A debugger with no breakpoints that runs without pausing.
356    pub fn new() -> Self {
357        Self {
358            breakpoints: HashMap::new(),
359            mode: StepMode::Continue,
360            base_depth: usize::MAX,
361            pause: Arc::new(AtomicBool::new(false)),
362            trace: None,
363        }
364    }
365
366    /// Replaces the breakpoints of `module` (an empty list removes them).
367    pub fn set_breakpoints(&mut self, module: &str, lines: &[u32]) {
368        if lines.is_empty() {
369            self.breakpoints.remove(module);
370        } else {
371            self.breakpoints
372                .insert(module.to_string(), lines.iter().copied().collect());
373        }
374    }
375
376    /// How to go on from the next [`Vm::run_debug`].
377    pub fn set_mode(&mut self, mode: StepMode) {
378        self.mode = mode;
379    }
380
381    /// A handle to ask this debugger to pause from another thread.
382    pub fn pause_handle(&self) -> PauseHandle {
383        PauseHandle(Arc::clone(&self.pause))
384    }
385
386    /// Sets the function called at every line event (also when not pausing). `None` removes it.
387    pub fn set_trace(&mut self, f: Option<TraceFn>) {
388        self.trace = f;
389    }
390
391    /// The lines of `module` that have instructions to run (labels and `fn`s), in ascending order.
392    pub fn breakable_lines(program: &Program, module: &str) -> Vec<u32> {
393        let Some(m) = program.modules.iter().position(|n| n == module) else {
394            return Vec::new();
395        };
396        let m = m as u32;
397        let mut lines: BTreeSet<u32> = BTreeSet::new();
398        for c in &program.labels {
399            if c.module == m {
400                lines.extend(c.lines.iter().copied().filter(|&l| l != 0));
401            }
402        }
403        for c in &program.fns {
404            if c.module == m {
405                lines.extend(c.lines.iter().copied().filter(|&l| l != 0));
406            }
407        }
408        lines.into_iter().collect()
409    }
410}
411
412impl DebugHook for Debugger {
413    fn on_line(&mut self, event: &LineEvent<'_>) -> HookAction {
414        if let Some(trace) = &mut self.trace {
415            trace(event);
416        }
417        let hit = self.pause.swap(false, Ordering::Relaxed)
418            || self
419                .breakpoints
420                .get(event.module)
421                .is_some_and(|lines| lines.contains(&event.line))
422            || match self.mode {
423                StepMode::Continue => false,
424                StepMode::In => true,
425                StepMode::Over => event.depth <= self.base_depth,
426                StepMode::Out => event.depth < self.base_depth,
427            };
428        if hit {
429            self.base_depth = event.depth;
430            self.mode = StepMode::Continue;
431            HookAction::Pause
432        } else {
433            HookAction::Continue
434        }
435    }
436}