1use crate::debugger::breakpoint::BreakpointType;
5use crate::debugger::state::{DebuggerState, ExecutionMode};
6use crate::evaluator::Evaluator;
7use std::cell::RefCell;
8use std::collections::HashSet;
9use std::io::{self, Write};
10use std::rc::Rc;
11
12#[derive(Debug, Clone, PartialEq)]
14pub enum CommandAction {
15 Continue,
17 Stay,
19 Quit,
21}
22
23pub struct DebuggerSession {
29 state: Rc<RefCell<DebuggerState>>,
30 source_code: Option<String>,
31 source_file: Option<String>,
32 breakable_lines: Option<HashSet<usize>>,
34 terminated: bool,
36}
37
38impl DebuggerSession {
39 pub fn new(state: Rc<RefCell<DebuggerState>>) -> Self {
41 DebuggerSession {
42 state,
43 source_code: None,
44 source_file: None,
45 breakable_lines: None,
46 terminated: false,
47 }
48 }
49
50 pub fn set_source(&mut self, source: String, file: String) {
52 self.source_code = Some(source);
53 self.source_file = Some(file);
54 }
55
56 pub fn set_breakable_lines(&mut self, lines: HashSet<usize>) {
58 self.breakable_lines = Some(lines);
59 }
60
61 pub fn shared_state(&self) -> Rc<RefCell<DebuggerState>> {
63 Rc::clone(&self.state)
64 }
65
66 pub fn is_terminated(&self) -> bool {
68 self.terminated
69 }
70
71 pub fn start(&mut self) {
73 self.state.borrow_mut().activate();
74 println!("Aether Debugger v1.0");
75 if let Some(file) = &self.source_file {
76 println!("Debugging: {}", file);
77 }
78 println!("Type 'help' for available commands\n");
79 }
80
81 pub fn run_pause_loop(&mut self, ev: &mut Evaluator) -> bool {
86 let (file, line) = self
87 .state
88 .borrow()
89 .current_location()
90 .cloned()
91 .unwrap_or_else(|| ("<unknown>".to_string(), 0));
92 println!("\nPaused at {}:{}\n", file, line);
93 print!("{}", self.listing(9));
94
95 loop {
96 print!("(aether-debug) ");
97 let _ = io::stdout().flush();
98
99 let mut line = String::new();
100 match io::stdin().read_line(&mut line) {
101 Ok(0) => {
102 self.state.borrow_mut().deactivate();
103 println!("\n(Input closed; running to program end)");
104 return false;
105 }
106 Ok(_) => {}
107 Err(_) => return false,
108 }
109
110 let (msg, action) = self.handle_command(ev, line.trim());
111 if !msg.is_empty() {
112 println!("{}", msg);
113 }
114 match action {
115 CommandAction::Continue => return false,
116 CommandAction::Stay => continue,
117 CommandAction::Quit => {
118 self.terminated = true;
119 return true;
120 }
121 }
122 }
123 }
124
125 pub fn handle_command(&mut self, ev: &mut Evaluator, cmd: &str) -> (String, CommandAction) {
127 let parts: Vec<&str> = cmd.split_whitespace().collect();
128 if parts.is_empty() {
129 return (String::new(), CommandAction::Stay);
130 }
131
132 let command = parts[0].to_lowercase();
133 let args = &parts[1..];
134
135 let (msg, action) = match command.as_str() {
136 "break" | "b" => self.cmd_break(ev, args),
137 "delete" | "d" => self.cmd_delete(args),
138 "disable" => self.cmd_disable(args),
139 "enable" => self.cmd_enable(args),
140 "info" => self.cmd_info(args),
141 "step" | "s" => self.cmd_step(args),
142 "next" | "n" => self.cmd_next(ev, args),
143 "finish" | "f" => self.cmd_finish(ev),
144 "continue" | "c" => self.cmd_continue(),
145 "print" | "p" => self.cmd_print(ev, args),
146 "backtrace" | "bt" => self.cmd_backtrace(ev, args),
147 "frame" => self.cmd_frame(args),
148 "list" | "l" => self.cmd_list(args),
149 "help" | "h" | "?" => self.cmd_help(),
150 "quit" | "q" => self.cmd_quit(),
151 _ => (
152 format!(
153 "Unknown command: {}. Type 'help' for available commands.",
154 command
155 ),
156 CommandAction::Stay,
157 ),
158 };
159
160 (msg, action)
161 }
162
163 fn cmd_break(&mut self, ev: &mut Evaluator, args: &[&str]) -> (String, CommandAction) {
166 if args.is_empty() {
167 return (
168 "Usage: break [file:]line [if condition] | break function_name".to_string(),
169 CommandAction::Stay,
170 );
171 }
172
173 let loc = args[0];
174 let condition: Option<String> = if args.len() >= 3 && args[1] == "if" {
177 Some(args[2..].join(" "))
178 } else {
179 None
180 };
181
182 if let Ok(line) = loc.parse::<usize>() {
184 let file = ev
186 .get_source_file()
187 .map(str::to_string)
188 .or_else(|| {
189 self.state
190 .borrow()
191 .current_location()
192 .map(|(f, _)| f.clone())
193 })
194 .or_else(|| self.source_file.clone())
195 .unwrap_or_else(|| "<unknown>".to_string());
196
197 let id = self.state.borrow_mut().set_breakpoint(match &condition {
198 Some(cond) => BreakpointType::Conditional {
199 file: file.clone(),
200 line,
201 condition: cond.clone(),
202 },
203 None => BreakpointType::Line {
204 file: file.clone(),
205 line,
206 },
207 });
208
209 let unbreakable = self
211 .breakable_lines
212 .as_ref()
213 .is_some_and(|lines| !lines.contains(&line));
214 let mut msg = format!("Breakpoint {} set at {}:{}", id, file, line);
215 if let Some(cond) = &condition {
216 msg.push_str(&format!(" if {cond}"));
217 }
218 if unbreakable {
219 msg.push_str(&format!(
220 "\nNote: line {} has no statement start; breakpoint may never trigger",
221 line
222 ));
223 }
224 return (msg, CommandAction::Stay);
225 }
226
227 if let Some(pos) = loc.find(':') {
229 let file = loc[..pos].to_string();
230 if let Ok(line) = loc[pos + 1..].parse::<usize>() {
231 let id = self.state.borrow_mut().set_breakpoint(match &condition {
232 Some(cond) => BreakpointType::Conditional {
233 file: file.clone(),
234 line,
235 condition: cond.clone(),
236 },
237 None => BreakpointType::Line {
238 file: file.clone(),
239 line,
240 },
241 });
242 return (
243 format!(
244 "Breakpoint {} set at {}:{}{}",
245 id,
246 file,
247 line,
248 condition
249 .as_ref()
250 .map(|c| format!(" if {c}"))
251 .unwrap_or_default()
252 ),
253 CommandAction::Stay,
254 );
255 }
256 }
257
258 let id = self
260 .state
261 .borrow_mut()
262 .set_breakpoint(BreakpointType::Function {
263 name: loc.to_string(),
264 });
265 (
266 format!("Breakpoint {} set at function '{}'", id, loc),
267 CommandAction::Stay,
268 )
269 }
270
271 fn cmd_delete(&mut self, args: &[&str]) -> (String, CommandAction) {
272 if args.is_empty() {
273 let count = self.state.borrow().list_breakpoints().len();
274 self.state.borrow_mut().remove_all_breakpoints();
275 return (
276 format!("All breakpoints deleted ({})", count),
277 CommandAction::Stay,
278 );
279 }
280
281 if let Ok(id) = args[0].parse::<usize>() {
282 if self.state.borrow_mut().remove_breakpoint(id) {
283 (format!("Breakpoint {} deleted", id), CommandAction::Stay)
284 } else {
285 (format!("Breakpoint {} not found", id), CommandAction::Stay)
286 }
287 } else {
288 ("Invalid breakpoint ID".to_string(), CommandAction::Stay)
289 }
290 }
291
292 fn cmd_disable(&mut self, args: &[&str]) -> (String, CommandAction) {
293 if args.is_empty() {
294 return (
295 "Usage: disable <breakpoint_id>".to_string(),
296 CommandAction::Stay,
297 );
298 }
299
300 if let Ok(id) = args[0].parse::<usize>() {
301 if self.state.borrow_mut().toggle_breakpoint(id, false) {
302 (format!("Breakpoint {} disabled", id), CommandAction::Stay)
303 } else {
304 (format!("Breakpoint {} not found", id), CommandAction::Stay)
305 }
306 } else {
307 ("Invalid breakpoint ID".to_string(), CommandAction::Stay)
308 }
309 }
310
311 fn cmd_enable(&mut self, args: &[&str]) -> (String, CommandAction) {
312 if args.is_empty() {
313 return (
314 "Usage: enable <breakpoint_id>".to_string(),
315 CommandAction::Stay,
316 );
317 }
318
319 if let Ok(id) = args[0].parse::<usize>() {
320 if self.state.borrow_mut().toggle_breakpoint(id, true) {
321 (format!("Breakpoint {} enabled", id), CommandAction::Stay)
322 } else {
323 (format!("Breakpoint {} not found", id), CommandAction::Stay)
324 }
325 } else {
326 ("Invalid breakpoint ID".to_string(), CommandAction::Stay)
327 }
328 }
329
330 fn cmd_info(&mut self, args: &[&str]) -> (String, CommandAction) {
331 if args.is_empty() {
332 return (
333 "Usage: info breakpoints | info locals | info args".to_string(),
334 CommandAction::Stay,
335 );
336 }
337
338 match args[0] {
339 "breakpoints" | "break" | "bp" => {
340 let state = self.state.borrow();
341 let breakpoints = state.list_breakpoints();
342 if breakpoints.is_empty() {
343 return ("No breakpoints".to_string(), CommandAction::Stay);
344 }
345
346 let mut result = String::from("Breakpoints:\n");
347 for bp in breakpoints {
348 let status = if bp.enabled { " enabled" } else { " disabled" };
349 result.push_str(&format!(
350 " ID: {:3}{} | {} | hits: {} | {}\n",
351 bp.id,
352 status,
353 bp.location_string(),
354 bp.hit_count,
355 if bp.ignore_count > 0 {
356 format!("(ignore first {})", bp.ignore_count)
357 } else {
358 String::new()
359 }
360 ));
361 }
362 (result, CommandAction::Stay)
363 }
364 "locals" => {
365 (
367 "Local variables: Not yet implemented".to_string(),
368 CommandAction::Stay,
369 )
370 }
371 "args" => (
372 "Arguments: Not yet implemented".to_string(),
373 CommandAction::Stay,
374 ),
375 _ => (
376 format!("Unknown info command: {}", args[0]),
377 CommandAction::Stay,
378 ),
379 }
380 }
381
382 fn cmd_step(&mut self, args: &[&str]) -> (String, CommandAction) {
383 let _count = if args.is_empty() {
384 1
385 } else {
386 args[0].parse::<usize>().unwrap_or(1)
387 };
388
389 self.state
390 .borrow_mut()
391 .set_execution_mode(ExecutionMode::StepInto);
392 ("Stepping...".to_string(), CommandAction::Continue)
393 }
394
395 fn cmd_next(&mut self, ev: &mut Evaluator, args: &[&str]) -> (String, CommandAction) {
396 let _count = if args.is_empty() {
397 1
398 } else {
399 args[0].parse::<usize>().unwrap_or(1)
400 };
401
402 let depth = ev.get_call_stack_depth();
403
404 let mut state = self.state.borrow_mut();
405 state.set_execution_mode(ExecutionMode::StepOver);
406 state.set_step_over_depth(depth);
407 ("Next...".to_string(), CommandAction::Continue)
408 }
409
410 fn cmd_finish(&mut self, ev: &mut Evaluator) -> (String, CommandAction) {
411 let depth = ev.get_call_stack_depth();
412
413 let mut state = self.state.borrow_mut();
414 state.set_execution_mode(ExecutionMode::StepOut);
415 state.set_step_over_depth(depth);
416 (
417 "Running until current function returns...".to_string(),
418 CommandAction::Continue,
419 )
420 }
421
422 fn cmd_continue(&mut self) -> (String, CommandAction) {
423 self.state
424 .borrow_mut()
425 .set_execution_mode(ExecutionMode::Continue);
426 ("Continuing...".to_string(), CommandAction::Continue)
427 }
428
429 fn cmd_print(&mut self, ev: &mut Evaluator, args: &[&str]) -> (String, CommandAction) {
430 if args.is_empty() {
431 return (
432 "Usage: print <variable_name>".to_string(),
433 CommandAction::Stay,
434 );
435 }
436
437 let var_name = args[0];
438
439 match ev.lookup_variable(var_name) {
441 Some(value) => (format!("{} = {}", var_name, value), CommandAction::Stay),
442 None => (
443 format!("Variable '{}' not found", var_name),
444 CommandAction::Stay,
445 ),
446 }
447 }
448
449 fn cmd_backtrace(&mut self, ev: &mut Evaluator, args: &[&str]) -> (String, CommandAction) {
450 let call_stack = ev.get_call_stack();
451
452 if call_stack.is_empty() {
453 return ("No stack.".to_string(), CommandAction::Stay);
454 }
455
456 let max_frames = if args.is_empty() {
457 call_stack.len()
458 } else {
459 args[0].parse::<usize>().unwrap_or(call_stack.len())
460 };
461
462 let mut result = String::from("Call stack:\n");
463 for (i, frame) in call_stack.iter().take(max_frames).enumerate() {
464 result.push_str(&format!("#{} {}\n", i, frame.signature));
465 }
466 (result, CommandAction::Stay)
467 }
468
469 fn cmd_frame(&mut self, args: &[&str]) -> (String, CommandAction) {
470 if args.is_empty() {
471 return (
472 "Usage: frame <frame_number>".to_string(),
473 CommandAction::Stay,
474 );
475 }
476
477 if let Ok(_frame_num) = args[0].parse::<usize>() {
478 (
479 "Frame selection not yet implemented".to_string(),
480 CommandAction::Stay,
481 )
482 } else {
483 ("Invalid frame number".to_string(), CommandAction::Stay)
484 }
485 }
486
487 fn cmd_list(&mut self, args: &[&str]) -> (String, CommandAction) {
488 let count = if args.is_empty() {
489 10
490 } else {
491 args[0].parse::<usize>().unwrap_or(10)
492 };
493
494 (self.listing(count), CommandAction::Stay)
495 }
496
497 fn listing(&self, count: usize) -> String {
501 let Some(source) = &self.source_code else {
502 return "No source code available".to_string();
503 };
504
505 let location = self.state.borrow().current_location().cloned();
506 if let Some((file, _)) = &location
507 && let Some(loaded) = &self.source_file
508 {
509 fn base(p: &str) -> &str {
510 p.rsplit(['/', '\\']).next().unwrap_or(p)
511 }
512 if base(file) != base(loaded) {
513 return format!("No source available for {}\n", file);
514 }
515 }
516
517 let current_line = location.map(|(_, line)| line).unwrap_or(1);
518
519 let lines: Vec<&str> = source.lines().collect();
520 let start = current_line.saturating_sub(count / 2);
521 let end = (start + count).min(lines.len());
522
523 let mut result = String::new();
524 for (idx, line) in lines.iter().enumerate().take(end).skip(start) {
525 let marker = if idx + 1 == current_line { "=>" } else { " " };
526 result.push_str(&format!("{} {:4}: {}\n", marker, idx + 1, line));
527 }
528 result
529 }
530
531 fn cmd_help(&mut self) -> (String, CommandAction) {
532 (HELP_TEXT.to_string(), CommandAction::Stay)
533 }
534
535 fn cmd_quit(&mut self) -> (String, CommandAction) {
536 ("Exiting debugger...".to_string(), CommandAction::Quit)
537 }
538}
539
540const HELP_TEXT: &str = r#"
541Aether Debugger Commands
542
543Execution Control:
544 step [N] Step N times (default 1), stepping into function calls
545 next [N] Step N times (default 1), stepping over function calls
546 finish Execute until the current function returns
547 continue Continue execution until next breakpoint
548
549Breakpoints:
550 break [file:]line Set breakpoint at line
551 break function Set breakpoint at function entry
552 delete [N] Delete breakpoint N (or all if N not specified)
553 disable [N] Disable breakpoint N
554 enable [N] Enable breakpoint N
555 info breakpoints List all breakpoints
556
557Stack & Variables:
558 backtrace [N] Print backtrace of N frames (all if N not specified)
559 frame N Select and print stack frame N
560 print expr Print value of expression/variable
561 info locals Print local variables
562
563Source:
564 list [N] List N lines of source (default 10)
565
566Miscellaneous:
567 help Show this help message
568 quit Exit debugger
569
570Examples:
571 (aether-debug) break 15 # Set breakpoint at line 15
572 (aether-debug) break calc.aether:20 # Set at file:line
573 (aether-debug) break processData # Set at function entry
574 (aether-debug) next # Step over
575 (aether-debug) step # Step into
576 (aether-debug) print X # Show variable X
577 (aether-debug) backtrace # Show call stack
578"#;
579
580#[cfg(test)]
581mod tests {
582 use super::*;
583 use crate::environment::Environment;
584
585 fn create_test_session() -> DebuggerSession {
586 let state = Rc::new(RefCell::new(DebuggerState::new()));
587 let mut session = DebuggerSession::new(state);
588 session.set_source(
589 "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n".to_string(),
590 "test.aether".to_string(),
591 );
592 session
593 }
594
595 fn create_test_evaluator() -> Evaluator {
596 let env = Rc::new(RefCell::new(Environment::new()));
597 Evaluator::with_env(env)
598 }
599
600 #[test]
601 fn test_break_command() {
602 let mut session = create_test_session();
603 let mut ev = create_test_evaluator();
604
605 let (result, _) = session.handle_command(&mut ev, "break 10");
606 assert!(result.contains("Breakpoint"));
607 }
608
609 #[test]
610 fn test_break_command_warns_on_unbreakable_line() {
611 let mut session = create_test_session();
612 session.set_breakable_lines(HashSet::from([1, 3]));
613 let mut ev = create_test_evaluator();
614
615 let (result, _) = session.handle_command(&mut ev, "break 2");
616 assert!(result.contains("Breakpoint"));
617 assert!(result.contains("may never trigger"));
618
619 let (result, _) = session.handle_command(&mut ev, "break 3");
620 assert!(result.contains("Breakpoint"));
621 assert!(!result.contains("may never trigger"));
622 }
623
624 #[test]
625 fn test_break_uses_evaluator_source_file() {
626 let mut session = create_test_session();
627 let mut ev = create_test_evaluator();
628 ev.set_source_file("main.aether".to_string());
629
630 let (result, _) = session.handle_command(&mut ev, "break 4");
631 assert!(result.contains("main.aether:4"));
632 }
633
634 #[test]
635 fn test_step_command() {
636 let mut session = create_test_session();
637 let mut ev = create_test_evaluator();
638
639 let (_, action) = session.handle_command(&mut ev, "step");
640 assert_eq!(action, CommandAction::Continue);
641 assert_eq!(
642 session.state.borrow().execution_mode(),
643 &ExecutionMode::StepInto
644 );
645 }
646
647 #[test]
648 fn test_next_command() {
649 let mut session = create_test_session();
650 let mut ev = create_test_evaluator();
651
652 let (_, action) = session.handle_command(&mut ev, "next");
653 assert_eq!(action, CommandAction::Continue);
654 assert_eq!(
655 session.state.borrow().execution_mode(),
656 &ExecutionMode::StepOver
657 );
658 }
659
660 #[test]
661 fn test_continue_command() {
662 let mut session = create_test_session();
663 let mut ev = create_test_evaluator();
664
665 let (_, action) = session.handle_command(&mut ev, "continue");
666 assert_eq!(action, CommandAction::Continue);
667 assert_eq!(
668 session.state.borrow().execution_mode(),
669 &ExecutionMode::Continue
670 );
671 }
672
673 #[test]
674 fn test_print_variable_via_scope_chain() {
675 let mut session = create_test_session();
676 let mut ev = create_test_evaluator();
677 ev.set_global("X".to_string(), crate::value::Value::Number(42.0));
678
679 let (result, _) = session.handle_command(&mut ev, "print X");
680 assert_eq!(result, "X = 42");
681
682 let (result, _) = session.handle_command(&mut ev, "print Y");
683 assert!(result.contains("not found"));
684 }
685
686 #[test]
687 fn test_shared_state_visible_to_both_sides() {
688 let mut session = create_test_session();
690 let mut ev = create_test_evaluator();
691 let shared = session.shared_state();
692 ev.attach_debugger(Rc::clone(&shared), Box::new(|_ev| false));
693
694 assert!(ev.debugger_attached());
695 session.handle_command(&mut ev, "break 2");
696 assert!(shared.borrow().is_active());
697 assert_eq!(shared.borrow().list_breakpoints().len(), 1);
698
699 ev.detach_debugger();
700 assert!(!ev.debugger_attached());
701 assert!(!shared.borrow().is_active());
702 }
703}