Skip to main content

aether/debugger/
state.rs

1// src/debugger/state.rs
2//! Debugger state management
3
4use crate::debugger::breakpoint::{Breakpoint, BreakpointType};
5use std::collections::HashMap;
6
7/// Execution control mode
8#[derive(Debug, Clone, PartialEq)]
9pub enum ExecutionMode {
10    /// Normal execution (check breakpoints only)
11    Normal,
12    /// Step into function calls
13    StepInto,
14    /// Step over function calls
15    StepOver,
16    /// Step out of current function
17    StepOut,
18    /// Continue until next breakpoint
19    Continue,
20}
21
22/// Core debugger state
23pub struct DebuggerState {
24    /// All breakpoints indexed by ID
25    breakpoints: HashMap<usize, Breakpoint>,
26    /// Next breakpoint ID to assign
27    next_breakpoint_id: usize,
28    /// Current execution mode
29    execution_mode: ExecutionMode,
30    /// Current source file location (file, line)
31    current_location: Option<(String, usize)>,
32    /// Stack depth for step over/step out operations
33    step_over_depth: Option<usize>,
34    /// Whether debugger is active
35    is_active: bool,
36}
37
38impl DebuggerState {
39    /// Create a new debugger state
40    pub fn new() -> Self {
41        DebuggerState {
42            breakpoints: HashMap::new(),
43            next_breakpoint_id: 1,
44            execution_mode: ExecutionMode::Normal,
45            current_location: None,
46            step_over_depth: None,
47            is_active: false,
48        }
49    }
50
51    /// Activate the debugger
52    pub fn activate(&mut self) {
53        self.is_active = true;
54    }
55
56    /// Deactivate the debugger
57    pub fn deactivate(&mut self) {
58        self.is_active = false;
59    }
60
61    /// Check if debugger is active
62    pub fn is_active(&self) -> bool {
63        self.is_active
64    }
65
66    /// Set a breakpoint and return its ID
67    pub fn set_breakpoint(&mut self, bp_type: BreakpointType) -> usize {
68        let id = self.next_breakpoint_id;
69        self.next_breakpoint_id += 1;
70        self.breakpoints.insert(id, Breakpoint::new(id, bp_type));
71        id
72    }
73
74    /// Remove a breakpoint by ID
75    pub fn remove_breakpoint(&mut self, id: usize) -> bool {
76        self.breakpoints.remove(&id).is_some()
77    }
78
79    /// Remove all breakpoints
80    pub fn remove_all_breakpoints(&mut self) {
81        self.breakpoints.clear();
82    }
83
84    /// Enable or disable a breakpoint
85    pub fn toggle_breakpoint(&mut self, id: usize, enabled: bool) -> bool {
86        if let Some(bp) = self.breakpoints.get_mut(&id) {
87            bp.enabled = enabled;
88            true
89        } else {
90            false
91        }
92    }
93
94    /// Get a breakpoint by ID
95    pub fn get_breakpoint(&self, id: usize) -> Option<&Breakpoint> {
96        self.breakpoints.get(&id)
97    }
98
99    /// List all breakpoints
100    pub fn list_breakpoints(&self) -> Vec<&Breakpoint> {
101        let mut bps: Vec<_> = self.breakpoints.values().collect();
102        bps.sort_by_key(|bp| bp.id);
103        bps
104    }
105
106    /// Set the execution mode
107    pub fn set_execution_mode(&mut self, mode: ExecutionMode) {
108        self.execution_mode = mode;
109    }
110
111    /// Get the current execution mode
112    pub fn execution_mode(&self) -> &ExecutionMode {
113        &self.execution_mode
114    }
115
116    /// Set the step over depth
117    pub fn set_step_over_depth(&mut self, depth: usize) {
118        self.step_over_depth = Some(depth);
119    }
120
121    /// Clear the step over depth
122    pub fn clear_step_over_depth(&mut self) {
123        self.step_over_depth = None;
124    }
125
126    /// Update current location
127    pub fn update_location(&mut self, file: String, line: usize) {
128        self.current_location = Some((file, line));
129    }
130
131    /// Get current location
132    pub fn current_location(&self) -> Option<&(String, usize)> {
133        self.current_location.as_ref()
134    }
135
136    /// Check if a function breakpoint should trigger
137    pub fn should_pause_at_function(&mut self, func_name: &str) -> bool {
138        if !self.is_active {
139            return false;
140        }
141
142        for bp in self.breakpoints.values_mut() {
143            if bp.is_function_breakpoint(func_name) && bp.enabled {
144                bp.hit_count += 1;
145                if bp.hit_count > bp.ignore_count {
146                    return true;
147                }
148            }
149        }
150        false
151    }
152
153    /// Check if execution should pause at the given location.
154    ///
155    /// `eval_cond` 在条件断点位置命中时被调用,用**当前求值环境**求值
156    /// 条件表达式并返回真值;条件为假或求值失败都不暂停。
157    pub fn should_pause(
158        &mut self,
159        file: &str,
160        line: usize,
161        call_stack_depth: usize,
162        eval_cond: &mut dyn FnMut(&str) -> bool,
163    ) -> bool {
164        if !self.is_active {
165            return false;
166        }
167
168        // Update current location
169        self.current_location = Some((file.to_string(), line));
170
171        match self.execution_mode {
172            ExecutionMode::Normal => {
173                // Check breakpoints only
174                self.any_breakpoint_triggers(file, line, eval_cond)
175            }
176            ExecutionMode::StepInto => {
177                // Pause at next statement
178                self.execution_mode = ExecutionMode::Normal;
179                true
180            }
181            ExecutionMode::StepOver => {
182                // Pause when stack depth returns to the same level
183                if let Some(target_depth) = self.step_over_depth
184                    && call_stack_depth <= target_depth
185                {
186                    self.step_over_depth = None;
187                    self.execution_mode = ExecutionMode::Normal;
188                    return true;
189                }
190                false
191            }
192            ExecutionMode::StepOut => {
193                // Pause when stack depth becomes less than current
194                if let Some(target_depth) = self.step_over_depth
195                    && call_stack_depth < target_depth
196                {
197                    self.step_over_depth = None;
198                    self.execution_mode = ExecutionMode::Normal;
199                    return true;
200                }
201                false
202            }
203            ExecutionMode::Continue => {
204                // Pause only at breakpoints
205                let paused = self.any_breakpoint_triggers(file, line, eval_cond);
206                if paused {
207                    self.execution_mode = ExecutionMode::Normal;
208                }
209                paused
210            }
211        }
212    }
213
214    /// 遍历断点判断是否应在当前位置暂停。
215    ///
216    /// 位置命中(含 hit_count/ignore_count 判定,见 [`Breakpoint::should_trigger`])
217    /// 后,条件断点还要经 `eval_cond` 求值条件:为假或求值失败则该断点
218    /// 本次不暂停,继续检查其余断点。
219    fn any_breakpoint_triggers(
220        &mut self,
221        file: &str,
222        line: usize,
223        eval_cond: &mut dyn FnMut(&str) -> bool,
224    ) -> bool {
225        for bp in self.breakpoints.values_mut() {
226            if bp.should_trigger(file, line) {
227                let satisfied = match bp.get_condition() {
228                    Some(cond) => eval_cond(cond),
229                    None => true,
230                };
231                if satisfied {
232                    return true;
233                }
234            }
235        }
236        false
237    }
238}
239
240impl Default for DebuggerState {
241    fn default() -> Self {
242        Self::new()
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    /// 恒真条件(行断点不受影响;条件断点在单元测试中恒触发)
251    fn cond_true(_: &str) -> bool {
252        true
253    }
254
255    #[test]
256    fn test_set_breakpoint() {
257        let mut state = DebuggerState::new();
258        let id = state.set_breakpoint(BreakpointType::Line {
259            file: "test.aether".to_string(),
260            line: 10,
261        });
262
263        assert_eq!(id, 1);
264        assert!(state.get_breakpoint(id).is_some());
265    }
266
267    #[test]
268    fn test_remove_breakpoint() {
269        let mut state = DebuggerState::new();
270        let id = state.set_breakpoint(BreakpointType::Line {
271            file: "test.aether".to_string(),
272            line: 10,
273        });
274
275        assert!(state.remove_breakpoint(id));
276        assert!(!state.remove_breakpoint(id));
277        assert!(state.get_breakpoint(id).is_none());
278    }
279
280    #[test]
281    fn test_toggle_breakpoint() {
282        let mut state = DebuggerState::new();
283        let id = state.set_breakpoint(BreakpointType::Line {
284            file: "test.aether".to_string(),
285            line: 10,
286        });
287
288        assert!(state.toggle_breakpoint(id, false));
289        assert!(!state.get_breakpoint(id).unwrap().enabled);
290        assert!(state.toggle_breakpoint(id, true));
291        assert!(state.get_breakpoint(id).unwrap().enabled);
292    }
293
294    #[test]
295    fn test_should_pause_normal_mode() {
296        let mut state = DebuggerState::new();
297        state.activate();
298
299        let _: usize = state.set_breakpoint(BreakpointType::Line {
300            file: "test.aether".to_string(),
301            line: 10,
302        });
303
304        assert!(state.should_pause("test.aether", 10, 0, &mut cond_true));
305        assert!(!state.should_pause("test.aether", 11, 0, &mut cond_true));
306    }
307
308    #[test]
309    fn test_step_into_mode() {
310        let mut state = DebuggerState::new();
311        state.activate();
312        state.set_execution_mode(ExecutionMode::StepInto);
313
314        // Should pause immediately
315        assert!(state.should_pause("test.aether", 10, 0, &mut cond_true));
316        // After stepping, mode returns to normal
317        assert_eq!(state.execution_mode(), &ExecutionMode::Normal);
318    }
319
320    #[test]
321    fn test_step_over_mode() {
322        let mut state = DebuggerState::new();
323        state.activate();
324        state.set_execution_mode(ExecutionMode::StepOver);
325        state.set_step_over_depth(2);
326
327        // Should not pause while depth > 2
328        assert!(!state.should_pause("test.aether", 10, 3, &mut cond_true));
329        // Should pause when depth returns to 2
330        assert!(state.should_pause("test.aether", 11, 2, &mut cond_true));
331    }
332
333    #[test]
334    fn test_step_out_mode() {
335        let mut state = DebuggerState::new();
336        state.activate();
337        state.set_execution_mode(ExecutionMode::StepOut);
338        state.set_step_over_depth(2);
339
340        // Should not pause while depth >= 2
341        assert!(!state.should_pause("test.aether", 10, 2, &mut cond_true));
342        // Should pause when depth < 2
343        assert!(state.should_pause("test.aether", 11, 1, &mut cond_true));
344    }
345
346    #[test]
347    fn test_function_breakpoint() {
348        let mut state = DebuggerState::new();
349        state.activate();
350        state.set_breakpoint(BreakpointType::Function {
351            name: "myFunc".to_string(),
352        });
353
354        assert!(state.should_pause_at_function("myFunc"));
355        assert!(!state.should_pause_at_function("otherFunc"));
356    }
357}