1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum UnitKind {
13 Label,
15 Fn,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum HookAction {
22 Continue,
24 Pause,
26}
27
28#[non_exhaustive]
30#[derive(Debug, Clone, Copy)]
31pub struct LineEvent<'a> {
32 pub module: &'a str,
34 pub unit: &'a str,
36 pub kind: UnitKind,
38 pub line: u32,
40 pub depth: usize,
42}
43
44pub trait DebugHook {
46 fn on_line(&mut self, event: &LineEvent<'_>) -> HookAction;
48}
49
50#[non_exhaustive]
52#[derive(Debug, Clone, PartialEq)]
53pub enum DebugYield {
54 Stop(Yield),
56 Paused,
58}
59
60#[non_exhaustive]
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct FrameInfo {
64 pub module: String,
66 pub name: String,
68 pub kind: UnitKind,
70 pub line: u32,
72}
73
74#[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 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum StepMode {
306 Continue,
308 In,
310 Over,
312 Out,
314}
315
316#[derive(Debug, Clone)]
318pub struct PauseHandle(Arc<AtomicBool>);
319
320impl PauseHandle {
321 pub fn request(&self) {
323 self.0.store(true, Ordering::Relaxed);
324 }
325}
326
327type TraceFn = Box<dyn FnMut(&LineEvent<'_>) + Send>;
328
329pub struct Debugger {
331 breakpoints: HashMap<String, BTreeSet<u32>>,
332 mode: StepMode,
333 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 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 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 pub fn set_mode(&mut self, mode: StepMode) {
378 self.mode = mode;
379 }
380
381 pub fn pause_handle(&self) -> PauseHandle {
383 PauseHandle(Arc::clone(&self.pause))
384 }
385
386 pub fn set_trace(&mut self, f: Option<TraceFn>) {
388 self.trace = f;
389 }
390
391 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}