use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::Result;
use serde_json::{Value, json};
use super::transport::DapTransport;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionPhase {
Initializing,
Running,
Stopped,
Terminated,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DapEvent {
Initialized,
Stopped { thread_id: i64, reason: String },
Continued,
Output { category: String, text: String },
Terminated,
BreakpointsUpdated,
InspectionUpdated,
Evaluated {
context: String,
expression: String,
result: String,
success: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BreakpointReport {
pub path: PathBuf,
pub line: usize,
pub verified: bool,
}
pub fn breakpoint_reports(msg: &Value) -> Vec<BreakpointReport> {
let body = match msg.get("body") {
Some(b) => b,
None => return Vec::new(),
};
let mut raw: Vec<&Value> = Vec::new();
if let Some(arr) = body.get("breakpoints").and_then(Value::as_array) {
raw.extend(arr.iter());
}
if let Some(one) = body.get("breakpoint") {
raw.push(one);
}
raw.into_iter()
.filter_map(|bp| {
let path = bp.get("source")?.get("path")?.as_str()?;
let line = bp.get("line").and_then(Value::as_i64).unwrap_or(0);
if line <= 0 {
return None;
}
Some(BreakpointReport {
path: PathBuf::from(path),
line: line as usize,
verified: bp.get("verified").and_then(Value::as_bool).unwrap_or(false),
})
})
.collect()
}
pub fn classify_event(msg: &Value) -> Option<DapEvent> {
if msg.get("type")?.as_str()? != "event" {
return None;
}
let body = msg.get("body");
match msg.get("event")?.as_str()? {
"initialized" => Some(DapEvent::Initialized),
"stopped" => Some(DapEvent::Stopped {
thread_id: body
.and_then(|b| b.get("threadId"))
.and_then(Value::as_i64)
.unwrap_or(0),
reason: body
.and_then(|b| b.get("reason"))
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
}),
"continued" => Some(DapEvent::Continued),
"output" => Some(DapEvent::Output {
category: body
.and_then(|b| b.get("category"))
.and_then(Value::as_str)
.unwrap_or("console")
.to_string(),
text: body
.and_then(|b| b.get("output"))
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
}),
"terminated" | "exited" => Some(DapEvent::Terminated),
_ => None,
}
}
pub fn output_is_user_visible(category: &str) -> bool {
category != "telemetry"
}
pub fn initialize_request() -> Value {
json!({
"type": "request",
"command": "initialize",
"arguments": {
"adapterID": "debugpy",
"linesStartAt1": true,
"columnsStartAt1": true,
"pathFormat": "path",
"supportsRunInTerminalRequest": true,
"supportsStartDebuggingRequest": true
}
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdapterKind {
Debugpy,
LldbDap,
JsDebug,
}
pub fn lldb_launch_request(program: &Path, stop_on_entry: bool) -> Value {
json!({
"type": "request",
"command": "launch",
"arguments": {
"program": program.to_string_lossy(),
"stopOnEntry": stop_on_entry,
}
})
}
pub fn lldb_test_launch_request(program: &Path, args: &[String]) -> Value {
json!({
"type": "request",
"command": "launch",
"arguments": {
"program": program.to_string_lossy(),
"args": args,
"stopOnEntry": false,
}
})
}
pub fn pytest_debug_launch_request(python: &Path, cwd: &Path, name: &str) -> Value {
json!({
"type": "request",
"command": "launch",
"arguments": {
"request": "launch",
"module": "pytest",
"args": ["-v", "-k", name],
"python": [python.to_string_lossy()],
"cwd": cwd.to_string_lossy(),
"console": "internalConsole",
"stopOnEntry": false,
"justMyCode": false
}
})
}
pub fn launch_request(program: &Path, interpreter: &Path, stop_on_entry: bool) -> Value {
json!({
"type": "request",
"command": "launch",
"arguments": {
"request": "launch",
"program": program.to_string_lossy(),
"python": [interpreter.to_string_lossy()],
"console": "internalConsole",
"stopOnEntry": stop_on_entry,
"justMyCode": false
}
})
}
pub fn js_launch_request(program: &Path, cwd: &Path, stop_on_entry: bool) -> Value {
json!({
"type": "request",
"command": "launch",
"arguments": {
"type": "pwa-node",
"request": "launch",
"program": program.to_string_lossy(),
"cwd": cwd.to_string_lossy(),
"console": "internalConsole",
"sourceMaps": true,
"stopOnEntry": stop_on_entry
}
})
}
pub fn js_child_launch_request(configuration: &Value, outer_request: Option<&str>) -> Value {
let command = match configuration
.get("request")
.and_then(Value::as_str)
.or(outer_request)
{
Some("attach") => "attach",
_ => "launch",
};
json!({
"type": "request",
"command": command,
"arguments": configuration,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartDebuggingRequest {
pub request_seq: i64,
pub config: Value,
pub request: Option<String>,
}
pub fn start_debugging_request(msg: &Value) -> Option<StartDebuggingRequest> {
if msg.get("type")?.as_str()? != "request" {
return None;
}
if msg.get("command")?.as_str()? != "startDebugging" {
return None;
}
let arguments = msg.get("arguments")?;
Some(StartDebuggingRequest {
request_seq: msg.get("seq")?.as_i64()?,
config: arguments.get("configuration")?.clone(),
request: arguments
.get("request")
.and_then(Value::as_str)
.map(str::to_string),
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceBreakpoint {
pub line: u32,
pub condition: Option<String>,
pub log_message: Option<String>,
}
impl SourceBreakpoint {
pub fn plain(line: u32) -> Self {
Self {
line,
condition: None,
log_message: None,
}
}
}
pub fn set_breakpoints_request(path: &Path, breakpoints: &[SourceBreakpoint]) -> Value {
let bps: Vec<Value> = breakpoints
.iter()
.map(|b| {
let mut bp = json!({ "line": b.line });
if let Some(c) = &b.condition {
bp["condition"] = json!(c);
}
if let Some(m) = &b.log_message {
bp["logMessage"] = json!(m);
}
bp
})
.collect();
let lines: Vec<u32> = breakpoints.iter().map(|b| b.line).collect();
json!({
"type": "request",
"command": "setBreakpoints",
"arguments": {
"source": { "path": path.to_string_lossy() },
"breakpoints": bps,
"lines": lines
}
})
}
pub fn reverse_request_response(request_seq: i64, command: &str, success: bool) -> Value {
json!({
"type": "response",
"request_seq": request_seq,
"success": success,
"command": command,
"message": if success { Value::Null } else { Value::from("unsupported by croft") },
})
}
pub fn configuration_done_request() -> Value {
json!({ "type": "request", "command": "configurationDone", "arguments": {} })
}
pub fn set_exception_breakpoints_request(filters: &[String]) -> Value {
json!({
"type": "request",
"command": "setExceptionBreakpoints",
"arguments": { "filters": filters }
})
}
pub fn thread_request(command: &str, thread_id: i64) -> Value {
json!({
"type": "request",
"command": command,
"arguments": { "threadId": thread_id }
})
}
pub fn stack_trace_request(thread_id: i64) -> Value {
json!({
"type": "request",
"command": "stackTrace",
"arguments": { "threadId": thread_id, "startFrame": 0 }
})
}
pub fn evaluate_request(expression: &str, frame_id: Option<i64>, context: &str) -> Value {
let mut args = json!({ "expression": expression, "context": context });
if let Some(fid) = frame_id {
args["frameId"] = Value::from(fid);
}
json!({ "type": "request", "command": "evaluate", "arguments": args })
}
pub fn parse_evaluate_result(response: &Value) -> Option<String> {
response
.get("body")?
.get("result")?
.as_str()
.map(str::to_string)
}
pub fn scopes_request(frame_id: i64) -> Value {
json!({
"type": "request",
"command": "scopes",
"arguments": { "frameId": frame_id }
})
}
pub fn variables_request(variables_reference: i64) -> Value {
json!({
"type": "request",
"command": "variables",
"arguments": { "variablesReference": variables_reference }
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackFrame {
pub id: i64,
pub name: String,
pub path: Option<PathBuf>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scope {
pub name: String,
pub variables_ref: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Variable {
pub name: String,
pub value: String,
pub type_name: String,
pub variables_ref: i64,
}
pub fn parse_stack_frames(stack_trace_response: &Value) -> Vec<StackFrame> {
stack_trace_response
.get("body")
.and_then(|b| b.get("stackFrames"))
.and_then(Value::as_array)
.map(|frames| {
frames
.iter()
.filter_map(|f| {
Some(StackFrame {
id: f.get("id")?.as_i64()?,
name: f
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
path: f
.get("source")
.and_then(|s| s.get("path"))
.and_then(Value::as_str)
.map(PathBuf::from),
line: f.get("line").and_then(Value::as_i64).unwrap_or(0) as usize,
})
})
.collect()
})
.unwrap_or_default()
}
pub fn parse_scopes(scopes_response: &Value) -> Vec<Scope> {
scopes_response
.get("body")
.and_then(|b| b.get("scopes"))
.and_then(Value::as_array)
.map(|scopes| {
scopes
.iter()
.filter_map(|s| {
Some(Scope {
name: s.get("name")?.as_str()?.to_string(),
variables_ref: s.get("variablesReference")?.as_i64()?,
})
})
.collect()
})
.unwrap_or_default()
}
pub fn parse_variables(variables_response: &Value) -> Vec<Variable> {
variables_response
.get("body")
.and_then(|b| b.get("variables"))
.and_then(Value::as_array)
.map(|vars| {
vars.iter()
.filter_map(|v| {
Some(Variable {
name: v.get("name")?.as_str()?.to_string(),
value: v
.get("value")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
type_name: v
.get("type")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
variables_ref: v
.get("variablesReference")
.and_then(Value::as_i64)
.unwrap_or(0),
})
})
.collect()
})
.unwrap_or_default()
}
pub fn fold_breakpoint_reports(
map: &mut BTreeMap<PathBuf, std::collections::BTreeSet<usize>>,
reports: &[BreakpointReport],
) -> bool {
use std::collections::{BTreeSet, btree_map::Entry};
if reports.is_empty() {
return false;
}
let mut by_path: BTreeMap<PathBuf, BTreeSet<usize>> = BTreeMap::new();
for r in reports {
let set = by_path.entry(r.path.clone()).or_default();
if !r.verified {
set.insert(r.line);
}
}
let mut changed = false;
for (path, unverified) in by_path {
match map.entry(path) {
Entry::Occupied(mut e) => {
if *e.get() != unverified {
if unverified.is_empty() {
e.remove();
} else {
e.insert(unverified);
}
changed = true;
}
}
Entry::Vacant(e) => {
if !unverified.is_empty() {
e.insert(unverified);
changed = true;
}
}
}
}
changed
}
pub struct DapSession {
transport: DapTransport,
child: Option<DapTransport>,
js_server: Option<(String, u16)>,
pub phase: SessionPhase,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
pub stopped_thread: Option<i64>,
pub current_location: Option<(PathBuf, usize)>,
pub unverified_breakpoints: BTreeMap<PathBuf, std::collections::BTreeSet<usize>>,
pub stack_frames: Vec<StackFrame>,
pub scopes: Vec<Scope>,
pub variables: BTreeMap<i64, Vec<Variable>>,
pub selected_frame: Option<i64>,
pending_var_refs: std::collections::HashMap<i64, i64>,
pending_evals: std::collections::HashMap<i64, (String, String)>,
pub exception_filters: Vec<String>,
known_thread: Option<i64>,
}
impl DapSession {
#[allow(clippy::too_many_arguments)]
pub fn launch(
adapter_program: &str,
adapter_args: &[String],
cwd: &Path,
program: &Path,
interpreter: &Path,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
stop_on_entry: bool,
) -> Result<DapSession> {
Self::launch_with(
adapter_program,
adapter_args,
cwd,
launch_request(program, interpreter, stop_on_entry),
breakpoints,
)
}
pub fn launch_with(
adapter_program: &str,
adapter_args: &[String],
cwd: &Path,
launch_request: Value,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
) -> Result<DapSession> {
let transport = DapTransport::spawn(adapter_program, adapter_args, cwd)?;
transport.send(initialize_request())?;
transport.send(launch_request)?;
Ok(Self::new_with_transport(transport, breakpoints, None))
}
pub fn launch_js(
node: &str,
server_js: &Path,
cwd: &Path,
program: &Path,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
stop_on_entry: bool,
) -> Result<DapSession> {
Self::launch_js_with(
node,
server_js,
cwd,
js_launch_request(program, cwd, stop_on_entry),
breakpoints,
)
}
pub fn launch_js_with(
node: &str,
server_js: &Path,
cwd: &Path,
start_request: Value,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
) -> Result<DapSession> {
let host = "127.0.0.1";
let port = super::transport::free_port()?;
let args = vec![
server_js.to_string_lossy().into_owned(),
port.to_string(),
host.to_string(),
];
let node_dir = super::install::node_bin_dir(node);
let transport =
DapTransport::connect_tcp_server(node, &args, cwd, host, port, node_dir.as_deref())?;
transport.send(initialize_request())?;
transport.send(start_request)?;
Ok(Self::new_with_transport(
transport,
breakpoints,
Some((host.to_string(), port)),
))
}
fn new_with_transport(
transport: DapTransport,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
js_server: Option<(String, u16)>,
) -> DapSession {
DapSession {
transport,
child: None,
js_server,
phase: SessionPhase::Initializing,
breakpoints,
stopped_thread: None,
current_location: None,
unverified_breakpoints: BTreeMap::new(),
stack_frames: Vec::new(),
scopes: Vec::new(),
variables: BTreeMap::new(),
selected_frame: None,
pending_var_refs: std::collections::HashMap::new(),
pending_evals: std::collections::HashMap::new(),
exception_filters: vec![String::from("uncaught")],
known_thread: None,
}
}
fn active(&self) -> &DapTransport {
self.child.as_ref().unwrap_or(&self.transport)
}
pub fn pause(&mut self) {
if let Some(tid) = self.stopped_thread.or(self.known_thread) {
let _ = self.active().send(thread_request("pause", tid));
}
}
pub fn set_exception_filters(&mut self, filters: Vec<String>) {
self.exception_filters = filters;
let _ = self
.transport
.send(set_exception_breakpoints_request(&self.exception_filters));
}
pub fn has_exception_filter(&self, filter: &str) -> bool {
self.exception_filters.iter().any(|f| f == filter)
}
pub fn evaluate(&mut self, expression: &str, context: &str) {
let req = evaluate_request(expression, self.selected_frame, context);
if let Ok(seq) = self.active().send(req) {
self.pending_evals
.insert(seq, (context.to_string(), expression.to_string()));
}
}
fn clear_inspection(&mut self) {
self.stack_frames.clear();
self.scopes.clear();
self.variables.clear();
self.selected_frame = None;
self.pending_var_refs.clear();
}
pub fn load_frame(&mut self, frame_id: i64) {
self.selected_frame = Some(frame_id);
self.scopes.clear();
self.variables.clear();
self.pending_var_refs.clear();
let _ = self.active().send(scopes_request(frame_id));
}
pub fn lookup_local(&self, name: &str) -> Option<&Variable> {
self.scopes
.iter()
.filter_map(|s| self.variables.get(&s.variables_ref))
.flatten()
.find(|v| v.name == name)
}
pub fn expand_variable(&mut self, variables_reference: i64) {
if variables_reference > 0 && !self.variables.contains_key(&variables_reference) {
self.request_variables(variables_reference);
}
}
fn request_variables(&mut self, variables_reference: i64) {
if let Ok(seq) = self.active().send(variables_request(variables_reference)) {
self.pending_var_refs.insert(seq, variables_reference);
}
}
fn apply_breakpoint_reports(&mut self, reports: &[BreakpointReport]) -> bool {
fold_breakpoint_reports(&mut self.unverified_breakpoints, reports)
}
pub fn poll(&mut self) -> Vec<DapEvent> {
let mut out = Vec::new();
while let Ok(msg) = self.transport.incoming.try_recv() {
self.handle_message(msg, false, &mut out);
}
let mut child_msgs = Vec::new();
if let Some(child) = self.child.as_ref() {
while let Ok(msg) = child.incoming.try_recv() {
child_msgs.push(msg);
}
}
for msg in child_msgs {
self.handle_message(msg, true, &mut out);
}
out
}
fn handle_message(&mut self, msg: Value, from_child: bool, out: &mut Vec<DapEvent>) {
if msg.get("type").and_then(Value::as_str) == Some("request") {
if let Some(req) = start_debugging_request(&msg) {
let _ = self.transport.send(reverse_request_response(
req.request_seq,
"startDebugging",
true,
));
self.open_child_session(&req.config, req.request.as_deref());
} else if let (Some(seq), Some(command)) = (
msg.get("seq").and_then(Value::as_i64),
msg.get("command").and_then(Value::as_str),
) {
let resp = reverse_request_response(seq, command, false);
if from_child {
if let Some(c) = self.child.as_ref() {
let _ = c.send(resp);
}
} else {
let _ = self.transport.send(resp);
}
}
return;
}
if msg.get("type").and_then(Value::as_str) == Some("response") {
match msg.get("command").and_then(Value::as_str) {
Some("stackTrace") => {
self.stack_frames = parse_stack_frames(&msg);
if let Some(top) = self.stack_frames.first() {
if let Some(path) = top.path.clone() {
self.current_location = Some((path, top.line));
}
let top_id = top.id;
self.load_frame(top_id);
}
out.push(DapEvent::InspectionUpdated);
}
Some("scopes") => {
self.scopes = parse_scopes(&msg);
let refs: Vec<i64> = self.scopes.iter().map(|s| s.variables_ref).collect();
for r in refs {
self.request_variables(r);
}
out.push(DapEvent::InspectionUpdated);
}
Some("variables") => {
let req_seq = msg.get("request_seq").and_then(Value::as_i64);
if let Some(reference) = req_seq.and_then(|s| self.pending_var_refs.remove(&s))
{
self.variables.insert(reference, parse_variables(&msg));
out.push(DapEvent::InspectionUpdated);
}
}
Some("evaluate") => {
let req_seq = msg.get("request_seq").and_then(Value::as_i64);
if let Some((context, expression)) =
req_seq.and_then(|s| self.pending_evals.remove(&s))
{
let success = msg.get("success").and_then(Value::as_bool).unwrap_or(false);
let result = parse_evaluate_result(&msg).unwrap_or_else(|| {
msg.get("message")
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
});
out.push(DapEvent::Evaluated {
context,
expression,
result,
success,
});
}
}
Some("setBreakpoints") if self.js_server.is_none() => {
let reports = breakpoint_reports(&msg);
if self.apply_breakpoint_reports(&reports) {
out.push(DapEvent::BreakpointsUpdated);
}
}
_ => {}
}
return;
}
if msg.get("event").and_then(Value::as_str) == Some("thread") {
if let Some(tid) = msg
.get("body")
.and_then(|b| b.get("threadId"))
.and_then(Value::as_i64)
{
self.known_thread = Some(tid);
}
return;
}
if msg.get("event").and_then(Value::as_str) == Some("breakpoint") {
if self.js_server.is_none() {
let reports = breakpoint_reports(&msg);
if self.apply_breakpoint_reports(&reports) {
out.push(DapEvent::BreakpointsUpdated);
}
}
return;
}
let Some(event) = classify_event(&msg) else {
return;
};
match &event {
DapEvent::Initialized => {
self.push_breakpoints();
let t = self.active();
let _ = t.send(set_exception_breakpoints_request(&self.exception_filters));
let _ = t.send(configuration_done_request());
self.phase = SessionPhase::Running;
}
DapEvent::Stopped { thread_id, .. } => {
self.stopped_thread = Some(*thread_id);
self.known_thread = Some(*thread_id);
self.phase = SessionPhase::Stopped;
self.clear_inspection();
let _ = self.active().send(stack_trace_request(*thread_id));
}
DapEvent::Continued => {
self.phase = SessionPhase::Running;
self.current_location = None;
self.clear_inspection();
}
DapEvent::Terminated => {
if from_child || self.child.is_none() {
self.phase = SessionPhase::Terminated;
self.current_location = None;
self.clear_inspection();
}
}
DapEvent::Output { .. } => {}
DapEvent::BreakpointsUpdated
| DapEvent::InspectionUpdated
| DapEvent::Evaluated { .. } => {}
}
if from_child || !matches!(event, DapEvent::Terminated) || self.child.is_none() {
out.push(event);
}
}
fn open_child_session(&mut self, config: &Value, outer_request: Option<&str>) {
let Some((host, port)) = self.js_server.clone() else {
return;
};
match DapTransport::connect_tcp(&host, port) {
Ok(child) => {
let _ = child.send(initialize_request());
let _ = child.send(js_child_launch_request(config, outer_request));
self.child = Some(child);
}
Err(e) => {
super::log::log(&format!("js-debug child connect failed: {e}"));
}
}
}
fn push_breakpoints(&mut self) {
let t = self.active();
for (path, lines) in &self.breakpoints {
let _ = t.send(set_breakpoints_request(path, lines));
}
}
pub fn continue_execution(&mut self) {
if let Some(tid) = self.stopped_thread {
let _ = self.active().send(thread_request("continue", tid));
self.phase = SessionPhase::Running;
}
}
pub fn update_breakpoints(&mut self, path: &Path, breakpoints: &[SourceBreakpoint]) {
let _ = self
.active()
.send(set_breakpoints_request(path, breakpoints));
}
pub fn step(&mut self, command: &str) {
if let Some(tid) = self.stopped_thread {
let _ = self.active().send(thread_request(command, tid));
}
}
pub fn disconnect(&mut self) {
let req = json!({
"type": "request",
"command": "disconnect",
"arguments": { "terminateDebuggee": true }
});
if let Some(child) = self.child.as_ref() {
let _ = child.send(req.clone());
}
let _ = self.transport.send(req);
self.phase = SessionPhase::Terminated;
}
}
pub fn inline_locals(
scopes: &[Scope],
variables: &std::collections::BTreeMap<i64, Vec<Variable>>,
) -> Vec<(String, String)> {
let local_refs: Vec<i64> = scopes
.iter()
.filter(|s| s.name.to_lowercase().contains("local"))
.map(|s| s.variables_ref)
.collect();
let refs: Vec<i64> = if local_refs.is_empty() {
scopes
.first()
.map(|s| s.variables_ref)
.into_iter()
.collect()
} else {
local_refs
};
refs.iter()
.filter_map(|r| variables.get(r))
.flatten()
.map(|v| (v.name.clone(), v.value.clone()))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn inline_locals_prefer_local_scopes_and_fall_back_to_the_first() {
let mut vars = std::collections::BTreeMap::new();
vars.insert(
1,
vec![Variable {
name: String::from("g"),
value: String::from("0"),
type_name: String::new(),
variables_ref: 0,
}],
);
vars.insert(
2,
vec![Variable {
name: String::from("x"),
value: String::from("1"),
type_name: String::new(),
variables_ref: 0,
}],
);
let scopes = vec![
Scope {
name: String::from("Globals"),
variables_ref: 1,
},
Scope {
name: String::from("Locals"),
variables_ref: 2,
},
];
assert_eq!(
inline_locals(&scopes, &vars),
vec![(String::from("x"), String::from("1"))],
"a Locals scope excludes globals"
);
let unnamed = vec![Scope {
name: String::from("Registers"),
variables_ref: 1,
}];
assert_eq!(
inline_locals(&unnamed, &vars),
vec![(String::from("g"), String::from("0"))],
"no local-named scope falls back to the first"
);
}
#[test]
fn classifies_stopped_event_with_thread_and_reason() {
let msg = json!({
"type": "event", "event": "stopped",
"body": { "threadId": 1, "reason": "breakpoint" }
});
assert_eq!(
classify_event(&msg),
Some(DapEvent::Stopped {
thread_id: 1,
reason: "breakpoint".into()
})
);
}
#[test]
fn classifies_initialized_and_terminated() {
assert_eq!(
classify_event(&json!({"type": "event", "event": "initialized"})),
Some(DapEvent::Initialized)
);
assert_eq!(
classify_event(&json!({"type": "event", "event": "terminated"})),
Some(DapEvent::Terminated)
);
assert_eq!(
classify_event(&json!({"type": "event", "event": "exited"})),
Some(DapEvent::Terminated)
);
}
#[test]
fn js_launch_request_is_pwa_node_with_source_maps() {
let req = js_launch_request(Path::new("/proj/app.ts"), Path::new("/proj"), false);
assert_eq!(req["command"], "launch");
assert_eq!(req["arguments"]["type"], "pwa-node");
assert_eq!(req["arguments"]["request"], "launch");
assert_eq!(req["arguments"]["program"], "/proj/app.ts");
assert_eq!(req["arguments"]["cwd"], "/proj");
assert_eq!(req["arguments"]["sourceMaps"], true);
assert_eq!(req["arguments"]["console"], "internalConsole");
}
#[test]
fn initialize_advertises_start_debugging_support() {
let req = initialize_request();
assert_eq!(req["arguments"]["supportsStartDebuggingRequest"], true);
}
#[test]
fn start_debugging_reverse_request_is_recognised_and_yields_child_config() {
let msg = json!({
"type": "request", "seq": 8, "command": "startDebugging",
"arguments": {
"request": "launch",
"configuration": {
"type": "pwa-node",
"name": "target.js [60277]",
"__pendingTargetId": "dd35f91abc4e878814ccfee3"
}
}
});
let parsed = start_debugging_request(&msg).expect("must recognise startDebugging");
assert_eq!(parsed.request_seq, 8);
assert_eq!(
parsed.config["__pendingTargetId"],
"dd35f91abc4e878814ccfee3"
);
assert_eq!(parsed.config["type"], "pwa-node");
}
#[test]
fn js_child_request_follows_the_configurations_request_kind() {
let launch_cfg = json!({ "type": "pwa-node", "__pendingTargetId": "x" });
assert_eq!(
js_child_launch_request(&launch_cfg, None)["command"],
"launch"
);
let attach_cfg =
json!({ "type": "pwa-node", "request": "attach", "__pendingTargetId": "x" });
let req = js_child_launch_request(&attach_cfg, None);
assert_eq!(req["command"], "attach");
assert_eq!(req["arguments"]["__pendingTargetId"], "x");
let bare_cfg = json!({ "type": "pwa-node", "__pendingTargetId": "x" });
assert_eq!(
js_child_launch_request(&bare_cfg, Some("attach"))["command"],
"attach"
);
assert_eq!(
js_child_launch_request(&attach_cfg, Some("launch"))["command"],
"attach"
);
}
#[test]
fn start_debugging_reverse_request_carries_the_outer_request_kind() {
let msg = json!({
"type": "request", "seq": 9, "command": "startDebugging",
"arguments": {
"request": "attach",
"configuration": { "type": "pwa-node", "__pendingTargetId": "t" }
}
});
let parsed = start_debugging_request(&msg).expect("recognised");
assert_eq!(parsed.request.as_deref(), Some("attach"));
let bare = json!({
"type": "request", "seq": 10, "command": "startDebugging",
"arguments": { "configuration": { "type": "pwa-node" } }
});
assert_eq!(start_debugging_request(&bare).unwrap().request, None);
}
#[test]
fn non_start_debugging_messages_are_not_mistaken_for_it() {
assert!(start_debugging_request(&json!({"type": "event", "event": "stopped"})).is_none());
assert!(
start_debugging_request(
&json!({"type": "request", "seq": 1, "command": "runInTerminal"})
)
.is_none()
);
}
#[test]
fn lldb_launch_request_carries_binary_not_interpreter() {
let req = lldb_launch_request(Path::new("/build/app"), false);
assert_eq!(req["command"], "launch");
assert_eq!(req["arguments"]["program"], "/build/app");
assert!(req["arguments"].get("python").is_none());
}
#[test]
fn set_exception_breakpoints_request_lists_filters() {
let req =
set_exception_breakpoints_request(&[String::from("uncaught"), String::from("raised")]);
assert_eq!(req["command"], "setExceptionBreakpoints");
assert_eq!(req["arguments"]["filters"][0], "uncaught");
assert_eq!(req["arguments"]["filters"][1], "raised");
}
#[test]
fn evaluate_request_carries_expression_frame_and_context() {
let with_frame = evaluate_request("x + 1", Some(42), "repl");
assert_eq!(with_frame["command"], "evaluate");
assert_eq!(with_frame["arguments"]["expression"], "x + 1");
assert_eq!(with_frame["arguments"]["frameId"], 42);
assert_eq!(with_frame["arguments"]["context"], "repl");
let no_frame = evaluate_request("len(xs)", None, "watch");
assert!(no_frame["arguments"].get("frameId").is_none());
}
#[test]
fn parse_evaluate_result_reads_body_result() {
let resp = json!({ "body": { "result": "3", "type": "int" } });
assert_eq!(parse_evaluate_result(&resp).as_deref(), Some("3"));
assert_eq!(parse_evaluate_result(&json!({"body": {}})), None);
}
#[test]
fn reverse_request_response_references_request_seq() {
let r = reverse_request_response(42, "runInTerminal", false);
assert_eq!(r["type"], "response");
assert_eq!(r["request_seq"], 42);
assert_eq!(r["command"], "runInTerminal");
assert_eq!(r["success"], false);
assert_eq!(r["message"], "unsupported by croft");
let ok = reverse_request_response(1, "startDebugging", true);
assert_eq!(ok["success"], true);
assert!(ok["message"].is_null());
}
#[test]
fn breakpoint_reports_parses_response_array() {
let msg = json!({
"type": "response", "command": "setBreakpoints",
"body": { "breakpoints": [
{ "verified": true, "line": 3, "source": { "path": "/a.py" } },
{ "verified": false, "line": 7, "source": { "path": "/a.py" } },
]}
});
let reports = breakpoint_reports(&msg);
assert_eq!(reports.len(), 2);
assert_eq!(reports[1].line, 7);
assert!(!reports[1].verified);
}
#[test]
fn breakpoint_reports_parses_singular_event_and_skips_line_zero() {
let event = json!({
"type": "event", "event": "breakpoint",
"body": { "reason": "changed",
"breakpoint": { "verified": true, "line": 5, "source": { "path": "/b.py" } } }
});
let reports = breakpoint_reports(&event);
assert_eq!(reports.len(), 1);
assert_eq!(reports[0].path, PathBuf::from("/b.py"));
let unresolved = json!({
"type": "response", "command": "setBreakpoints",
"body": { "breakpoints": [
{ "verified": true, "line": 0, "source": { "path": "/c.py" } } ]}
});
assert!(breakpoint_reports(&unresolved).is_empty());
}
#[test]
fn fold_breakpoint_reports_tracks_only_unverified() {
let mut map = BTreeMap::new();
let p = PathBuf::from("/a.py");
let changed = fold_breakpoint_reports(
&mut map,
&[
BreakpointReport {
path: p.clone(),
line: 3,
verified: true,
},
BreakpointReport {
path: p.clone(),
line: 7,
verified: false,
},
],
);
assert!(changed);
assert_eq!(
map.get(&p).unwrap().iter().copied().collect::<Vec<_>>(),
vec![7]
);
let changed = fold_breakpoint_reports(
&mut map,
&[BreakpointReport {
path: p.clone(),
line: 7,
verified: true,
}],
);
assert!(changed);
assert!(!map.contains_key(&p));
assert!(!fold_breakpoint_reports(&mut map, &[]));
}
#[test]
fn telemetry_output_is_filtered_but_program_output_is_kept() {
assert!(!output_is_user_visible("telemetry"));
assert!(output_is_user_visible("stdout"));
assert!(output_is_user_visible("stderr"));
assert!(output_is_user_visible("console"));
}
#[test]
fn classifies_output_event() {
let msg = json!({
"type": "event", "event": "output",
"body": { "category": "stdout", "output": "hello\n" }
});
assert_eq!(
classify_event(&msg),
Some(DapEvent::Output {
category: "stdout".into(),
text: "hello\n".into()
})
);
}
#[test]
fn ignores_responses_and_unknown_events() {
assert_eq!(
classify_event(&json!({"type": "response", "command": "initialize"})),
None
);
assert_eq!(
classify_event(&json!({"type": "event", "event": "module"})),
None
);
}
#[test]
fn set_breakpoints_request_maps_lines_to_objects() {
let req = set_breakpoints_request(
Path::new("/a/b.py"),
&[
SourceBreakpoint::plain(2),
SourceBreakpoint {
line: 7,
condition: Some(String::from("i > 3")),
log_message: None,
},
],
);
assert_eq!(req["command"], "setBreakpoints");
assert_eq!(req["arguments"]["source"]["path"], "/a/b.py");
let bps = req["arguments"]["breakpoints"].as_array().unwrap();
assert_eq!(bps.len(), 2);
assert_eq!(bps[0]["line"], 2);
assert!(bps[0].get("condition").is_none());
assert_eq!(bps[1]["line"], 7);
assert_eq!(bps[1]["condition"], "i > 3");
}
#[test]
fn set_breakpoints_request_carries_log_messages() {
let req = set_breakpoints_request(
Path::new("/a/b.py"),
&[
SourceBreakpoint {
line: 4,
condition: None,
log_message: Some(String::from("x is {x}")),
},
SourceBreakpoint {
line: 9,
condition: Some(String::from("n > 0")),
log_message: Some(String::from("n={n}")),
},
SourceBreakpoint::plain(11),
],
);
let bps = req["arguments"]["breakpoints"].as_array().unwrap();
assert_eq!(bps[0]["logMessage"], "x is {x}");
assert!(bps[0].get("condition").is_none());
assert_eq!(bps[1]["condition"], "n > 0");
assert_eq!(bps[1]["logMessage"], "n={n}");
assert!(bps[2].get("logMessage").is_none());
}
#[test]
fn pytest_debug_launch_request_launches_the_pytest_module() {
let req = pytest_debug_launch_request(
Path::new("/proj/.venv/bin/python"),
Path::new("/proj"),
"test_addition",
);
assert_eq!(req["command"], "launch");
assert_eq!(req["arguments"]["module"], "pytest");
assert!(
req["arguments"].get("program").is_none(),
"a module launch must not also name a program"
);
let args = req["arguments"]["args"].as_array().unwrap();
assert_eq!(args[0], "-v");
assert_eq!(args[1], "-k");
assert_eq!(args[2], "test_addition");
assert_eq!(req["arguments"]["python"][0], "/proj/.venv/bin/python");
assert_eq!(req["arguments"]["cwd"], "/proj");
assert_eq!(req["arguments"]["justMyCode"], false);
}
#[test]
fn lldb_test_launch_request_carries_the_filter_args() {
let req = lldb_test_launch_request(
Path::new("/proj/target/debug/deps/croft-abc123"),
&[String::from("my_case"), String::from("--nocapture")],
);
assert_eq!(req["command"], "launch");
assert_eq!(
req["arguments"]["program"],
"/proj/target/debug/deps/croft-abc123"
);
let args = req["arguments"]["args"].as_array().unwrap();
assert_eq!(args[0], "my_case");
assert_eq!(args[1], "--nocapture");
}
#[test]
fn launch_request_carries_program_and_interpreter() {
let req = launch_request(Path::new("/w/app.py"), Path::new("/v/bin/python"), false);
assert_eq!(req["command"], "launch");
assert_eq!(req["arguments"]["program"], "/w/app.py");
assert_eq!(req["arguments"]["python"][0], "/v/bin/python");
assert_eq!(req["arguments"]["request"], "launch");
}
#[test]
fn thread_request_carries_thread_id() {
let req = thread_request("continue", 3);
assert_eq!(req["command"], "continue");
assert_eq!(req["arguments"]["threadId"], 3);
}
#[test]
fn stack_trace_request_targets_full_stack() {
let req = stack_trace_request(5);
assert_eq!(req["command"], "stackTrace");
assert_eq!(req["arguments"]["threadId"], 5);
assert_eq!(req["arguments"]["startFrame"], 0);
assert!(req["arguments"].get("levels").is_none());
}
#[test]
fn parse_stack_frames_reads_all_frames_with_ids() {
let resp = json!({
"type": "response", "command": "stackTrace",
"body": { "stackFrames": [
{ "id": 1000, "name": "isValid", "source": { "path": "/w/app.py" }, "line": 12 },
{ "id": 1001, "name": "<module>", "source": { "path": "/w/app.py" }, "line": 24 }
]}
});
let frames = parse_stack_frames(&resp);
assert_eq!(frames.len(), 2);
assert_eq!(frames[0].id, 1000);
assert_eq!(frames[0].name, "isValid");
assert_eq!(frames[0].path, Some(PathBuf::from("/w/app.py")));
assert_eq!(frames[0].line, 12);
assert_eq!(frames[1].id, 1001);
}
#[test]
fn parse_stack_frames_empty_when_malformed() {
assert!(parse_stack_frames(&json!({"body": {}})).is_empty());
assert!(parse_stack_frames(&json!({})).is_empty());
}
#[test]
fn parse_scopes_and_variables() {
let scopes = parse_scopes(&json!({
"body": { "scopes": [
{ "name": "Locals", "variablesReference": 7 },
{ "name": "Globals", "variablesReference": 8 }
]}
}));
assert_eq!(scopes.len(), 2);
assert_eq!(scopes[0].name, "Locals");
assert_eq!(scopes[0].variables_ref, 7);
let vars = parse_variables(&json!({
"body": { "variables": [
{ "name": "x", "value": "1", "type": "int", "variablesReference": 0 },
{ "name": "obj", "value": "<Foo>", "type": "Foo", "variablesReference": 9 }
]}
}));
assert_eq!(vars.len(), 2);
assert_eq!(vars[0].name, "x");
assert_eq!(vars[0].value, "1");
assert_eq!(vars[0].type_name, "int");
assert_eq!(vars[0].variables_ref, 0);
assert_eq!(
vars[1].variables_ref, 9,
"expandable variable keeps its ref"
);
}
#[test]
#[ignore = "requires ~/.croft/debug-venv (uv + debugpy on CPython 3.14)"]
fn launches_debugpy_and_stops_at_breakpoint() {
use std::io::Write;
let py = crate::dap::install::ensure_debug_venv().expect("provision debug venv");
let mut f = tempfile::Builder::new().suffix(".py").tempfile().unwrap();
writeln!(f, "x = 1\ny = 2\nz = x + y\nprint(z)").unwrap();
let path = f.path().canonicalize().unwrap();
let mut bps = BTreeMap::new();
bps.insert(path.clone(), vec![SourceBreakpoint::plain(3)]); let mut sess = DapSession::launch(
&py.to_string_lossy(),
&["-m".to_string(), "debugpy.adapter".to_string()],
path.parent().unwrap(),
&path,
&py,
bps,
false,
)
.unwrap();
let mut stopped = false;
for _ in 0..100 {
for ev in sess.poll() {
if matches!(ev, DapEvent::Stopped { .. }) {
stopped = true;
}
}
if sess.current_location.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
sess.disconnect();
assert!(stopped, "expected a `stopped` event from debugpy");
let (_loc, line) = sess.current_location.clone().expect("a paused location");
assert_eq!(line, 3, "should pause on the breakpoint line");
}
#[test]
#[ignore = "requires node + ~/.croft/js-debug (vscode-js-debug server)"]
fn launches_js_debug_and_stops_at_breakpoint() {
use std::io::Write;
let node = crate::dap::install::node_program().expect("node on PATH");
let server = crate::dap::install::ensure_js_debug().expect("provision js-debug");
let mut f = tempfile::Builder::new().suffix(".js").tempfile().unwrap();
writeln!(
f,
"const a = 1;\nconst b = 2;\nconst c = a + b;\nconsole.log(c);"
)
.unwrap();
let path = f.path().canonicalize().unwrap();
let mut bps = BTreeMap::new();
bps.insert(path.clone(), vec![SourceBreakpoint::plain(3)]); let mut sess =
DapSession::launch_js(&node, &server, path.parent().unwrap(), &path, bps, false)
.unwrap();
let mut stopped = false;
for _ in 0..200 {
for ev in sess.poll() {
if matches!(ev, DapEvent::Stopped { .. }) {
stopped = true;
}
}
if sess.current_location.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
sess.disconnect();
assert!(
stopped,
"expected a `stopped` event from js-debug's child session"
);
let (_loc, line) = sess.current_location.clone().expect("a paused location");
assert_eq!(line, 3, "should pause on the breakpoint line");
}
#[test]
#[ignore = "requires ~/.croft/debug-venv (uv + debugpy on CPython 3.14)"]
fn inspection_chain_populates_stack_and_locals() {
use std::io::Write;
let py = crate::dap::install::ensure_debug_venv().expect("provision debug venv");
let mut f = tempfile::Builder::new().suffix(".py").tempfile().unwrap();
writeln!(f, "x = 1\ny = 2\nz = x + y\nprint(z)").unwrap();
let path = f.path().canonicalize().unwrap();
let mut bps = BTreeMap::new();
bps.insert(path.clone(), vec![SourceBreakpoint::plain(3)]);
let mut sess = DapSession::launch(
&py.to_string_lossy(),
&["-m".to_string(), "debugpy.adapter".to_string()],
path.parent().unwrap(),
&path,
&py,
bps,
false,
)
.unwrap();
let mut have_locals = false;
for _ in 0..200 {
sess.poll();
let names: Vec<&str> = sess
.variables
.values()
.flatten()
.map(|v| v.name.as_str())
.collect();
if names.contains(&"x") && names.contains(&"y") {
have_locals = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let frames = sess.stack_frames.clone();
let xy: Vec<(String, String)> = sess
.variables
.values()
.flatten()
.filter(|v| v.name == "x" || v.name == "y")
.map(|v| (v.name.clone(), v.value.clone()))
.collect();
sess.disconnect();
assert!(
!frames.is_empty(),
"call stack must be populated at the stop"
);
assert!(have_locals, "locals x and y must arrive via the chain");
assert!(xy.contains(&("x".to_string(), "1".to_string())));
assert!(xy.contains(&("y".to_string(), "2".to_string())));
let x = sess.lookup_local("x").expect("lookup_local should find x");
assert_eq!(x.value, "1");
assert!(sess.lookup_local("nonexistent").is_none());
}
#[test]
#[ignore = "requires lldb-dap (Xcode Command Line Tools) + cc"]
fn lldb_dap_session_launches_via_shared_machinery() {
use std::io::Write;
let adapter = "/Library/Developer/CommandLineTools/usr/bin/lldb-dap";
if !std::path::Path::new(adapter).is_file() {
return;
}
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("m.c");
let mut f = std::fs::File::create(&src).unwrap();
writeln!(f, "#include <stdio.h>\nint main(){{\n int x=41;\n x++;\n printf(\"%d\\n\", x);\n return 0;\n}}").unwrap();
let bin = dir.path().join("m.dbg");
let ok = std::process::Command::new("cc")
.args([
"-g",
"-O0",
src.to_str().unwrap(),
"-o",
bin.to_str().unwrap(),
])
.status()
.map(|s| s.success())
.unwrap_or(false);
assert!(ok, "cc must compile the test program");
let mut sess = DapSession::launch_with(
adapter,
&[],
dir.path(),
lldb_launch_request(&bin, false),
BTreeMap::new(),
)
.unwrap();
let mut terminated = false;
for _ in 0..200 {
for ev in sess.poll() {
if matches!(ev, DapEvent::Terminated) {
terminated = true;
}
}
if terminated {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
sess.disconnect();
assert!(
terminated,
"lldb-dap session must launch and run to completion via launch_with"
);
}
#[test]
#[ignore = "requires ~/.croft/debug-venv (uv + debugpy on CPython 3.14)"]
fn binds_breakpoint_set_via_symlinked_path() {
use std::io::Write;
let py = crate::dap::install::ensure_debug_venv().expect("provision debug venv");
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("real");
std::fs::create_dir_all(&real).unwrap();
let mut f = std::fs::File::create(real.join("m.py")).unwrap();
writeln!(f, "a = 1\nb = 2\nc = a + b\nprint(c)").unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
let via_link = link.join("m.py");
assert_ne!(
via_link,
via_link.canonicalize().unwrap(),
"test setup: path must be non-canonical"
);
let mut bps = BTreeMap::new();
bps.insert(via_link.clone(), vec![SourceBreakpoint::plain(3)]);
let mut sess = DapSession::launch(
&py.to_string_lossy(),
&["-m".to_string(), "debugpy.adapter".to_string()],
&link,
&via_link,
&py,
bps,
false,
)
.unwrap();
let mut stopped = false;
for _ in 0..100 {
for ev in sess.poll() {
if matches!(ev, DapEvent::Stopped { .. }) {
stopped = true;
}
}
if sess.current_location.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
sess.disconnect();
assert!(
stopped,
"breakpoint via symlinked path must still bind+stop"
);
let (loc, line) = sess.current_location.clone().expect("a paused location");
assert_eq!(line, 3);
assert_eq!(loc, via_link, "debugpy must report the path as launched");
}
}