use crate::host::{self, with_host, Obj};
use serde_json::{json, Value as J};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
use std::os::fd::FromRawFd;
use std::sync::{Arc, Mutex};
enum Resume {
Continue,
Step,
Quit,
}
struct Dap {
reader: BufReader<std::io::Stdin>,
out: Arc<Mutex<File>>,
seq: i64,
breakpoints: HashMap<String, HashSet<u32>>,
func_breakpoints: HashSet<String>,
program: Option<String>,
config_done: bool,
started: bool,
step_mode: bool,
func_bp_armed: bool,
pause_request: bool,
cur_line: u32,
disconnected: bool,
capture: Capture,
}
thread_local! {
static DAP: std::cell::RefCell<Option<Dap>> = const { std::cell::RefCell::new(None) };
}
fn with_dap<R>(f: impl FnOnce(&mut Dap) -> R) -> Option<R> {
DAP.with(|d| d.borrow_mut().as_mut().map(f))
}
pub fn run_stdio() -> i32 {
let capture = match Capture::start() {
Ok(c) => c,
Err(e) => {
eprintln!("elisp --dap: {e}");
return 1;
}
};
let dap = Dap {
reader: BufReader::new(std::io::stdin()),
out: capture.out.clone(),
seq: 0,
breakpoints: HashMap::new(),
func_breakpoints: HashSet::new(),
program: None,
config_done: false,
started: false,
step_mode: false,
func_bp_armed: false,
pause_request: false,
cur_line: 0,
disconnected: false,
capture,
};
DAP.with(|d| *d.borrow_mut() = Some(dap));
while let Some(msg) = with_dap(|d| d.read_msg()).flatten() {
let run_now = with_dap(|d| d.handle_toplevel(&msg)).unwrap_or(false);
if with_dap(|d| d.disconnected).unwrap_or(true) {
break;
}
if run_now {
run_program();
with_dap(|d| d.capture.finish());
with_dap(|d| d.terminate());
break;
}
}
DAP.with(|d| *d.borrow_mut() = None);
0
}
fn run_program() {
let Some(path) = with_dap(|d| d.program.clone()).flatten() else {
with_dap(|d| {
d.event(
"output",
json!({"category": "stderr", "output": "no program specified\n"}),
)
});
return;
};
let src = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) => {
with_dap(|d| {
d.event(
"output",
json!({"category": "stderr", "output": format!("cannot read {path}: {e}\n")}),
)
});
return;
}
};
host::reset_host();
host::set_debug_mode(true);
let compiled = with_host(|h| {
let forms = crate::reader::read_all(h, &src)?;
crate::compiler::compile_program(h, &forms)
});
let result = match compiled {
Ok(chunk) => host::run_chunk(chunk),
Err(e) => Err(e),
};
host::set_debug_mode(false);
if let Err(e) = result {
with_dap(|d| {
d.event(
"output",
json!({"category": "stderr", "output": format!("error: {e}\n")}),
)
});
}
}
pub fn check_line(line: u32) {
with_dap(|d| d.on_line(line));
}
pub fn enter_function(callee: &fusevm::Value) {
with_dap(|d| {
if d.should_stop_at_sub(callee) {
d.set_step_mode(true);
d.func_bp_armed = true;
}
});
}
impl Dap {
fn next_seq(&mut self) -> i64 {
self.seq += 1;
self.seq
}
fn write(&mut self, msg: &J) {
let s = msg.to_string();
if let Ok(mut f) = self.out.lock() {
let _ = write!(f, "Content-Length: {}\r\n\r\n{}", s.len(), s);
let _ = f.flush();
}
}
fn event(&mut self, event: &str, body: J) {
let seq = self.next_seq();
self.write(&json!({"seq": seq, "type": "event", "event": event, "body": body}));
}
fn respond(&mut self, req: &J, body: J) {
let seq = self.next_seq();
self.write(&json!({
"seq": seq, "type": "response",
"request_seq": req["seq"], "success": true,
"command": req["command"], "body": body,
}));
}
fn maybe_start(&mut self) -> bool {
if self.program.is_some() && self.config_done && !self.started {
self.started = true;
true
} else {
false
}
}
fn canon(p: &str) -> String {
std::fs::canonicalize(p)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| p.to_string())
}
fn set_breakpoints(&mut self, msg: &J) {
let path = Self::canon(msg["arguments"]["source"]["path"].as_str().unwrap_or(""));
let mut lines = HashSet::new();
let mut verified = Vec::new();
if let Some(arr) = msg["arguments"]["breakpoints"].as_array() {
for bp in arr {
if let Some(l) = bp["line"].as_u64() {
lines.insert(l as u32);
verified.push(json!({"verified": true, "line": l}));
}
}
}
if !path.is_empty() {
self.breakpoints.insert(path, lines);
}
self.respond(msg, json!({"breakpoints": verified}));
}
fn set_function_breakpoints(&mut self, msg: &J) {
let names: Vec<String> = msg["arguments"]["breakpoints"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|b| b["name"].as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let body: Vec<J> = names.iter().map(|_| json!({"verified": true})).collect();
self.func_breakpoints = names.into_iter().collect();
self.respond(msg, json!({"breakpoints": body}));
}
fn set_step_mode(&mut self, on: bool) {
self.step_mode = on;
}
fn should_stop_at_sub(&self, callee: &fusevm::Value) -> bool {
if self.func_breakpoints.is_empty() {
return false;
}
with_host(|h| {
if let Some(name) = h.sym_name(callee) {
return self.func_breakpoints.contains(&name);
}
let fusevm::Value::Obj(id) = callee else {
return false;
};
self.func_breakpoints.iter().any(|n| {
h.find_symbol(n)
.map(|sym| h.function_designator(&sym))
.is_some_and(|f| matches!(f, fusevm::Value::Obj(x) if x == *id))
})
})
}
fn handle_toplevel(&mut self, msg: &J) -> bool {
if msg["type"] != "request" {
return false;
}
match msg["command"].as_str().unwrap_or("") {
"initialize" => {
self.respond(
msg,
json!({
"supportsConfigurationDoneRequest": true,
"supportsEvaluateForHovers": true,
"supportsFunctionBreakpoints": true,
"supportsTerminateRequest": true,
}),
);
self.event("initialized", json!({}));
}
"setBreakpoints" => self.set_breakpoints(msg),
"setFunctionBreakpoints" => self.set_function_breakpoints(msg),
"setExceptionBreakpoints" => self.respond(msg, json!({})),
"launch" => {
let raw = msg["arguments"]["program"].as_str().unwrap_or("");
self.program = Some(Self::canon(raw));
if msg["arguments"]["stopOnEntry"].as_bool().unwrap_or(false) {
self.step_mode = true;
}
self.respond(msg, json!({}));
return self.maybe_start();
}
"configurationDone" => {
self.config_done = true;
self.respond(msg, json!({}));
return self.maybe_start();
}
"threads" => self.respond(msg, json!({"threads": [{"id": 1, "name": "main"}]})),
"disconnect" | "terminate" => {
self.respond(msg, json!({}));
self.disconnected = true;
}
"source" => self.respond(msg, json!({})),
_ => self.respond(msg, json!({})),
}
false
}
fn breakpoint_hit(&self, line: u32) -> bool {
self.program
.as_ref()
.and_then(|p| self.breakpoints.get(p))
.map(|s| s.contains(&line))
.unwrap_or(false)
}
fn on_line(&mut self, line: u32) {
if self.disconnected {
return;
}
self.cur_line = line;
let reason = if self.pause_request {
self.pause_request = false;
self.func_bp_armed = false;
"pause"
} else if self.func_bp_armed {
self.func_bp_armed = false;
"function breakpoint"
} else if self.step_mode {
"step"
} else if self.breakpoint_hit(line) {
"breakpoint"
} else {
return;
};
let file = self.program.clone().unwrap_or_default();
self.event(
"stopped",
json!({
"reason": reason,
"threadId": 1,
"allThreadsStopped": true,
"text": format!("{file}:{line}"),
}),
);
match self.pause_loop() {
Resume::Continue => self.step_mode = false,
Resume::Step => self.step_mode = true,
Resume::Quit => {
self.disconnected = true;
}
}
}
fn pause_loop(&mut self) -> Resume {
loop {
let Some(msg) = self.read_msg() else {
return Resume::Quit; };
if msg["type"] != "request" {
continue;
}
match msg["command"].as_str().unwrap_or("") {
"continue" => {
self.respond(&msg, json!({"allThreadsContinued": true}));
return Resume::Continue;
}
"next" | "stepIn" => {
self.respond(&msg, json!({"allThreadsContinued": true}));
return Resume::Step;
}
"stepOut" => {
self.respond(&msg, json!({"allThreadsContinued": true}));
return Resume::Continue;
}
"pause" => self.respond(&msg, json!({})), "threads" => self.respond(&msg, json!({"threads": [{"id": 1, "name": "main"}]})),
"stackTrace" => {
let frame = json!({
"id": 1, "name": "main", "line": self.cur_line, "column": 1,
"source": {"path": self.program.clone().unwrap_or_default()},
});
self.respond(&msg, json!({"stackFrames": [frame], "totalFrames": 1}));
}
"scopes" => {
self.respond(
&msg,
json!({"scopes": [{
"name": "Globals", "variablesReference": 1000, "expensive": false,
}]}),
);
}
"variables" => {
let vars = global_variables();
self.respond(&msg, json!({"variables": vars}));
}
"evaluate" => {
let expr = msg["arguments"]["expression"].as_str().unwrap_or("");
let result = eval_in_host(expr);
self.respond(&msg, json!({"result": result, "variablesReference": 0}));
}
"setBreakpoints" => self.set_breakpoints(&msg),
"setFunctionBreakpoints" => self.set_function_breakpoints(&msg),
"setExceptionBreakpoints" => self.respond(&msg, json!({})),
"source" => self.respond(&msg, json!({})),
"disconnect" | "terminate" => {
self.respond(&msg, json!({}));
return Resume::Quit;
}
_ => self.respond(&msg, json!({})),
}
}
}
fn terminate(&mut self) {
self.event("terminated", json!({}));
self.event("exited", json!({"exitCode": 0}));
}
fn read_msg(&mut self) -> Option<J> {
let mut content_len = 0usize;
loop {
let mut line = String::new();
if self.reader.read_line(&mut line).ok()? == 0 {
return None;
}
let t = line.trim_end();
if t.is_empty() {
break;
}
if let Some(v) = t.strip_prefix("Content-Length:") {
content_len = v.trim().parse().ok()?;
}
}
let mut buf = vec![0u8; content_len];
self.reader.read_exact(&mut buf).ok()?;
serde_json::from_slice(&buf).ok()
}
}
fn global_variables() -> Vec<J> {
with_host(|h| {
let mut out = Vec::new();
for obj in &h.arena {
if let Obj::Symbol(s) = obj {
if let Some(v) = &s.value {
out.push(json!({
"name": s.name,
"value": h.print(v, true),
"variablesReference": 0,
}));
}
}
}
out.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str()));
out
})
}
fn eval_in_host(expr: &str) -> String {
let prev = host::debug_mode();
host::set_debug_mode(false);
let result = (|| {
let forms = with_host(|h| crate::reader::read_all(h, expr))
.map_err(|e| format!("read error: {e}"))?;
let mut last = String::from("nil");
for form in &forms {
let chunk = with_host(|h| crate::compiler::compile_top(h, form))
.map_err(|e| format!("error: {e}"))?;
match host::run_chunk(chunk) {
Ok(v) => last = with_host(|h| h.print(&v, true)),
Err(e) => return Err(format!("error: {e}")),
}
}
Ok(last)
})();
host::set_debug_mode(prev);
result.unwrap_or_else(|e| e)
}
struct Capture {
out: Arc<Mutex<File>>,
saved_stdout: i32,
reader_thread: Option<std::thread::JoinHandle<()>>,
}
impl Capture {
fn start() -> Result<Self, String> {
unsafe {
let saved = libc::dup(1);
if saved < 0 {
return Err("dup(stdout) failed".into());
}
let mut fds = [0i32; 2];
if libc::pipe(fds.as_mut_ptr()) != 0 {
return Err("pipe() failed".into());
}
let (read_fd, write_fd) = (fds[0], fds[1]);
if libc::dup2(write_fd, 1) < 0 {
return Err("dup2() failed".into());
}
libc::close(write_fd);
let out: Arc<Mutex<File>> = Arc::new(Mutex::new(File::from_raw_fd(saved)));
let out_thread = out.clone();
let reader_thread = std::thread::spawn(move || {
let mut f = File::from_raw_fd(read_fd);
let mut buf = [0u8; 4096];
loop {
match f.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
let text = String::from_utf8_lossy(&buf[..n]).into_owned();
let msg = json!({
"seq": 0, "type": "event", "event": "output",
"body": {"category": "stdout", "output": text},
});
let s = msg.to_string();
if let Ok(mut w) = out_thread.lock() {
let _ = write!(w, "Content-Length: {}\r\n\r\n{}", s.len(), s);
let _ = w.flush();
}
}
}
}
});
Ok(Capture {
out,
saved_stdout: saved,
reader_thread: Some(reader_thread),
})
}
}
}
impl Capture {
fn finish(&mut self) {
unsafe {
libc::dup2(self.saved_stdout, 1);
}
if let Some(t) = self.reader_thread.take() {
let _ = t.join();
}
}
}
impl Drop for Capture {
fn drop(&mut self) {
self.finish();
}
}