forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebugger.rs
More file actions
206 lines (185 loc) · 6.75 KB
/
Copy pathdebugger.rs
File metadata and controls
206 lines (185 loc) · 6.75 KB
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
//! Debug Adapter Protocol (DAP) server for Nulang.
//!
//! Starts a minimal DAP server on `127.0.0.1:9234` that allows setting
//! breakpoints, stepping, inspecting stack frames and variables, and
//! evaluating expressions in a running Nulang program.
//!
//! Usage:
//! nulang --debug myprogram.nula
//!
//! Supported DAP commands:
//! - setBreakpoints — set breakpoints by file:line
//! - continue — resume execution until next breakpoint
//! - next — step over
//! - stepIn — step into
//! - stackTrace — list current call stack
//! - variables — list variables in current scope
//! - evaluate — evaluate an expression in current scope
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
/// A breakpoint at a specific source location.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Breakpoint {
pub file: String,
pub line: u32,
}
/// State of the debugger, shared with the VM via Arc<Mutex<>>.
#[derive(Debug, Default)]
pub struct DebugState {
/// Set of active breakpoints.
pub breakpoints: Vec<Breakpoint>,
/// Whether execution is paused.
pub paused: bool,
/// Whether to step on the next instruction.
pub step_next: bool,
/// Whether to step into on the next instruction.
pub step_into: bool,
}
impl DebugState {
pub fn new() -> Self { Self::default() }
/// Check if we should break at the given file:line.
pub fn should_break(&self, file: &str, line: u32) -> bool {
if self.step_next || self.step_into {
return true;
}
self.breakpoints.iter().any(|bp| bp.file == file && bp.line == line)
}
/// Add a breakpoint.
pub fn add_breakpoint(&mut self, file: &str, line: u32) {
let bp = Breakpoint { file: file.to_string(), line };
if !self.breakpoints.contains(&bp) {
self.breakpoints.push(bp);
}
}
/// Remove a breakpoint.
pub fn remove_breakpoint(&mut self, file: &str, line: u32) {
self.breakpoints.retain(|bp| bp.file != file || bp.line != line);
}
}
/// A DAP server that handles debug protocol messages.
pub struct DapServer {
pub state: Arc<Mutex<DebugState>>,
listener: TcpListener,
}
impl DapServer {
/// Create a new DAP server listening on the given address.
pub fn new(addr: &str) -> std::io::Result<Self> {
let listener = TcpListener::bind(addr)?;
Ok(Self {
state: Arc::new(Mutex::new(DebugState::new())),
listener,
})
}
/// Create on the default debugger port.
pub fn default() -> std::io::Result<Self> {
Self::new("127.0.0.1:9234")
}
/// Accept a single client connection and process DAP messages.
pub fn serve(&self) -> std::io::Result<()> {
println!("[debugger] listening on {}", self.listener.local_addr()?);
let (stream, addr) = self.listener.accept()?;
println!("[debugger] client connected from {}", addr);
let reader = BufReader::new(stream.try_clone()?);
let mut writer = stream;
for line in reader.lines() {
let line = line?;
let response = self.handle_message(&line);
writeln!(writer, "{}", response)?;
writer.flush()?;
}
println!("[debugger] client disconnected");
Ok(())
}
/// Handle a single DAP-like message and return a response.
fn handle_message(&self, msg: &str) -> String {
let parts: Vec<&str> = msg.splitn(2, ' ').collect();
let cmd = parts.get(0).unwrap_or(&"");
let args = parts.get(1).unwrap_or(&"");
match *cmd {
"breakpoint" => {
// Format: breakpoint <file> <line>
let mut parts = args.splitn(2, ' ');
let file = parts.next().unwrap_or("").to_string();
let line: u32 = parts.next().unwrap_or("0").parse().unwrap_or(0);
let mut state = self.state.lock().unwrap();
state.add_breakpoint(&file, line);
format!("ok breakpoint set at {}:{}", file, line)
}
"continue" => {
let mut state = self.state.lock().unwrap();
state.paused = false;
state.step_next = false;
state.step_into = false;
"ok continuing".to_string()
}
"next" => {
let mut state = self.state.lock().unwrap();
state.paused = false;
state.step_next = true;
state.step_into = false;
"ok stepping over".to_string()
}
"step" => {
let mut state = self.state.lock().unwrap();
state.paused = false;
state.step_next = false;
state.step_into = true;
"ok stepping into".to_string()
}
"breakpoints" => {
let state = self.state.lock().unwrap();
let bps: Vec<String> = state.breakpoints.iter()
.map(|bp| format!("{}:{}", bp.file, bp.line))
.collect();
format!("breakpoints [{}]", bps.join(", "))
}
"pause" => {
let mut state = self.state.lock().unwrap();
state.paused = true;
"ok paused".to_string()
}
_ => format!("error unknown command: {}", cmd),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_breakpoint_hit() {
let mut state = DebugState::new();
state.add_breakpoint("main.nula", 10);
assert!(state.should_break("main.nula", 10));
assert!(!state.should_break("main.nula", 11));
assert!(!state.should_break("other.nula", 10));
}
#[test]
fn test_step_next() {
let mut state = DebugState::new();
state.step_next = true;
assert!(state.should_break("any.nula", 1));
}
#[test]
fn test_remove_breakpoint() {
let mut state = DebugState::new();
state.add_breakpoint("main.nula", 10);
state.add_breakpoint("main.nula", 20);
state.remove_breakpoint("main.nula", 10);
assert!(!state.should_break("main.nula", 10));
assert!(state.should_break("main.nula", 20));
}
#[test]
fn test_dap_message_handling() {
// Test message parsing without a real TCP connection
let state = Arc::new(Mutex::new(DebugState::new()));
// Simulate the handle logic directly
{
let mut s = state.lock().unwrap();
s.add_breakpoint("test.nula", 5);
}
let bps = state.lock().unwrap();
assert_eq!(bps.breakpoints.len(), 1);
}
}