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,
},
ExceptionInfo { summary: String },
}
fn launch_failure_reason(msg: &Value) -> String {
msg.pointer("/body/error/format")
.and_then(Value::as_str)
.or_else(|| msg.get("message").and_then(Value::as_str))
.filter(|s| !s.is_empty())
.unwrap_or("the debug adapter refused to start the program")
.to_string()
}
#[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,
Delve,
}
pub fn delve_zero_config_request(file: &Path) -> Value {
let dir = file.parent().unwrap_or_else(|| Path::new("."));
let is_test = file
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.ends_with("_test.go"));
json!({
"type": "request",
"command": "launch",
"arguments": {
"mode": if is_test { "test" } else { "debug" },
"program": dir.to_string_lossy(),
"cwd": dir.to_string_lossy(),
"stopOnEntry": false,
}
})
}
pub fn with_remote_output(mut request: Value) -> Value {
if request["command"] == "launch"
&& let Some(args) = request.get_mut("arguments").and_then(Value::as_object_mut)
{
args.entry("outputMode").or_insert_with(|| json!("remote"));
}
request
}
pub fn delve_test_request(dir: &Path, args: &[String]) -> Value {
json!({
"type": "request",
"command": "launch",
"arguments": {
"mode": "test",
"program": dir.to_string_lossy(),
"cwd": dir.to_string_lossy(),
"args": args,
"stopOnEntry": false,
}
})
}
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": true
}
})
}
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": true
}
})
}
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>,
pub hit_condition: Option<String>,
}
impl SourceBreakpoint {
pub fn plain(line: u32) -> Self {
Self {
line,
condition: None,
log_message: None,
hit_condition: 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);
}
if let Some(h) = &b.hit_condition {
bp["hitCondition"] = json!(h);
}
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 set_function_breakpoints_request(names: &[String]) -> Value {
let bps: Vec<Value> = names.iter().map(|n| json!({ "name": n })).collect();
json!({
"type": "request",
"command": "setFunctionBreakpoints",
"arguments": { "breakpoints": bps }
})
}
pub fn data_breakpoint_info_request(variables_reference: i64, name: &str) -> Value {
json!({
"type": "request",
"command": "dataBreakpointInfo",
"arguments": { "variablesReference": variables_reference, "name": name }
})
}
pub fn set_data_breakpoints_request(data_ids: &[String]) -> Value {
let bps: Vec<Value> = data_ids
.iter()
.map(|id| json!({ "dataId": id, "accessType": "write" }))
.collect();
json!({
"type": "request",
"command": "setDataBreakpoints",
"arguments": { "breakpoints": bps }
})
}
pub fn configuration_done_request() -> Value {
json!({ "type": "request", "command": "configurationDone", "arguments": {} })
}
const RAISED_FILTER_IDS: &[&str] = &["raised", "all", "caught"];
const THROW_FILTER_IDS: &[&str] = &["cpp_throw", "objc_throw", "swift_throw"];
fn raised_filter_ids(offered: &[(String, bool)]) -> Option<Vec<String>> {
let has = |id: &str| offered.iter().any(|(o, _)| o == id);
if let Some(id) = RAISED_FILTER_IDS.iter().find(|id| has(id)) {
return Some(vec![id.to_string()]);
}
let throws: Vec<String> = THROW_FILTER_IDS
.iter()
.filter(|id| has(id))
.map(|id| id.to_string())
.collect();
(!throws.is_empty()).then_some(throws)
}
fn offered_exception_filters(caps: &Value) -> Option<Vec<(String, bool)>> {
let list = caps.get("exceptionBreakpointFilters")?.as_array()?;
Some(
list.iter()
.filter_map(|f| {
let id = f.get("filter")?.as_str()?.to_string();
Some((id, f.get("default").and_then(Value::as_bool) == Some(true)))
})
.collect(),
)
}
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 threads_request() -> Value {
json!({ "type": "request", "command": "threads" })
}
pub fn parse_threads(msg: &Value) -> Vec<(i64, String)> {
msg.pointer("/body/threads")
.and_then(Value::as_array)
.map(|ts| {
ts.iter()
.filter_map(|t| {
Some((
t.get("id")?.as_i64()?,
t.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
))
})
.collect()
})
.unwrap_or_default()
}
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 exception_summary(response: &Value) -> Option<String> {
let body = response.get("body")?;
let text = |pointer: &str| {
body.pointer(pointer)
.and_then(Value::as_str)
.map(str::trim)
.unwrap_or("")
};
let id = text("/exceptionId")
.split("(note:")
.next()
.unwrap_or("")
.trim();
let description = [text("/description"), text("/details/message")]
.into_iter()
.find(|s| !s.is_empty())
.and_then(|s| s.lines().next())
.unwrap_or("")
.trim();
match (id.is_empty(), description.is_empty()) {
(true, true) => None,
(false, true) => Some(id.to_string()),
(true, false) => Some(description.to_string()),
(false, false) if description.starts_with(id) => Some(description.to_string()),
(false, false) => Some(format!("{id}: {description}")),
}
}
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,
pub expensive: bool,
}
#[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()?,
expensive: s.get("expensive").and_then(Value::as_bool) == Some(true),
})
})
.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 update_breakpoint_lines(
map: &mut BTreeMap<PathBuf, std::collections::BTreeSet<usize>>,
reports: &[BreakpointReport],
) -> bool {
let mut changed = false;
for r in reports {
let set = map.entry(r.path.clone()).or_default();
changed |= if r.verified {
set.remove(&r.line)
} else {
set.insert(r.line)
};
if set.is_empty() {
map.remove(&r.path);
}
}
changed
}
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 NamedSession<S = DapSession> {
pub name: String,
pub session: S,
pub backlog: Vec<DapEvent>,
}
pub struct DebugSessions<S = DapSession> {
sessions: Vec<NamedSession<S>>,
focused: usize,
}
impl<S> Default for DebugSessions<S> {
fn default() -> Self {
Self {
sessions: Vec::new(),
focused: 0,
}
}
}
impl<S> DebugSessions<S> {
pub fn is_empty(&self) -> bool {
self.sessions.is_empty()
}
pub fn len(&self) -> usize {
self.sessions.len()
}
pub fn focused(&self) -> Option<&S> {
self.sessions.get(self.focused).map(|s| &s.session)
}
pub fn focused_name(&self) -> Option<&str> {
self.sessions.get(self.focused).map(|s| s.name.as_str())
}
pub fn focused_mut(&mut self) -> Option<&mut S> {
self.sessions.get_mut(self.focused).map(|s| &mut s.session)
}
pub fn replace_with(&mut self, name: impl Into<String>, session: S) {
self.sessions.clear();
self.sessions.push(NamedSession {
name: name.into(),
session,
backlog: Vec::new(),
});
self.focused = 0;
}
pub fn push(&mut self, name: impl Into<String>, session: S) {
self.sessions.push(NamedSession {
name: name.into(),
session,
backlog: Vec::new(),
});
self.focused = self.sessions.len() - 1;
}
pub fn focus(&mut self, index: usize) -> bool {
if index < self.sessions.len() {
self.focused = index;
true
} else {
false
}
}
pub fn names(&self) -> Vec<String> {
self.sessions.iter().map(|s| s.name.clone()).collect()
}
pub fn remove(&mut self, index: usize) -> Option<NamedSession<S>> {
if index >= self.sessions.len() {
return None;
}
let gone = self.sessions.remove(index);
if self.focused > index || self.focused >= self.sessions.len() {
self.focused = self.focused.saturating_sub(1);
}
Some(gone)
}
pub fn focused_index(&self) -> usize {
self.focused
}
pub fn iter_named_mut_indexed(
&mut self,
) -> impl Iterator<Item = (usize, &mut NamedSession<S>)> {
self.sessions.iter_mut().enumerate()
}
pub fn take_focused_backlog(&mut self) -> Vec<DapEvent> {
self.sessions
.get_mut(self.focused)
.map(|s| std::mem::take(&mut s.backlog))
.unwrap_or_default()
}
pub fn clear(&mut self) {
self.sessions.clear();
self.focused = 0;
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut S> {
self.sessions.iter_mut().map(|s| &mut s.session)
}
}
pub struct DapSession {
transport: DapTransport,
child: Option<DapTransport>,
js_server: Option<(String, u16)>,
pub phase: SessionPhase,
pub launch_error: Option<String>,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
pub stopped_thread: Option<i64>,
pub threads: Vec<(i64, String)>,
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 open_expensive_scopes: std::collections::BTreeSet<(String, usize)>,
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)>,
exception_info_seq: Option<i64>,
pub exception_filters: Vec<String>,
pending_raised: Option<bool>,
known_thread: Option<i64>,
pub capabilities: Value,
pub function_breakpoints: Vec<String>,
run_to: Option<(PathBuf, u32)>,
pub data_breakpoints: Vec<(String, String)>,
pending_data_info: std::collections::HashMap<i64, String>,
attached: bool,
build_dir: Option<DebugBuildDir>,
}
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())?;
let attached = is_attach(&launch_request);
transport.send(launch_request)?;
let mut session = Self::new_with_transport(transport, breakpoints, None);
session.attached = attached;
Ok(session)
}
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)),
))
}
pub fn launch_delve(
dlv: &Path,
cwd: &Path,
start_request: Value,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
) -> Result<DapSession> {
let build_dir = delve_builds(&start_request)
.then(DebugBuildDir::create)
.and_then(std::io::Result::ok);
let start_request = match &build_dir {
Some(dir) => with_build_output(start_request, dir.path()),
None => start_request,
};
let host = "127.0.0.1";
let port = super::transport::free_port()?;
let args = vec![String::from("dap"), format!("--listen={host}:{port}")];
let transport =
DapTransport::connect_tcp_server(&dlv.to_string_lossy(), &args, cwd, host, port, None)?;
transport.send(initialize_request())?;
let attached = is_attach(&start_request);
transport.send(with_remote_output(start_request))?;
let mut session = Self::new_with_transport(transport, breakpoints, None);
session.attached = attached;
session.build_dir = build_dir;
Ok(session)
}
pub fn attach_delve_server(
host: &str,
port: u16,
attach_request: Value,
breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
) -> Result<DapSession> {
let transport = DapTransport::connect_tcp(host, port)?;
transport.send(initialize_request())?;
transport.send(attach_request)?;
let mut session = Self::new_with_transport(transport, breakpoints, None);
session.attached = true;
Ok(session)
}
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,
launch_error: None,
breakpoints,
stopped_thread: None,
threads: Vec::new(),
current_location: None,
unverified_breakpoints: BTreeMap::new(),
stack_frames: Vec::new(),
scopes: Vec::new(),
open_expensive_scopes: std::collections::BTreeSet::new(),
variables: BTreeMap::new(),
selected_frame: None,
pending_var_refs: std::collections::HashMap::new(),
pending_evals: std::collections::HashMap::new(),
exception_info_seq: None,
exception_filters: vec![String::from("uncaught")],
pending_raised: None,
known_thread: None,
capabilities: Value::Null,
function_breakpoints: Vec::new(),
run_to: None,
data_breakpoints: Vec::new(),
pending_data_info: std::collections::HashMap::new(),
attached: false,
build_dir: 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
.active()
.send(set_exception_breakpoints_request(&self.exception_filters));
}
pub fn raised_exception_filters(&self) -> Option<Vec<String>> {
raised_filter_ids(&offered_exception_filters(&self.capabilities)?)
}
pub fn toggle_raised_exceptions(&mut self) -> Option<bool> {
if self.capabilities.is_null() {
let on = !self.pending_raised.unwrap_or(false);
self.pending_raised = Some(on);
return Some(on);
}
let raised = self.raised_exception_filters()?;
let on = !raised.iter().any(|r| self.has_exception_filter(r));
let mut filters: Vec<String> = self
.exception_filters
.iter()
.filter(|f| !raised.contains(f))
.cloned()
.collect();
if on {
filters.extend(raised);
}
self.set_exception_filters(filters);
Some(on)
}
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 select_thread(&mut self, thread_id: i64) {
if self.phase != SessionPhase::Stopped || self.stopped_thread == Some(thread_id) {
return;
}
self.stopped_thread = Some(thread_id);
self.known_thread = Some(thread_id);
self.clear_inspection();
let _ = self.active().send(stack_trace_request(thread_id));
}
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)
}
fn scope_key(&self, index: usize) -> Option<(String, usize)> {
let scope = self.scopes.get(index)?;
let nth = self.scopes[..index]
.iter()
.filter(|s| s.name == scope.name)
.count();
Some((scope.name.clone(), nth))
}
pub fn scope_open(&self, index: usize) -> bool {
match self.scopes.get(index) {
Some(scope) if scope.expensive => self
.scope_key(index)
.is_some_and(|k| self.open_expensive_scopes.contains(&k)),
Some(_) => true,
None => false,
}
}
pub fn toggle_expensive_scope(&mut self, index: usize) {
let Some(key) = self.scope_key(index) else {
return;
};
if !self.open_expensive_scopes.remove(&key) {
self.open_expensive_scopes.insert(key);
let r = self.scopes[index].variables_ref;
self.expand_variable(r);
}
}
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("threads") => {
self.threads = parse_threads(&msg);
out.push(DapEvent::InspectionUpdated);
}
Some("exceptionInfo") => {
let req_seq = msg.get("request_seq").and_then(Value::as_i64);
if req_seq.is_some() && req_seq == self.exception_info_seq {
self.exception_info_seq = None;
if let Some(summary) = exception_summary(&msg) {
out.push(DapEvent::ExceptionInfo { summary });
}
}
}
Some("scopes") => {
self.scopes = parse_scopes(&msg);
let refs: Vec<i64> = (0..self.scopes.len())
.filter(|&i| self.scope_open(i))
.map(|i| self.scopes[i].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("initialize") => {
if let Some(body) = msg.get("body") {
self.capabilities = body.clone();
if let Some(offered) = offered_exception_filters(body) {
let mut keep: Vec<String> = self
.exception_filters
.iter()
.filter(|f| offered.iter().any(|(id, _)| id == *f))
.cloned()
.collect();
for (id, default) in &offered {
if *default && !keep.contains(id) {
keep.push(id.clone());
}
}
if self.pending_raised == Some(true) {
for id in raised_filter_ids(&offered).unwrap_or_default() {
if !keep.contains(&id) {
keep.push(id);
}
}
}
self.exception_filters = keep;
}
self.pending_raised = None;
}
}
Some("launch" | "attach")
if msg.get("success").and_then(Value::as_bool) == Some(false) =>
{
let reason = launch_failure_reason(&msg);
out.push(DapEvent::Output {
category: String::from("stderr"),
text: format!("{reason}\n"),
});
self.launch_error = Some(reason);
self.phase = SessionPhase::Terminated;
self.current_location = None;
out.push(DapEvent::Terminated);
}
Some("dataBreakpointInfo") => {
let req_seq = msg.get("request_seq").and_then(Value::as_i64);
if let Some(label) = req_seq.and_then(|s| self.pending_data_info.remove(&s)) {
let body = msg.get("body");
match body.and_then(|b| b.get("dataId")).and_then(Value::as_str) {
Some(id) => {
self.data_breakpoints.push((id.to_string(), label));
self.push_data_breakpoints();
}
None => {
let why = body
.and_then(|b| b.get("description"))
.and_then(Value::as_str)
.unwrap_or("the adapter cannot watch it")
.to_string();
out.push(DapEvent::Output {
category: String::from("console"),
text: format!("Cannot break when {label} changes: {why}\n"),
});
}
}
}
}
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 update_breakpoint_lines(&mut self.unverified_breakpoints, &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, reason } => {
if let Some((path, _)) = self.run_to.take() {
let own = self.breakpoints.get(&path).cloned().unwrap_or_default();
let _ = self.active().send(set_breakpoints_request(&path, &own));
}
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));
let _ = self.active().send(threads_request());
self.exception_info_seq = None;
if reason == "exception" && self.supports("supportsExceptionInfoRequest") {
self.exception_info_seq = self
.active()
.send(thread_request("exceptionInfo", *thread_id))
.ok();
}
}
DapEvent::Continued => {
self.phase = SessionPhase::Running;
self.current_location = None;
self.exception_info_seq = None;
self.clear_inspection();
}
DapEvent::Terminated => {
if from_child || self.child.is_none() {
self.phase = SessionPhase::Terminated;
self.current_location = None;
self.exception_info_seq = None;
self.clear_inspection();
}
}
DapEvent::Output { .. } => {}
DapEvent::BreakpointsUpdated
| DapEvent::InspectionUpdated
| DapEvent::Evaluated { .. }
| DapEvent::ExceptionInfo { .. } => {}
}
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));
}
if !self.function_breakpoints.is_empty() {
let _ = t.send(set_function_breakpoints_request(&self.function_breakpoints));
}
}
pub fn supports(&self, name: &str) -> bool {
match &self.capabilities {
Value::Null => true,
caps => caps.get(name).and_then(Value::as_bool).unwrap_or(false),
}
}
pub fn set_function_breakpoints(&mut self, names: Vec<String>) {
self.function_breakpoints = names;
if !matches!(self.phase, SessionPhase::Initializing) {
let _ = self
.active()
.send(set_function_breakpoints_request(&self.function_breakpoints));
}
}
pub fn run_to_cursor(&mut self, path: &Path, line: u32) {
if let Some((old, _)) = self.run_to.take()
&& old != path
{
let own = self.breakpoints.get(&old).cloned().unwrap_or_default();
let _ = self.active().send(set_breakpoints_request(&old, &own));
}
self.run_to = Some((path.to_path_buf(), line));
let own = self.breakpoints.get(path).cloned().unwrap_or_default();
let set = self.with_run_to(path, &own);
let _ = self.active().send(set_breakpoints_request(path, &set));
self.continue_execution();
}
fn with_run_to(&self, path: &Path, own: &[SourceBreakpoint]) -> Vec<SourceBreakpoint> {
with_run_to(self.run_to.as_ref(), path, own)
}
pub fn break_on_change(&mut self, variables_reference: i64, name: &str) {
if let Ok(seq) = self
.active()
.send(data_breakpoint_info_request(variables_reference, name))
{
self.pending_data_info.insert(seq, name.to_string());
}
}
pub fn clear_data_breakpoints(&mut self) {
self.data_breakpoints.clear();
self.push_data_breakpoints();
}
fn push_data_breakpoints(&mut self) {
let ids: Vec<String> = self
.data_breakpoints
.iter()
.map(|(id, _)| id.clone())
.collect();
let _ = self.active().send(set_data_breakpoints_request(&ids));
}
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;
self.exception_info_seq = None;
}
}
pub fn update_breakpoints(&mut self, path: &Path, breakpoints: &[SourceBreakpoint]) {
self.breakpoints
.insert(path.to_path_buf(), breakpoints.to_vec());
let set = self.with_run_to(path, breakpoints);
let _ = self.active().send(set_breakpoints_request(path, &set));
}
pub fn step(&mut self, command: &str) {
if let Some(tid) = self.stopped_thread {
let _ = self.active().send(thread_request(command, tid));
self.exception_info_seq = None;
}
}
pub fn disconnect(&mut self) {
let req = disconnect_request(self.attached);
if let Some(child) = self.child.as_ref() {
let _ = child.send(req.clone());
}
let _ = self.transport.send(req);
self.phase = SessionPhase::Terminated;
self.exception_info_seq = None;
}
}
fn is_attach(request: &Value) -> bool {
request["command"] == "attach"
}
pub fn delve_builds(request: &Value) -> bool {
let args = &request["arguments"];
request["command"] == "launch"
&& args.get("output").is_none()
&& matches!(
args["mode"].as_str(),
None | Some("debug" | "test" | "auto")
)
}
pub fn with_build_output(mut request: Value, dir: &Path) -> Value {
let bin = dir.join(format!("__debug_bin{}", std::env::consts::EXE_SUFFIX));
if let Some(args) = request.get_mut("arguments").and_then(Value::as_object_mut) {
args.insert("output".into(), json!(bin.to_string_lossy()));
}
request
}
#[derive(Debug)]
pub struct DebugBuildDir(PathBuf);
impl DebugBuildDir {
pub fn create() -> std::io::Result<Self> {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos());
let dir = std::env::temp_dir().join(format!(
"croft-dlv-{}-{}-{nanos}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder.create(&dir)?;
Ok(Self(dir))
}
pub fn path(&self) -> &Path {
&self.0
}
}
impl Drop for DebugBuildDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn disconnect_request(attached: bool) -> Value {
json!({
"type": "request",
"command": "disconnect",
"arguments": { "terminateDebuggee": !attached }
})
}
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 session_set_tests {
use super::DebugSessions;
#[test]
fn a_replace_clears_the_set_while_a_push_joins_it() {
let mut set: DebugSessions<&str> = DebugSessions::default();
assert!(set.is_empty(), "nothing is being debugged to start with");
set.replace_with("server", "s1");
set.push("client", "c1");
assert_eq!(set.len(), 2, "the member joined rather than replacing");
assert_eq!(set.names(), vec!["server", "client"], "in launch order");
set.replace_with("alone", "a1");
assert_eq!(set.names(), vec!["alone"]);
}
#[test]
fn focus_always_names_a_session_that_exists() {
let mut set: DebugSessions<&str> = DebugSessions::default();
assert_eq!(set.focused(), None, "an empty set focuses nothing");
assert_eq!(set.focused_name(), None);
set.replace_with("first", "f");
set.push("second", "s");
assert_eq!(
set.focused_name(),
Some("second"),
"a push focuses what it just started"
);
assert!(set.focus(0), "an existing index is focusable");
assert_eq!(set.focused(), Some(&"f"));
assert!(
!set.focus(9),
"a missing one is refused rather than dangling"
);
assert_eq!(
set.focused_name(),
Some("first"),
"and the refusal leaves the previous focus untouched"
);
set.clear();
assert!(set.is_empty() && set.focused().is_none());
set.replace_with("fresh", "x");
assert_eq!(set.focused_name(), Some("fresh"));
}
#[test]
fn removing_one_session_leaves_the_others_and_keeps_the_focus_valid() {
let mut set: DebugSessions<&str> = DebugSessions::default();
set.replace_with("server", "s");
set.push("client", "c");
set.push("worker", "w");
set.focus(2);
assert_eq!(set.remove(2).map(|s| s.name), Some(String::from("worker")));
assert_eq!(set.names(), vec!["server", "client"]);
assert_eq!(set.focused_name(), Some("client"));
set.focus(1);
assert_eq!(set.remove(0).map(|s| s.name), Some(String::from("server")));
assert_eq!(set.focused_name(), Some("client"), "still the same session");
assert!(set.remove(5).is_none(), "a missing index removes nothing");
let mut three: DebugSessions<&str> = DebugSessions::default();
three.replace_with("a", "1");
three.push("b", "2");
three.push("c", "3");
three.focus(1);
assert_eq!(three.remove(1).map(|s| s.name), Some(String::from("b")));
assert_eq!(three.names(), vec!["a", "c"]);
assert_eq!(
three.focused_name(),
Some("c"),
"the next live session, not the first"
);
assert_eq!(set.len(), 1);
set.remove(0);
assert!(set.is_empty() && set.focused().is_none());
}
#[test]
fn every_session_is_reachable_with_its_index() {
let mut set: DebugSessions<u32> = DebugSessions::default();
set.replace_with("a", 10);
set.push("b", 20);
set.push("c", 30);
let seen: Vec<(usize, u32)> = set
.iter_named_mut_indexed()
.map(|(i, s)| (i, s.session))
.collect();
assert_eq!(
seen,
vec![(0, 10), (1, 20), (2, 30)],
"all three with their positions - a poll that visited only the \
focused one would leave the rest at the gate, started and dead"
);
}
#[test]
fn every_session_is_reachable_for_a_stop() {
let mut set: DebugSessions<u32> = DebugSessions::default();
set.replace_with("a", 1);
set.push("b", 2);
set.push("c", 3);
set.focus(1);
let seen: Vec<u32> = set.iter_mut().map(|s| *s).collect();
assert_eq!(
seen,
vec![1, 2, 3],
"all three, not just the focused one - a stop that misses a \
session orphans a live process"
);
}
}
fn with_run_to(
run_to: Option<&(PathBuf, u32)>,
path: &Path,
own: &[SourceBreakpoint],
) -> Vec<SourceBreakpoint> {
let mut set = own.to_vec();
if let Some((target, line)) = run_to
&& target == path
{
set.retain(|b| b.line != *line);
set.push(SourceBreakpoint::plain(*line));
}
set
}
#[cfg(test)]
pub(crate) mod tests {
#[cfg(unix)]
#[test]
fn a_refused_launch_ends_the_session_with_the_adapters_reason() {
let tmp = tempfile::tempdir().unwrap();
let adapter = tmp.path().join("adapter.py");
std::fs::write(
&adapter,
r#"import sys, json
def read():
n = 0
while True:
line = sys.stdin.buffer.readline()
if not line:
sys.exit(0)
if line.strip() == b"":
break
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1])
return json.loads(sys.stdin.buffer.read(n))
def send(m):
b = json.dumps(m).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(b) + b)
sys.stdout.buffer.flush()
seq = 0
while True:
req = read()
seq += 1
if req["command"] == "initialize":
send({"seq": seq, "type": "response", "request_seq": req["seq"], "success": True, "command": "initialize", "body": {}})
elif req["command"] == "launch":
send({"seq": seq, "type": "response", "request_seq": req["seq"], "success": False, "command": "launch",
"message": "Failed to launch /w",
"body": {"error": {"id": 3000, "showUser": True,
"format": "Failed to launch /w: Go version go1.24.7 is too old for this version of Delve (minimum supported version 1.25, suppress this error with --check-go-version=false)"}}})
else:
send({"seq": seq, "type": "response", "request_seq": req["seq"], "success": True, "command": req["command"]})
"#,
)
.unwrap();
let launch =
json!({"type": "request", "command": "launch", "arguments": {"request": "launch"}});
let mut session = DapSession::launch_with(
"python3",
&[adapter.to_string_lossy().into_owned()],
tmp.path(),
launch,
BTreeMap::new(),
)
.unwrap();
let mut events = Vec::new();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the adapter's launch response",
|| {
events.extend(session.poll());
session.phase == SessionPhase::Terminated
},
);
let reason = session.launch_error.clone().expect("the reason is kept");
assert!(reason.contains("go1.24.7 is too old"), "{reason}");
assert!(events.iter().any(|e| matches!(e, DapEvent::Terminated)));
assert!(
events
.iter()
.any(|e| matches!(e, DapEvent::Output { category, text }
if category == "stderr" && text.contains("minimum supported version 1.25"))),
"{events:?}"
);
let bare = json!({"type": "response", "command": "attach", "success": false, "message": "no such process"});
assert_eq!(launch_failure_reason(&bare), "no such process");
}
#[test]
fn delve_zero_config_runs_the_package_or_its_tests() {
let main = delve_zero_config_request(Path::new("/w/cmd/app/main.go"));
assert_eq!(main["arguments"]["mode"], "debug");
assert_eq!(main["arguments"]["program"], "/w/cmd/app");
let test = delve_zero_config_request(Path::new("/w/pkg/util_test.go"));
assert_eq!(test["arguments"]["mode"], "test");
assert_eq!(test["arguments"]["program"], "/w/pkg");
}
#[test]
fn delve_launches_forward_the_program_output() {
let zero = with_remote_output(delve_zero_config_request(Path::new("/w/main.go")));
assert_eq!(zero["arguments"]["outputMode"], "remote");
let test = with_remote_output(delve_test_request(Path::new("/w"), &[]));
assert_eq!(test["arguments"]["outputMode"], "remote");
}
#[test]
fn an_explicit_output_mode_or_an_attach_is_left_alone() {
let local = json!({"command": "launch", "arguments": {"outputMode": "local"}});
assert_eq!(
with_remote_output(local)["arguments"]["outputMode"],
"local"
);
let attach = json!({"command": "attach", "arguments": {"processId": 7}});
assert!(
with_remote_output(attach)["arguments"]
.get("outputMode")
.is_none()
);
}
#[test]
#[ignore]
fn delve_shows_the_program_output() {
let dlv = std::env::var_os("CROFT_TEST_DLV")
.map(PathBuf::from)
.or_else(|| crate::dap::install::dlv_program().ok())
.expect("dlv");
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("go.mod"), "module t\n\ngo 1.21\n").unwrap();
let main = tmp.path().join("main.go");
std::fs::write(
&main,
"package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(\"starting up\")\n\tfmt.Fprintln(os.Stderr, \"warning: done\")\n}\n",
)
.unwrap();
let main = main.canonicalize().unwrap();
let mut s = DapSession::launch_delve(
&dlv,
main.parent().unwrap(),
delve_zero_config_request(&main),
BTreeMap::new(),
)
.expect("delve starts");
let mut output = String::new();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(90);
while s.phase != SessionPhase::Terminated && std::time::Instant::now() < deadline {
for ev in s.poll() {
if let DapEvent::Output { text, .. } = ev {
output.push_str(&text);
}
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(output.contains("starting up"), "stdout missing: {output:?}");
assert!(
output.contains("warning: done"),
"stderr missing: {output:?}"
);
}
#[test]
#[ignore]
fn delve_stops_at_a_breakpoint_in_a_real_go_program() {
let dlv = std::env::var_os("CROFT_TEST_DLV")
.map(PathBuf::from)
.or_else(|| crate::dap::install::dlv_program().ok())
.expect("dlv");
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("go.mod"), "module t\n\ngo 1.21\n").unwrap();
let main = tmp.path().join("main.go");
std::fs::write(
&main,
"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tx := 41\n\tx++\n\tfmt.Println(x)\n}\n",
)
.unwrap();
let main = main.canonicalize().unwrap();
let mut bps = BTreeMap::new();
bps.insert(main.clone(), vec![SourceBreakpoint::plain(7)]);
let mut s = DapSession::launch_delve(
&dlv,
main.parent().unwrap(),
delve_zero_config_request(&main),
bps,
)
.expect("delve starts");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(90);
while s.phase != SessionPhase::Stopped && std::time::Instant::now() < deadline {
s.poll();
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert_eq!(s.phase, SessionPhase::Stopped, "delve never stopped");
while s.current_location.is_none() && std::time::Instant::now() < deadline {
s.poll();
std::thread::sleep(std::time::Duration::from_millis(50));
}
let (file, line) = s.current_location.clone().expect("a stop location");
assert_eq!(line, 7);
assert_eq!(file.canonicalize().unwrap(), main);
s.disconnect();
}
#[test]
#[ignore]
fn delve_either_stops_or_says_why_it_cannot_start() {
let dlv = std::env::var_os("CROFT_TEST_DLV")
.map(PathBuf::from)
.or_else(|| crate::dap::install::dlv_program().ok())
.expect("dlv");
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("go.mod"), "module t\n\ngo 1.21\n").unwrap();
let main = tmp.path().join("main.go");
std::fs::write(
&main,
"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tx := 41\n\tx++\n\tfmt.Println(x)\n}\n",
)
.unwrap();
let main = main.canonicalize().unwrap();
let mut bps = BTreeMap::new();
bps.insert(main.clone(), vec![SourceBreakpoint::plain(7)]);
let mut s = DapSession::launch_delve(
&dlv,
main.parent().unwrap(),
delve_zero_config_request(&main),
bps,
)
.expect("delve starts");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(90);
while !matches!(s.phase, SessionPhase::Stopped | SessionPhase::Terminated)
&& std::time::Instant::now() < deadline
{
s.poll();
std::thread::sleep(std::time::Duration::from_millis(50));
}
match s.phase {
SessionPhase::Stopped => {}
SessionPhase::Terminated => {
let why = s.launch_error.clone().expect("a refused launch says why");
assert!(why.contains("too old"), "{why}");
eprintln!("delve refused, as expected for this Go: {why}");
}
other => panic!("still {other:?} after 90 s"),
}
s.disconnect();
}
#[test]
#[ignore]
fn delve_test_mode_runs_only_the_chosen_test() {
let dlv = std::env::var_os("CROFT_TEST_DLV")
.map(PathBuf::from)
.or_else(|| crate::dap::install::dlv_program().ok())
.expect("dlv");
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("go.mod"), "module t\n\ngo 1.21\n").unwrap();
let file = tmp.path().join("a_test.go");
std::fs::write(
&file,
"package t\n\nimport \"testing\"\n\n\
func TestA(t *testing.T) {\n\tt.Log(\"a\")\n}\n\n\
func TestB(t *testing.T) {\n\tt.Log(\"b\")\n}\n",
)
.unwrap();
let file = file.canonicalize().unwrap();
let dir = file.parent().unwrap().to_path_buf();
let mut bps = BTreeMap::new();
bps.insert(
file.clone(),
vec![SourceBreakpoint::plain(6), SourceBreakpoint::plain(10)],
);
let request =
delve_test_request(&dir, &crate::testing::gotest::test_binary_args(".::TestB"));
let mut s = DapSession::launch_delve(&dlv, &dir, request, bps).expect("delve starts");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
while s.current_location.is_none() && std::time::Instant::now() < deadline {
s.poll();
std::thread::sleep(std::time::Duration::from_millis(50));
}
let (at, line) = s.current_location.clone().expect("a stop location");
assert_eq!(line, 10, "stopped in TestB, not TestA");
assert_eq!(at.canonicalize().unwrap(), file);
s.disconnect();
}
fn go_program(src: &str) -> (tempfile::TempDir, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("go.mod"), "module t\n\ngo 1.21\n").unwrap();
let main = tmp.path().join("main.go");
std::fs::write(&main, src).unwrap();
let main = main.canonicalize().unwrap();
(tmp, main)
}
fn test_dlv() -> PathBuf {
std::env::var_os("CROFT_TEST_DLV")
.map(PathBuf::from)
.or_else(|| crate::dap::install::dlv_program().ok())
.expect("dlv")
}
fn poll_delve_until(
s: &mut DapSession,
output: &mut Vec<String>,
done: impl Fn(&DapSession) -> bool,
) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(90);
while !done(s) && std::time::Instant::now() < deadline {
for ev in s.poll() {
if let DapEvent::Output { text, .. } = ev {
output.push(text);
}
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
}
#[test]
#[ignore]
fn delve_honours_conditions_and_logpoints() {
let (_tmp, main) = go_program(
"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ttotal := 0\n\
\tfor i := 0; i < 10; i++ {\n\t\ttotal += i\n\t\tfmt.Println(total)\n\t}\n}\n",
);
let mut bps = BTreeMap::new();
bps.insert(
main.clone(),
vec![
SourceBreakpoint {
line: 8,
condition: None,
log_message: Some(String::from("tick {i}")),
hit_condition: None,
},
SourceBreakpoint {
line: 9,
condition: Some(String::from("i == 6")),
log_message: None,
hit_condition: None,
},
],
);
let mut s = DapSession::launch_delve(
&test_dlv(),
main.parent().unwrap(),
delve_zero_config_request(&main),
bps,
)
.expect("delve starts");
let mut output = Vec::new();
poll_delve_until(&mut s, &mut output, |s| s.lookup_local("i").is_some());
let (_, line) = s.current_location.clone().expect("a stop location");
assert_eq!(line, 9, "stopped on the conditional line, not the logpoint");
assert_eq!(
s.lookup_local("i").map(|v| v.value.clone()).as_deref(),
Some("6"),
"the condition held at the stop"
);
let text = output.concat();
for i in 0..=6 {
assert!(
text.contains(&format!("tick {i}")),
"logpoint {i}: {text:?}"
);
}
assert!(
!text.contains("tick 7"),
"nothing ran past the stop: {text:?}"
);
s.disconnect();
}
#[test]
#[ignore]
fn delve_lists_goroutines_and_shows_one_s_stack() {
let (_tmp, main) = go_program(
"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\
func worker(c chan int) {\n\tv := <-c\n\tfmt.Println(v)\n}\n\n\
func main() {\n\tc := make(chan int)\n\tgo worker(c)\n\
\ttime.Sleep(200 * time.Millisecond)\n\tc <- 1\n\
\ttime.Sleep(100 * time.Millisecond)\n}\n",
);
let mut bps = BTreeMap::new();
bps.insert(main.clone(), vec![SourceBreakpoint::plain(17)]);
let mut s = DapSession::launch_delve(
&test_dlv(),
main.parent().unwrap(),
delve_zero_config_request(&main),
bps,
)
.expect("delve starts");
let mut output = Vec::new();
poll_delve_until(&mut s, &mut output, |s| {
s.current_location.is_some() && s.threads.len() > 1
});
let (_, line) = s.current_location.clone().expect("a stop location");
assert_eq!(line, 17);
let worker = s
.threads
.iter()
.find(|(_, name)| name.contains("main.worker"))
.map(|(id, _)| *id)
.unwrap_or_else(|| panic!("the worker goroutine is listed: {:?}", s.threads));
assert!(
s.threads.iter().any(|(_, name)| name.contains("main.main")),
"{:?}",
s.threads
);
s.select_thread(worker);
poll_delve_until(&mut s, &mut output, |s| {
s.stack_frames
.iter()
.any(|f| f.name.contains("main.worker"))
});
let frame = s
.stack_frames
.iter()
.find(|f| f.name.contains("main.worker"))
.unwrap_or_else(|| panic!("the worker's own stack: {:?}", s.stack_frames));
assert_eq!(frame.line, 9, "parked on its channel receive");
assert!(
s.stack_frames.iter().all(|f| f.name != "main.main"),
"the stack is the worker's, not main's: {:?}",
s.stack_frames
);
s.disconnect();
}
#[test]
#[ignore]
fn delve_expands_evaluates_and_steps() {
let (_tmp, main) = go_program(
"package main\n\nimport \"fmt\"\n\ntype point struct{ X, Y int }\n\n\
func double(n int) int {\n\treturn n * 2\n}\n\n\
func main() {\n\txs := []int{1, 2, 3}\n\tm := map[string]int{\"a\": 1}\n\
\tp := point{X: 4, Y: 5}\n\td := double(p.X)\n\tfmt.Println(xs, m, p, d)\n}\n",
);
let mut bps = BTreeMap::new();
bps.insert(main.clone(), vec![SourceBreakpoint::plain(15)]);
let mut s = DapSession::launch_delve(
&test_dlv(),
main.parent().unwrap(),
delve_zero_config_request(&main),
bps,
)
.expect("delve starts");
let mut out = Vec::new();
poll_delve_until(&mut s, &mut out, |s| s.lookup_local("p").is_some());
assert_eq!(s.current_location.clone().map(|l| l.1), Some(15));
let children = |s: &mut DapSession, out: &mut Vec<String>, name: &str| {
let r = s.lookup_local(name).expect(name).variables_ref;
assert!(r > 0, "{name} is expandable");
s.expand_variable(r);
poll_delve_until(s, out, |s| s.variables.contains_key(&r));
s.variables[&r]
.iter()
.map(|v| (v.name.clone(), v.value.clone()))
.collect::<Vec<_>>()
};
let xs = children(&mut s, &mut out, "xs");
assert_eq!(
xs.iter().map(|(_, v)| v.as_str()).collect::<Vec<_>>(),
["1", "2", "3"],
"{xs:?}"
);
let m = children(&mut s, &mut out, "m");
assert!(m.iter().any(|(k, v)| k.contains("a") && v == "1"), "{m:?}");
let p = children(&mut s, &mut out, "p");
assert!(p.contains(&("X".into(), "4".into())), "{p:?}");
assert!(p.contains(&("Y".into(), "5".into())), "{p:?}");
s.evaluate("p.X + len(xs)", "repl");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
let mut result = None;
while result.is_none() && std::time::Instant::now() < deadline {
for ev in s.poll() {
if let DapEvent::Evaluated {
result: r, success, ..
} = ev
{
result = Some((r, success));
}
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert_eq!(result, Some((String::from("7"), true)));
let step = |s: &mut DapSession, out: &mut Vec<String>, cmd: &str| {
s.step(cmd);
poll_delve_until(s, out, |s| {
s.phase == SessionPhase::Running || s.current_location.is_none()
});
poll_delve_until(s, out, |s| s.current_location.is_some());
s.current_location.clone().map(|l| l.1)
};
let into = step(&mut s, &mut out, "stepIn");
assert!(matches!(into, Some(7) | Some(8)), "into double: {into:?}");
poll_delve_until(&mut s, &mut out, |s| !s.stack_frames.is_empty());
assert_eq!(
s.stack_frames.first().map(|f| f.name.as_str()),
Some("main.double")
);
let back = step(&mut s, &mut out, "stepOut");
assert!(
matches!(back, Some(15) | Some(16)),
"back in main: {back:?}"
);
if back == Some(15) {
assert_eq!(step(&mut s, &mut out, "next"), Some(16));
}
poll_delve_until(&mut s, &mut out, |s| s.lookup_local("d").is_some());
assert_eq!(
s.lookup_local("d").map(|v| v.value.clone()).as_deref(),
Some("8")
);
s.disconnect();
}
#[test]
fn run_to_cursor_stops_even_on_a_logpoint_line() {
let src = PathBuf::from("/w/app.py");
let logpoint = SourceBreakpoint {
line: 9,
condition: None,
log_message: Some(String::from("x")),
hit_condition: None,
};
let target = (src.clone(), 9);
let set = with_run_to(Some(&target), &src, std::slice::from_ref(&logpoint));
assert_eq!(set, vec![SourceBreakpoint::plain(9)]);
assert_eq!(
with_run_to(
Some(&target),
Path::new("/w/other.py"),
std::slice::from_ref(&logpoint)
),
vec![logpoint]
);
}
use super::*;
#[test]
fn stopping_an_attached_session_leaves_its_process_running() {
let attach = json!({"type": "request", "command": "attach", "arguments": {"processId": 7}});
let launch = json!({"type": "request", "command": "launch", "arguments": {}});
assert!(is_attach(&attach));
assert!(!is_attach(&launch));
assert_eq!(
disconnect_request(is_attach(&attach))["arguments"]["terminateDebuggee"],
false
);
assert_eq!(
disconnect_request(is_attach(&launch))["arguments"]["terminateDebuggee"],
true
);
}
#[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,
expensive: false,
},
Scope {
name: String::from("Locals"),
variables_ref: 2,
expensive: false,
},
];
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,
expensive: false,
}];
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 exception_summary_names_the_type_and_message() {
let debugpy = json!({ "body": {
"exceptionId": "ModuleNotFoundError",
"description": "No module named 'requests'",
"breakMode": "unhandled",
"details": { "message": "No module named 'requests'", "stackTrace": "..." }
}});
assert_eq!(
exception_summary(&debugpy).as_deref(),
Some("ModuleNotFoundError: No module named 'requests'")
);
let noted = json!({ "body": {
"exceptionId": "ValueError (note: full exception trace is shown but \
execution is paused at: _run_module_as_main)",
"description": "boom 42"
}});
assert_eq!(
exception_summary(¬ed).as_deref(),
Some("ValueError: boom 42")
);
let js = json!({ "body": {
"exceptionId": "Error",
"description": "Error: boom\n at main (/w/app.js:3:9)"
}});
assert_eq!(exception_summary(&js).as_deref(), Some("Error: boom"));
let only_details = json!({ "body": {
"exceptionId": "panic",
"details": { "message": "index out of range" }
}});
assert_eq!(
exception_summary(&only_details).as_deref(),
Some("panic: index out of range")
);
let only_id = json!({ "body": { "exceptionId": "KeyError", "description": "" } });
assert_eq!(exception_summary(&only_id).as_deref(), Some("KeyError"));
assert_eq!(exception_summary(&json!({ "body": {} })), None);
assert_eq!(exception_summary(&json!({ "success": false })), 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 a_breakpoint_event_updates_only_its_own_line() {
let p = PathBuf::from("/a.py");
let report = |line, verified| BreakpointReport {
path: p.clone(),
line,
verified,
};
let mut map = BTreeMap::new();
fold_breakpoint_reports(&mut map, &[report(3, false), report(7, false)]);
assert!(update_breakpoint_lines(&mut map, &[report(3, true)]));
assert_eq!(map[&p], [7].into_iter().collect());
assert!(update_breakpoint_lines(&mut map, &[report(9, false)]));
assert_eq!(map[&p], [7, 9].into_iter().collect());
assert!(!update_breakpoint_lines(&mut map, &[report(9, false)]));
update_breakpoint_lines(&mut map, &[report(7, true), report(9, true)]);
assert!(!map.contains_key(&p), "an empty set is dropped");
assert!(!update_breakpoint_lines(&mut map, &[report(1, true)]));
assert!(map.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,
hit_condition: 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");
}
const FAKE_DAP: &str = r#"
import json, sys
log = open(sys.argv[1], "a")
seq = [1000]
def read():
length = None
while True:
line = sys.stdin.buffer.readline()
if not line:
return None
line = line.strip()
if not line:
break
if line.lower().startswith(b"content-length:"):
length = int(line.split(b":")[1])
return json.loads(sys.stdin.buffer.read(length))
def send(msg):
seq[0] += 1
msg["seq"] = seq[0]
body = json.dumps(msg).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body) + body)
sys.stdout.buffer.flush()
def reply(req, body=None):
send({"type": "response", "request_seq": req["seq"], "success": True,
"command": req["command"], "body": body or {}})
def stopped():
send({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}})
while True:
req = read()
if req is None:
break
log.write(json.dumps({"command": req["command"], "arguments": req.get("arguments")}) + "\n")
log.flush()
c = req["command"]
if c == "initialize":
reply(req, {"supportsFunctionBreakpoints": True, "supportsDataBreakpoints": True,
"supportsHitConditionalBreakpoints": True})
send({"type": "event", "event": "initialized"})
elif c == "configurationDone":
reply(req)
stopped()
elif c == "continue":
reply(req)
stopped()
elif c == "dataBreakpointInfo":
reply(req, {"dataId": "var:" + req["arguments"]["name"], "description": "x"})
elif c == "disconnect":
reply(req)
break
else:
reply(req)
"#;
fn requests(log: &Path) -> Vec<Value> {
std::fs::read_to_string(log)
.unwrap_or_default()
.lines()
.filter_map(|l| serde_json::from_str(l).ok())
.collect()
}
fn poll_until(session: &mut DapSession, log: &Path, done: impl Fn(&[Value]) -> bool) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while std::time::Instant::now() < deadline {
session.poll();
if done(&requests(log)) {
return;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
panic!("timed out; requests so far: {:?}", requests(log));
}
fn exception_filter_session(filters: &str) -> Option<(DapSession, tempfile::TempDir, PathBuf)> {
std::process::Command::new("python3")
.arg("--version")
.output()
.ok()?;
let caps = if filters.is_empty() {
String::from("{}")
} else {
format!("{{\"exceptionBreakpointFilters\": {filters}}}")
};
let script = FAKE_DAP.replace(
r#"reply(req, {"supportsFunctionBreakpoints": True, "supportsDataBreakpoints": True,
"supportsHitConditionalBreakpoints": True})"#,
&format!("reply(req, {caps})"),
);
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("fake_dap.py");
std::fs::write(&path, script).unwrap();
let log = tmp.path().join("requests.jsonl");
let mut session = DapSession::launch_with(
"python3",
&[path.display().to_string(), log.display().to_string()],
tmp.path(),
json!({"type": "request", "command": "launch", "arguments": {}}),
BTreeMap::new(),
)
.expect("fake adapter spawns");
poll_until(&mut session, &log, |r| {
r.iter().any(|q| q["command"] == "configurationDone")
});
Some((session, tmp, log))
}
fn sent_exception_filters(log: &Path) -> Vec<Value> {
requests(log)
.into_iter()
.filter(|q| q["command"] == "setExceptionBreakpoints")
.map(|q| q["arguments"]["filters"].clone())
.collect()
}
#[test]
fn the_raised_exceptions_toggle_uses_js_debugs_all_filter() {
let Some((mut session, _tmp, log)) = exception_filter_session(
r#"[{"filter": "all", "label": "Caught Exceptions", "default": False},
{"filter": "uncaught", "label": "Uncaught Exceptions", "default": False}]"#,
) else {
return;
};
assert_eq!(
session.raised_exception_filters(),
Some(vec![String::from("all")])
);
assert_eq!(session.toggle_raised_exceptions(), Some(true));
poll_until(&mut session, &log, |_| {
sent_exception_filters(&log).len() >= 2
});
assert_eq!(session.toggle_raised_exceptions(), Some(false));
poll_until(&mut session, &log, |_| {
sent_exception_filters(&log).len() >= 3
});
assert_eq!(
sent_exception_filters(&log),
vec![
json!(["uncaught"]),
json!(["uncaught", "all"]),
json!(["uncaught"])
]
);
}
#[test]
fn lldb_dap_gets_its_own_filters_and_cpp_throw_for_raised() {
let Some((mut session, _tmp, log)) = exception_filter_session(
r#"[{"filter": "cpp_catch", "label": "C++ Catch", "default": False},
{"filter": "cpp_throw", "label": "C++ Throw", "default": False},
{"filter": "rust_panic", "label": "Rust Panic", "default": True}]"#,
) else {
return;
};
assert_eq!(
session.raised_exception_filters(),
Some(vec![String::from("cpp_throw")])
);
assert_eq!(session.toggle_raised_exceptions(), Some(true));
poll_until(&mut session, &log, |_| {
sent_exception_filters(&log).len() >= 2
});
assert_eq!(
sent_exception_filters(&log),
vec![json!(["rust_panic"]), json!(["rust_panic", "cpp_throw"])]
);
}
#[test]
fn lldb_dap_raised_toggle_covers_objective_c_throws() {
let Some((mut session, _tmp, log)) = exception_filter_session(
r#"[{"filter": "cpp_catch", "label": "C++ Catch", "default": False},
{"filter": "cpp_throw", "label": "C++ Throw", "default": False},
{"filter": "objc_catch", "label": "Objective-C Catch", "default": False},
{"filter": "objc_throw", "label": "Objective-C Throw", "default": False}]"#,
) else {
return;
};
assert_eq!(session.toggle_raised_exceptions(), Some(true));
poll_until(&mut session, &log, |_| {
sent_exception_filters(&log).len() >= 2
});
assert_eq!(session.toggle_raised_exceptions(), Some(false));
poll_until(&mut session, &log, |_| {
sent_exception_filters(&log).len() >= 3
});
assert_eq!(
sent_exception_filters(&log),
vec![json!([]), json!(["cpp_throw", "objc_throw"]), json!([])]
);
}
#[test]
fn an_adapter_without_exception_filters_has_nothing_to_toggle() {
let Some((mut session, _tmp, log)) = exception_filter_session("") else {
return;
};
assert_eq!(session.raised_exception_filters(), None);
assert_eq!(session.toggle_raised_exceptions(), None);
session.poll();
std::thread::sleep(std::time::Duration::from_millis(200));
session.poll();
assert_eq!(sent_exception_filters(&log), vec![json!(["uncaught"])]);
let Some((session, _tmp, _log)) = exception_filter_session(
r#"[{"filter": "raised", "label": "Raised Exceptions", "default": False},
{"filter": "uncaught", "label": "Uncaught Exceptions", "default": True},
{"filter": "userUnhandled", "label": "User Uncaught Exceptions", "default": False}]"#,
) else {
return;
};
assert_eq!(
session.raised_exception_filters(),
Some(vec![String::from("raised")])
);
assert_eq!(session.exception_filters, vec![String::from("uncaught")]);
}
#[test]
fn an_expensive_scope_is_fetched_only_once_opened() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let script = FAKE_DAP.replace(
" elif c == \"disconnect\":",
r#" elif c == "stackTrace":
reply(req, {"stackFrames": [{"id": 5, "name": "work", "line": 4,
"source": {"path": "/w/big.js"}}]})
elif c == "scopes":
reply(req, {"scopes": [
{"name": "Local: work", "variablesReference": 10, "expensive": False},
{"name": "Global", "variablesReference": 20, "expensive": True}]})
elif c == "variables":
ref = req["arguments"]["variablesReference"]
reply(req, {"variables": [{"name": "v%d" % ref, "value": "1", "variablesReference": 0}]})
elif c == "disconnect":"#,
);
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("fake_dap.py");
std::fs::write(&path, script).unwrap();
let log = tmp.path().join("requests.jsonl");
let mut session = DapSession::launch_with(
"python3",
&[path.display().to_string(), log.display().to_string()],
tmp.path(),
json!({"type": "request", "command": "launch", "arguments": {}}),
BTreeMap::new(),
)
.expect("fake adapter spawns");
let fetched = |log: &Path| -> Vec<i64> {
requests(log)
.iter()
.filter(|q| q["command"] == "variables")
.filter_map(|q| q["arguments"]["variablesReference"].as_i64())
.collect()
};
let scopes_asked = |log: &Path| {
requests(log)
.iter()
.filter(|q| q["command"] == "scopes")
.count()
};
poll_until(&mut session, &log, |_| fetched(&log).len() == 1);
for _ in 0..20 {
session.poll();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(fetched(&log), vec![10], "only the Local scope");
let global = session
.scopes
.iter()
.position(|s| s.name == "Global")
.unwrap();
assert!(session.scopes[global].expensive);
assert!(!session.scope_open(global));
session.toggle_expensive_scope(global);
poll_until(&mut session, &log, |_| fetched(&log) == vec![10, 20]);
assert!(session.scope_open(global));
session.continue_execution();
poll_until(&mut session, &log, |_| fetched(&log).len() == 4);
assert_eq!(fetched(&log), vec![10, 20, 10, 20]);
session.toggle_expensive_scope(global);
session.continue_execution();
poll_until(&mut session, &log, |_| {
scopes_asked(&log) == 3 && fetched(&log).len() == 5
});
for _ in 0..20 {
session.poll();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(fetched(&log), vec![10, 20, 10, 20, 10]);
}
#[test]
fn goroutines_list_and_select_and_an_attach_disconnects_softly() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let script = FAKE_DAP.replace(
" elif c == \"disconnect\":",
r#" elif c == "threads":
reply(req, {"threads": [{"id": 1, "name": "main"}, {"id": 7, "name": "worker"}]})
elif c == "stackTrace":
tid = req["arguments"]["threadId"]
name = "main.run" if tid == 1 else "main.work"
reply(req, {"stackFrames": [{"id": tid * 100, "name": name, "line": tid,
"source": {"path": "/w/main.go"}}]})
elif c == "disconnect":"#,
);
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("fake_dap.py");
std::fs::write(&path, script).unwrap();
let log = tmp.path().join("requests.jsonl");
let mut session = DapSession::launch_with(
"python3",
&[path.display().to_string(), log.display().to_string()],
tmp.path(),
json!({"type": "request", "command": "attach", "arguments": {"processId": 77}}),
BTreeMap::new(),
)
.expect("fake adapter spawns");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while (session.threads.len() < 2 || session.stack_frames.is_empty())
&& std::time::Instant::now() < deadline
{
session.poll();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(
session.threads,
vec![(1, String::from("main")), (7, String::from("worker"))]
);
assert_eq!(session.stack_frames[0].name, "main.run");
session.select_thread(7);
assert_eq!(session.stopped_thread, Some(7));
while session.stack_frames.is_empty() && std::time::Instant::now() < deadline {
session.poll();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(
session.stack_frames[0].name, "main.work",
"the goroutine's own stack"
);
session.disconnect();
poll_until(&mut session, &log, |r| {
r.iter().any(|q| q["command"] == "disconnect")
});
let disc = requests(&log)
.into_iter()
.find(|q| q["command"] == "disconnect")
.unwrap();
assert_eq!(
disc["arguments"]["terminateDebuggee"], false,
"croft did not start it"
);
}
#[test]
fn breakpoint_kinds_reach_the_adapter() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let tmp = tempfile::tempdir().unwrap();
let script = tmp.path().join("fake_dap.py");
std::fs::write(&script, FAKE_DAP).unwrap();
let log = tmp.path().join("requests.jsonl");
let src = tmp.path().join("app.py");
let mut bps = BTreeMap::new();
bps.insert(
src.clone(),
vec![SourceBreakpoint {
line: 3,
condition: None,
log_message: None,
hit_condition: Some(String::from("5")),
}],
);
let mut session = DapSession::launch_with(
"python3",
&[script.display().to_string(), log.display().to_string()],
tmp.path(),
json!({"type": "request", "command": "launch", "arguments": {}}),
bps,
)
.expect("fake adapter spawns");
session.set_function_breakpoints(vec![String::from("main")]);
poll_until(&mut session, &log, |r| {
r.iter().any(|q| q["command"] == "configurationDone")
});
let reqs = requests(&log);
let fbp = reqs
.iter()
.find(|q| q["command"] == "setFunctionBreakpoints")
.expect("sent");
assert_eq!(fbp["arguments"]["breakpoints"][0]["name"], "main");
let sbp = reqs
.iter()
.find(|q| q["command"] == "setBreakpoints")
.expect("sent");
assert_eq!(sbp["arguments"]["breakpoints"][0]["hitCondition"], "5");
assert!(session.supports("supportsDataBreakpoints"));
assert!(!session.supports("supportsStepBack"));
while session.stopped_thread.is_none() {
session.poll();
}
session.run_to_cursor(&src, 9);
poll_until(&mut session, &log, |r| {
r.iter()
.filter(|q| q["command"] == "setBreakpoints")
.count()
>= 3
});
let sets: Vec<Value> = requests(&log)
.into_iter()
.filter(|q| q["command"] == "setBreakpoints")
.collect();
let lines = |q: &Value| -> Vec<u64> {
q["arguments"]["breakpoints"]
.as_array()
.unwrap()
.iter()
.map(|b| b["line"].as_u64().unwrap())
.collect()
};
assert_eq!(
lines(&sets[1]),
vec![3, 9],
"the one-stop breakpoint is added"
);
assert_eq!(lines(&sets[2]), vec![3], "and withdrawn at the stop");
session.break_on_change(42, "total");
poll_until(&mut session, &log, |r| {
r.iter().any(|q| q["command"] == "setDataBreakpoints")
});
let dbp = requests(&log)
.into_iter()
.find(|q| q["command"] == "setDataBreakpoints")
.unwrap();
assert_eq!(dbp["arguments"]["breakpoints"][0]["dataId"], "var:total");
assert_eq!(
session.data_breakpoints,
vec![(String::from("var:total"), String::from("total"))]
);
session.disconnect();
}
#[test]
fn an_exception_stop_reports_what_was_thrown() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let script = FAKE_DAP
.replace(r#""reason": "breakpoint""#, r#""reason": "exception""#)
.replace(
r#""supportsHitConditionalBreakpoints": True"#,
r#""supportsHitConditionalBreakpoints": True, "supportsExceptionInfoRequest": True"#,
)
.replace(
" elif c == \"disconnect\":",
r#" elif c == "exceptionInfo":
reply(req, {"exceptionId": "ModuleNotFoundError",
"description": "No module named 'requests'", "breakMode": "unhandled"})
elif c == "disconnect":"#,
);
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("fake_dap.py");
std::fs::write(&path, script).unwrap();
let log = tmp.path().join("requests.jsonl");
let mut session = DapSession::launch_with(
"python3",
&[path.display().to_string(), log.display().to_string()],
tmp.path(),
json!({"type": "request", "command": "launch", "arguments": {}}),
BTreeMap::new(),
)
.expect("fake adapter spawns");
let mut summary = None;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the fake adapter to answer exceptionInfo",
|| {
for ev in session.poll() {
if let DapEvent::ExceptionInfo { summary: s } = ev {
summary = Some(s);
}
}
summary.is_some()
},
);
let asked = requests(&log)
.into_iter()
.find(|q| q["command"] == "exceptionInfo")
.expect("exceptionInfo was requested");
assert_eq!(asked["arguments"]["threadId"], 1);
assert_eq!(
summary.as_deref(),
Some("ModuleNotFoundError: No module named 'requests'")
);
session.disconnect();
}
fn one_stop_then_disconnect(
reason: &str,
supports_exception_info: bool,
) -> (Vec<Value>, Vec<String>) {
let mut script = FAKE_DAP
.replace(
r#""reason": "breakpoint""#,
&format!(r#""reason": "{reason}""#),
)
.replace(
" elif c == \"disconnect\":",
r#" elif c == "exceptionInfo":
reply(req, {"exceptionId": "KeyError", "description": "'x'"})
elif c == "disconnect":"#,
);
if supports_exception_info {
script = script.replace(
r#""supportsHitConditionalBreakpoints": True"#,
r#""supportsHitConditionalBreakpoints": True, "supportsExceptionInfoRequest": True"#,
);
}
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("fake_dap.py");
std::fs::write(&path, script).unwrap();
let log = tmp.path().join("requests.jsonl");
let mut session = DapSession::launch_with(
"python3",
&[path.display().to_string(), log.display().to_string()],
tmp.path(),
json!({"type": "request", "command": "launch", "arguments": {}}),
BTreeMap::new(),
)
.expect("fake adapter spawns");
let mut summaries = Vec::new();
let mut drain = |session: &mut DapSession| {
for ev in session.poll() {
if let DapEvent::ExceptionInfo { summary } = ev {
summaries.push(summary);
}
}
};
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the fake adapter to stop",
|| {
drain(&mut session);
requests(&log).iter().any(|q| q["command"] == "threads")
},
);
session.disconnect();
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the fake adapter to log the disconnect",
|| {
drain(&mut session);
requests(&log).iter().any(|q| q["command"] == "disconnect")
},
);
(requests(&log), summaries)
}
#[test]
fn a_breakpoint_stop_does_not_ask_what_was_thrown() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let (reqs, summaries) = one_stop_then_disconnect("breakpoint", true);
assert!(
!reqs.iter().any(|q| q["command"] == "exceptionInfo"),
"{reqs:?}"
);
assert!(summaries.is_empty(), "{summaries:?}");
}
#[test]
fn an_exception_stop_skips_exception_info_the_adapter_lacks() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let (reqs, summaries) = one_stop_then_disconnect("exception", false);
assert!(
reqs.iter().any(|q| q["command"] == "stackTrace"),
"the stop was handled: {reqs:?}"
);
assert!(
!reqs.iter().any(|q| q["command"] == "exceptionInfo"),
"{reqs:?}"
);
assert!(summaries.is_empty(), "{summaries:?}");
}
fn held_exception_info_session(arms: &str) -> (tempfile::TempDir, PathBuf, DapSession) {
let script = FAKE_DAP
.replace(r#""reason": "breakpoint""#, r#""reason": "exception""#)
.replace(
r#""supportsHitConditionalBreakpoints": True"#,
r#""supportsHitConditionalBreakpoints": True, "supportsExceptionInfoRequest": True"#,
)
.replace(
"def stopped():",
r#"held = []
def answer(req, name, text):
reply(req, {"exceptionId": name, "description": text})
def marker():
send({"type": "event", "event": "output", "body": {"category": "stdout", "output": "MARKER\n"}})
def stopped():"#,
)
.replace(" elif c == \"continue\":\n reply(req)\n stopped()\n", arms);
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("fake_dap.py");
std::fs::write(&path, script).unwrap();
let log = tmp.path().join("requests.jsonl");
let session = DapSession::launch_with(
"python3",
&[path.display().to_string(), log.display().to_string()],
tmp.path(),
json!({"type": "request", "command": "launch", "arguments": {}}),
BTreeMap::new(),
)
.expect("fake adapter spawns");
(tmp, log, session)
}
fn exception_info_after(
session: &mut DapSession,
log: &Path,
then: impl FnOnce(&mut DapSession),
) -> Vec<String> {
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"an exception stop that asks what was thrown",
|| {
session.poll();
session.stopped_thread.is_some()
&& requests(log)
.iter()
.any(|q| q["command"] == "exceptionInfo")
},
);
then(session);
let mut summaries = Vec::new();
let mut marked = false;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the fake adapter's marker",
|| {
for ev in session.poll() {
match ev {
DapEvent::ExceptionInfo { summary } => summaries.push(summary),
DapEvent::Output { text, .. } if text.contains("MARKER") => marked = true,
_ => {}
}
}
marked
},
);
summaries
}
#[test]
fn an_exception_reply_that_arrives_after_the_stop_ended_is_dropped() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let arms = r#" elif c == "exceptionInfo":
held.append(req)
elif c in ("continue", "next", "disconnect"):
reply(req)
for h in held:
answer(h, "KeyError", "'x'")
marker()
"#;
type Move = fn(&mut DapSession);
let moves: [(&str, Move); 3] = [
("continue", DapSession::continue_execution),
("step", |s| s.step("next")),
("disconnect", DapSession::disconnect),
];
let late: Vec<(&str, Vec<String>)> = moves
.into_iter()
.map(|(name, then)| {
let (_tmp, log, mut session) = held_exception_info_session(arms);
let late = exception_info_after(&mut session, &log, then);
session.disconnect();
(name, late)
})
.filter(|(_, late)| !late.is_empty())
.collect();
assert!(late.is_empty(), "reported after the stop ended: {late:?}");
}
#[test]
fn an_older_stops_exception_reply_does_not_overwrite_the_newer_ones() {
if std::process::Command::new("python3")
.arg("--version")
.output()
.is_err()
{
return;
}
let arms = r#" elif c == "exceptionInfo":
held.append(req)
if len(held) == 2:
answer(held[1], "ValueError", "new")
answer(held[0], "KeyError", "'old'")
marker()
elif c == "continue":
reply(req)
stopped()
"#;
let (_tmp, log, mut session) = held_exception_info_session(arms);
let seen = exception_info_after(&mut session, &log, DapSession::continue_execution);
session.disconnect();
assert_eq!(seen, vec![String::from("ValueError: new")]);
}
#[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}")),
hit_condition: None,
},
SourceBreakpoint {
line: 9,
condition: Some(String::from("n > 0")),
log_message: Some(String::from("n={n}")),
hit_condition: None,
},
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");
}
#[test]
fn python_launches_step_through_the_users_code_only() {
let f5 = launch_request(Path::new("/w/main.py"), Path::new("/v/bin/python"), false);
assert_eq!(f5["arguments"]["justMyCode"], true, "F5 on the active file");
let test = pytest_debug_launch_request(
Path::new("/proj/.venv/bin/python"),
Path::new("/proj"),
"test_addition",
);
assert_eq!(test["arguments"]["justMyCode"], true, "Debug Test");
}
#[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);
assert!(!scopes[0].expensive && !scopes[1].expensive);
let scopes = parse_scopes(&json!({
"body": { "scopes": [
{ "name": "Local: work", "variablesReference": 7, "expensive": false },
{ "name": "Global", "variablesReference": 8, "expensive": true }
]}
}));
assert_eq!(
scopes.iter().map(|s| s.expensive).collect::<Vec<_>>(),
vec![false, true]
);
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");
}
#[test]
fn a_delve_launch_builds_outside_the_workspace() {
let dir = Path::new("/tmp/croft-dlv-x");
for request in [
delve_zero_config_request(Path::new("/w/main.go")),
delve_zero_config_request(Path::new("/w/main_test.go")),
json!({"command": "launch", "arguments": {"program": "/w"}}),
] {
assert!(delve_builds(&request), "{request}");
let out = with_build_output(request, dir);
let bin = out["arguments"]["output"].as_str().unwrap();
assert!(bin.starts_with("/tmp/croft-dlv-x/__debug_bin"), "{bin}");
}
}
#[test]
fn an_explicit_output_or_a_launch_that_builds_nothing_is_left_alone() {
for request in [
json!({"command": "launch", "arguments": {"mode": "debug", "output": "./bin/app"}}),
json!({"command": "launch", "arguments": {"mode": "exec", "program": "/w/app"}}),
json!({"command": "launch", "arguments": {"mode": "core", "program": "/w/app"}}),
json!({"command": "attach", "arguments": {"processId": 7}}),
] {
assert!(!delve_builds(&request), "{request}");
}
}
#[test]
fn the_build_folder_is_removed_with_the_session() {
let a = DebugBuildDir::create().unwrap();
let b = DebugBuildDir::create().unwrap();
assert_ne!(a.path(), b.path());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(a.path()).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o700);
}
let bin = a.path().join("__debug_bin");
std::fs::write(&bin, "x").unwrap();
let path = a.path().to_path_buf();
drop(a);
assert!(!path.exists());
assert!(b.path().is_dir());
}
#[test]
#[ignore]
fn delve_leaves_no_debug_binary_in_the_package() {
let dlv = std::env::var_os("CROFT_TEST_DLV")
.map(PathBuf::from)
.or_else(|| crate::dap::install::dlv_program().ok())
.expect("dlv");
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("go.mod"), "module t\n\ngo 1.21\n").unwrap();
let main = tmp.path().join("main.go");
std::fs::write(
&main,
"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tx := 41\n\tx++\n\tfmt.Println(x)\n}\n",
)
.unwrap();
let main = main.canonicalize().unwrap();
let leftovers = || {
std::fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with("__debug_bin"))
.collect::<Vec<_>>()
};
for stop_at_breakpoint in [true, false] {
let mut bps = BTreeMap::new();
if stop_at_breakpoint {
bps.insert(main.clone(), vec![SourceBreakpoint::plain(7)]);
}
let mut s = DapSession::launch_delve(
&dlv,
main.parent().unwrap(),
delve_zero_config_request(&main),
bps,
)
.expect("delve starts");
let want = if stop_at_breakpoint {
SessionPhase::Stopped
} else {
SessionPhase::Terminated
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(90);
while s.phase != want && std::time::Instant::now() < deadline {
s.poll();
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert_eq!(s.phase, want);
s.disconnect();
drop(s);
std::thread::sleep(std::time::Duration::from_millis(300));
assert!(leftovers().is_empty(), "left behind: {:?}", leftovers());
}
}
pub(crate) fn headless_delve(n: usize) -> (u16, std::thread::JoinHandle<Vec<Value>>) {
use std::io::{BufRead, Read};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
stream
.set_read_timeout(Some(std::time::Duration::from_secs(10)))
.unwrap();
let mut reader = std::io::BufReader::new(stream);
let mut out = Vec::new();
while out.len() < n {
let mut len = 0;
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return out;
}
if let Some(v) = line.trim().strip_prefix("Content-Length:") {
len = v.trim().parse().unwrap();
}
if line.trim().is_empty() {
break;
}
}
let mut body = vec![0; len];
reader.read_exact(&mut body).unwrap();
out.push(serde_json::from_slice(&body).unwrap());
}
out
});
(port, handle)
}
#[test]
fn attach_delve_server_talks_to_the_headless_delve_directly() {
let (port, server) = headless_delve(2);
let attach = json!({"type": "request", "command": "attach",
"arguments": {"mode": "remote"}});
let session = DapSession::attach_delve_server("127.0.0.1", port, attach, BTreeMap::new())
.expect("connects");
let got = server.join().unwrap();
assert_eq!(got[0]["command"], "initialize");
assert_eq!(got[1]["command"], "attach");
assert_eq!(got[1]["arguments"]["mode"], "remote");
assert!(session.attached);
}
}