diff --git a/helix-dap/src/lib.rs b/helix-dap/src/lib.rs index d0229249d..b0605c4f0 100644 --- a/helix-dap/src/lib.rs +++ b/helix-dap/src/lib.rs @@ -3,10 +3,11 @@ mod transport; mod types; pub use client::{Client, ConnectionType}; -pub use events::Event; pub use transport::{Payload, Response, Transport}; pub use types::*; +use serde::de::DeserializeOwned; + use thiserror::Error; #[derive(Error, Debug)] pub enum Error { @@ -18,9 +19,84 @@ pub enum Error { Timeout(u64), #[error("server closed the stream")] StreamClosed, + #[error("Unhandled")] + Unhandled, #[error(transparent)] ExecutableNotFound(#[from] helix_stdx::env::ExecutableNotFoundError), #[error(transparent)] Other(#[from] anyhow::Error), } pub type Result = core::result::Result; + +#[derive(Debug)] +pub enum Request { + RunInTerminal(::Arguments), +} + +impl Request { + pub fn parse(command: &str, arguments: Option) -> Result { + use crate::types::Request as _; + + let arguments = arguments.unwrap_or_default(); + let request = match command { + requests::RunInTerminal::COMMAND => Self::RunInTerminal(parse_value(arguments)?), + _ => return Err(Error::Unhandled), + }; + + Ok(request) + } +} + +#[derive(Debug)] +pub enum Event { + Initialized(::Body), + Stopped(::Body), + Continued(::Body), + Exited(::Body), + Terminated(::Body), + Thread(::Body), + Output(::Body), + Breakpoint(::Body), + Module(::Body), + LoadedSource(::Body), + Process(::Body), + Capabilities(::Body), + // ProgressStart(), + // ProgressUpdate(), + // ProgressEnd(), + // Invalidated(), + Memory(::Body), +} + +impl Event { + pub fn parse(event: &str, body: Option) -> Result { + use crate::events::Event as _; + + let body = body.unwrap_or_default(); + let event = match event { + events::Initialized::EVENT => Self::Initialized(parse_value(body)?), + events::Stopped::EVENT => Self::Stopped(parse_value(body)?), + events::Continued::EVENT => Self::Continued(parse_value(body)?), + events::Exited::EVENT => Self::Exited(parse_value(body)?), + events::Terminated::EVENT => Self::Terminated(parse_value(body)?), + events::Thread::EVENT => Self::Thread(parse_value(body)?), + events::Output::EVENT => Self::Output(parse_value(body)?), + events::Breakpoint::EVENT => Self::Breakpoint(parse_value(body)?), + events::Module::EVENT => Self::Module(parse_value(body)?), + events::LoadedSource::EVENT => Self::LoadedSource(parse_value(body)?), + events::Process::EVENT => Self::Process(parse_value(body)?), + events::Capabilities::EVENT => Self::Capabilities(parse_value(body)?), + events::Memory::EVENT => Self::Memory(parse_value(body)?), + _ => return Err(Error::Unhandled), + }; + + Ok(event) + } +} + +fn parse_value(value: serde_json::Value) -> Result +where + T: DeserializeOwned, +{ + serde_json::from_value(value).map_err(|err| err.into()) +} diff --git a/helix-dap/src/transport.rs b/helix-dap/src/transport.rs index 0f646b6a4..1b1fca5f6 100644 --- a/helix-dap/src/transport.rs +++ b/helix-dap/src/transport.rs @@ -1,4 +1,4 @@ -use crate::{Error, Event, Result}; +use crate::{Error, Result}; use anyhow::Context; use log::{error, info, warn}; use serde::{Deserialize, Serialize}; @@ -32,11 +32,17 @@ pub struct Response { pub body: Option, } +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +pub struct Event { + pub event: String, + pub body: Option, +} + #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum Payload { // type = "event" - Event(Box), + Event(Event), // type = "response" Response(Response), // type = "request" diff --git a/helix-dap/src/types.rs b/helix-dap/src/types.rs index 5a198714c..67f4937f1 100644 --- a/helix-dap/src/types.rs +++ b/helix-dap/src/types.rs @@ -759,33 +759,30 @@ pub mod requests { pub mod events { use super::*; - #[derive(Debug, Clone, Serialize, Deserialize)] - #[serde(rename_all = "camelCase")] - #[serde(tag = "event", content = "body")] - // seq is omitted as unused and is not sent by some implementations - pub enum Event { - Initialized(Option), - Stopped(Stopped), - Continued(Continued), - Exited(Exited), - Terminated(Option), - Thread(Thread), - Output(Output), - Breakpoint(Breakpoint), - Module(Module), - LoadedSource(LoadedSource), - Process(Process), - Capabilities(Capabilities), - // ProgressStart(), - // ProgressUpdate(), - // ProgressEnd(), - // Invalidated(), - Memory(Memory), + pub trait Event { + type Body: serde::de::DeserializeOwned + serde::Serialize; + const EVENT: &'static str; + } + + #[derive(Debug)] + pub enum Initialized {} + + impl Event for Initialized { + type Body = Option; + const EVENT: &'static str = "initialized"; + } + + #[derive(Debug)] + pub enum Stopped {} + + impl Event for Stopped { + type Body = StoppedBody; + const EVENT: &'static str = "stopped"; } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Stopped { + pub struct StoppedBody { pub reason: String, #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, @@ -801,37 +798,77 @@ pub mod events { pub hit_breakpoint_ids: Option>, } + #[derive(Debug)] + pub enum Continued {} + + impl Event for Continued { + type Body = ContinuedBody; + const EVENT: &'static str = "continued"; + } + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Continued { + pub struct ContinuedBody { pub thread_id: ThreadId, #[serde(skip_serializing_if = "Option::is_none")] pub all_threads_continued: Option, } - #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] - #[serde(rename_all = "camelCase")] - pub struct Exited { - pub exit_code: usize, + #[derive(Debug)] + pub enum Exited {} + + impl Event for Exited { + type Body = ExitedBody; + const EVENT: &'static str = "exited"; } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Terminated { + pub struct ExitedBody { + pub exit_code: usize, + } + + #[derive(Debug)] + pub enum Terminated {} + + impl Event for Terminated { + type Body = Option; + const EVENT: &'static str = "terminated"; + } + + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] + #[serde(rename_all = "camelCase")] + pub struct TerminatedBody { #[serde(skip_serializing_if = "Option::is_none")] pub restart: Option, } - #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] - #[serde(rename_all = "camelCase")] - pub struct Thread { - pub reason: String, - pub thread_id: ThreadId, + #[derive(Debug)] + pub enum Thread {} + + impl Event for Thread { + type Body = ThreadBody; + const EVENT: &'static str = "thread"; } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Output { + pub struct ThreadBody { + pub reason: String, + pub thread_id: ThreadId, + } + + #[derive(Debug)] + pub enum Output {} + + impl Event for Output { + type Body = OutputBody; + const EVENT: &'static str = "output"; + } + + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] + #[serde(rename_all = "camelCase")] + pub struct OutputBody { pub output: String, #[serde(skip_serializing_if = "Option::is_none")] pub category: Option, @@ -849,30 +886,62 @@ pub mod events { pub data: Option, } + #[derive(Debug)] + pub enum Breakpoint {} + + impl Event for Breakpoint { + type Body = BreakpointBody; + const EVENT: &'static str = "breakpoint"; + } + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Breakpoint { + pub struct BreakpointBody { pub reason: String, pub breakpoint: super::Breakpoint, } + #[derive(Debug)] + pub enum Module {} + + impl Event for Module { + type Body = ModuleBody; + const EVENT: &'static str = "module"; + } + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Module { + pub struct ModuleBody { pub reason: String, pub module: super::Module, } - #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] - #[serde(rename_all = "camelCase")] - pub struct LoadedSource { - pub reason: String, - pub source: super::Source, + #[derive(Debug)] + pub enum LoadedSource {} + + impl Event for LoadedSource { + type Body = LoadedSourceBody; + const EVENT: &'static str = "loadedSource"; } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Process { + pub struct LoadedSourceBody { + pub reason: String, + pub source: super::Source, + } + + #[derive(Debug)] + pub enum Process {} + + impl Event for Process { + type Body = ProcessBody; + const EVENT: &'static str = "process"; + } + + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] + #[serde(rename_all = "camelCase")] + pub struct ProcessBody { pub name: String, #[serde(skip_serializing_if = "Option::is_none")] pub system_process_id: Option, @@ -884,38 +953,55 @@ pub mod events { pub pointer_size: Option, } + #[derive(Debug)] + pub enum Capabilities {} + + impl Event for Capabilities { + type Body = CapabilitiesBody; + const EVENT: &'static str = "capabilities"; + } + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Capabilities { + pub struct CapabilitiesBody { pub capabilities: super::DebuggerCapabilities, } // #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] // #[serde(rename_all = "camelCase")] - // pub struct Invalidated { + // pub struct InvalidatedBody { // pub areas: Vec, // pub thread_id: Option, // pub stack_frame_id: Option, // } + #[derive(Debug)] + pub enum Memory {} + + impl Event for Memory { + type Body = MemoryBody; + const EVENT: &'static str = "memory"; + } + #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Memory { + pub struct MemoryBody { pub memory_reference: String, pub offset: usize, pub count: usize, } +} #[test] fn test_deserialize_module_id_from_number() { let raw = r#"{"id": 0, "name": "Name"}"#; - let module: super::Module = serde_json::from_str(raw).expect("Error!"); + let module: Module = serde_json::from_str(raw).expect("Error!"); assert_eq!(module.id, "0"); } #[test] fn test_deserialize_module_id_from_string() { let raw = r#"{"id": "0", "name": "Name"}"#; - let module: super::Module = serde_json::from_str(raw).expect("Error!"); + let module: Module = serde_json::from_str(raw).expect("Error!"); assert_eq!(module.id, "0"); } diff --git a/helix-view/src/handlers/dap.rs b/helix-view/src/handlers/dap.rs index 81766dd59..56eb8efa9 100644 --- a/helix-view/src/handlers/dap.rs +++ b/helix-view/src/handlers/dap.rs @@ -5,6 +5,7 @@ use helix_core::Selection; use helix_dap::{self as dap, Client, ConnectionType, Payload, Request, ThreadId}; use helix_lsp::block_on; use log::warn; +use serde_json::json; use std::fmt::Write; use std::path::PathBuf; @@ -141,7 +142,6 @@ pub fn breakpoints_changed( impl Editor { pub async fn handle_debugger_message(&mut self, payload: helix_dap::Payload) -> bool { - use dap::requests::RunInTerminal; use helix_dap::{events, Event}; let debugger = match self.debugger.as_mut() { @@ -149,250 +149,260 @@ impl Editor { None => return false, }; match payload { - Payload::Event(ev) => match *ev { - Event::Stopped(events::Stopped { - thread_id, - description, - text, - reason, - all_threads_stopped, - .. - }) => { - let all_threads_stopped = all_threads_stopped.unwrap_or_default(); - - if all_threads_stopped { - if let Ok(response) = debugger.request::(()).await { - for thread in response.threads { - fetch_stack_trace(debugger, thread.id).await; - } - select_thread_id(self, thread_id.unwrap_or_default(), false).await; - } - } else if let Some(thread_id) = thread_id { - debugger.thread_states.insert(thread_id, reason.clone()); // TODO: dap uses "type" || "reason" here - - // whichever thread stops is made "current" (if no previously selected thread). - select_thread_id(self, thread_id, false).await; - } - - let scope = match thread_id { - Some(id) => format!("Thread {}", id), - None => "Target".to_owned(), - }; - - let mut status = format!("{} stopped because of {}", scope, reason); - if let Some(desc) = description { - write!(status, " {}", desc).unwrap(); - } - if let Some(text) = text { - write!(status, " {}", text).unwrap(); - } - if all_threads_stopped { - status.push_str(" (all threads stopped)"); - } - - self.set_status(status); - } - Event::Continued(events::Continued { thread_id, .. }) => { - debugger - .thread_states - .insert(thread_id, "running".to_owned()); - if debugger.thread_id == Some(thread_id) { - debugger.resume_application(); - } - } - Event::Thread(_) => { - // TODO: update thread_states, make threads request - } - Event::Breakpoint(events::Breakpoint { reason, breakpoint }) => { - match &reason[..] { - "new" => { - if let Some(source) = breakpoint.source { - self.breakpoints - .entry(source.path.unwrap()) // TODO: no unwraps - .or_default() - .push(Breakpoint { - id: breakpoint.id, - verified: breakpoint.verified, - message: breakpoint.message, - line: breakpoint.line.unwrap().saturating_sub(1), // TODO: no unwrap - column: breakpoint.column, - ..Default::default() - }); - } - } - "changed" => { - for breakpoints in self.breakpoints.values_mut() { - if let Some(i) = - breakpoints.iter().position(|b| b.id == breakpoint.id) - { - breakpoints[i].verified = breakpoint.verified; - breakpoints[i].message = breakpoint - .message - .clone() - .or_else(|| breakpoints[i].message.take()); - breakpoints[i].line = breakpoint - .line - .map_or(breakpoints[i].line, |line| line.saturating_sub(1)); - breakpoints[i].column = - breakpoint.column.or(breakpoints[i].column); - } - } - } - "removed" => { - for breakpoints in self.breakpoints.values_mut() { - if let Some(i) = - breakpoints.iter().position(|b| b.id == breakpoint.id) - { - breakpoints.remove(i); - } - } - } - reason => { - warn!("Unknown breakpoint event: {}", reason); - } - } - } - Event::Output(events::Output { - category, output, .. - }) => { - let prefix = match category { - Some(category) => { - if &category == "telemetry" { - return false; - } - format!("Debug ({}):", category) - } - None => "Debug:".to_owned(), - }; - - log::info!("{}", output); - self.set_status(format!("{} {}", prefix, output)); - } - Event::Initialized(_) => { - // send existing breakpoints - for (path, breakpoints) in &mut self.breakpoints { - // TODO: call futures in parallel, await all - let _ = breakpoints_changed(debugger, path.clone(), breakpoints); - } - // TODO: fetch breakpoints (in case we're attaching) - - if debugger.configuration_done().await.is_ok() { - self.set_status("Debugged application started"); - }; // TODO: do we need to handle error? - } - Event::Terminated(terminated) => { - let restart_args = if let Some(terminated) = terminated { - terminated.restart - } else { - None - }; - - let disconnect_args = Some(DisconnectArguments { - restart: Some(restart_args.is_some()), - terminate_debuggee: None, - suspend_debuggee: None, - }); - - if let Err(err) = debugger.disconnect(disconnect_args).await { - self.set_error(format!( - "Cannot disconnect debugger upon terminated event receival {:?}", - err - )); + Payload::Event(event) => { + let event = match Event::parse(&event.event, event.body) { + Ok(event) => event, + Err(dap::Error::Unhandled) => { + log::info!("Discarding unknown DAP event '{}'", event.event); return false; } + Err(err) => { + log::warn!("Discarding invalid DAP event '{}': {err}", event.event); + return false; + } + }; + match event { + Event::Stopped(events::StoppedBody { + thread_id, + description, + text, + reason, + all_threads_stopped, + .. + }) => { + let all_threads_stopped = all_threads_stopped.unwrap_or_default(); - match restart_args { - Some(restart_args) => { - log::info!("Attempting to restart debug session."); - let connection_type = match debugger.connection_type() { - Some(connection_type) => connection_type, - None => { - self.set_error("No starting request found, to be used in restarting the debugging session."); - return false; + if all_threads_stopped { + if let Ok(response) = + debugger.request::(()).await + { + for thread in response.threads { + fetch_stack_trace(debugger, thread.id).await; } - }; + select_thread_id(self, thread_id.unwrap_or_default(), false).await; + } + } else if let Some(thread_id) = thread_id { + debugger.thread_states.insert(thread_id, reason.clone()); // TODO: dap uses "type" || "reason" here - let relaunch_resp = if let ConnectionType::Launch = connection_type { - debugger.launch(restart_args).await - } else { - debugger.attach(restart_args).await - }; + // whichever thread stops is made "current" (if no previously selected thread). + select_thread_id(self, thread_id, false).await; + } - if let Err(err) = relaunch_resp { - self.set_error(format!( - "Failed to restart debugging session: {:?}", - err - )); + let scope = match thread_id { + Some(id) => format!("Thread {}", id), + None => "Target".to_owned(), + }; + + let mut status = format!("{} stopped because of {}", scope, reason); + if let Some(desc) = description { + write!(status, " {}", desc).unwrap(); + } + if let Some(text) = text { + write!(status, " {}", text).unwrap(); + } + if all_threads_stopped { + status.push_str(" (all threads stopped)"); + } + + self.set_status(status); + } + Event::Continued(events::ContinuedBody { thread_id, .. }) => { + debugger + .thread_states + .insert(thread_id, "running".to_owned()); + if debugger.thread_id == Some(thread_id) { + debugger.resume_application(); + } + } + Event::Thread(_) => { + // TODO: update thread_states, make threads request + } + Event::Breakpoint(events::BreakpointBody { reason, breakpoint }) => { + match &reason[..] { + "new" => { + if let Some(source) = breakpoint.source { + self.breakpoints + .entry(source.path.unwrap()) // TODO: no unwraps + .or_default() + .push(Breakpoint { + id: breakpoint.id, + verified: breakpoint.verified, + message: breakpoint.message, + line: breakpoint.line.unwrap().saturating_sub(1), // TODO: no unwrap + column: breakpoint.column, + ..Default::default() + }); + } + } + "changed" => { + for breakpoints in self.breakpoints.values_mut() { + if let Some(i) = + breakpoints.iter().position(|b| b.id == breakpoint.id) + { + breakpoints[i].verified = breakpoint.verified; + breakpoints[i].message = breakpoint + .message + .clone() + .or_else(|| breakpoints[i].message.take()); + breakpoints[i].line = + breakpoint.line.map_or(breakpoints[i].line, |line| { + line.saturating_sub(1) + }); + breakpoints[i].column = + breakpoint.column.or(breakpoints[i].column); + } + } + } + "removed" => { + for breakpoints in self.breakpoints.values_mut() { + if let Some(i) = + breakpoints.iter().position(|b| b.id == breakpoint.id) + { + breakpoints.remove(i); + } + } + } + reason => { + warn!("Unknown breakpoint event: {}", reason); } } - None => { - self.debugger = None; - self.set_status( - "Terminated debugging session and disconnected debugger.", - ); + } + Event::Output(events::OutputBody { + category, output, .. + }) => { + let prefix = match category { + Some(category) => { + if &category == "telemetry" { + return false; + } + format!("Debug ({}):", category) + } + None => "Debug:".to_owned(), + }; + + log::info!("{}", output); + self.set_status(format!("{} {}", prefix, output)); + } + Event::Initialized(_) => { + // send existing breakpoints + for (path, breakpoints) in &mut self.breakpoints { + // TODO: call futures in parallel, await all + let _ = breakpoints_changed(debugger, path.clone(), breakpoints); + } + // TODO: fetch breakpoints (in case we're attaching) + + if debugger.configuration_done().await.is_ok() { + self.set_status("Debugged application started"); + }; // TODO: do we need to handle error? + } + Event::Terminated(terminated) => { + let restart_args = if let Some(terminated) = terminated { + terminated.restart + } else { + None + }; + + let disconnect_args = Some(DisconnectArguments { + restart: Some(restart_args.is_some()), + terminate_debuggee: None, + suspend_debuggee: None, + }); + + if let Err(err) = debugger.disconnect(disconnect_args).await { + self.set_error(format!( + "Cannot disconnect debugger upon terminated event receival {:?}", + err + )); + return false; + } + + match restart_args { + Some(restart_args) => { + log::info!("Attempting to restart debug session."); + let connection_type = match debugger.connection_type() { + Some(connection_type) => connection_type, + None => { + self.set_error("No starting request found, to be used in restarting the debugging session."); + return false; + } + }; + + let relaunch_resp = if let ConnectionType::Launch = connection_type + { + debugger.launch(restart_args).await + } else { + debugger.attach(restart_args).await + }; + + if let Err(err) = relaunch_resp { + self.set_error(format!( + "Failed to restart debugging session: {:?}", + err + )); + } + } + None => { + self.debugger = None; + self.set_status( + "Terminated debugging session and disconnected debugger.", + ); + } } } - } - Event::Exited(resp) => { - let exit_code = resp.exit_code; - if exit_code != 0 { - self.set_error(format!( - "Debuggee failed to exit successfully (exit code: {exit_code})." - )); + Event::Exited(resp) => { + let exit_code = resp.exit_code; + if exit_code != 0 { + self.set_error(format!( + "Debuggee failed to exit successfully (exit code: {exit_code})." + )); + } + } + ev => { + log::warn!("Unhandled event {:?}", ev); + return false; // return early to skip render } } - ev => { - log::warn!("Unhandled event {:?}", ev); - return false; // return early to skip render - } - }, + } Payload::Response(_) => unreachable!(), - Payload::Request(request) => match request.command.as_str() { - RunInTerminal::COMMAND => { - let arguments: dap::requests::RunInTerminalArguments = - serde_json::from_value(request.arguments.unwrap_or_default()).unwrap(); - // TODO: no unwrap - - let config = match self.config().terminal.clone() { - Some(config) => config, - None => { + Payload::Request(request) => { + let reply = match Request::parse(&request.command, request.arguments) { + Ok(Request::RunInTerminal(arguments)) => { + let config = self.config(); + let Some(config) = config.terminal.as_ref() else { self.set_error("No external terminal defined"); return true; - } - }; + }; - // Re-borrowing debugger to avoid issues when loading config - let debugger = match self.debugger.as_mut() { - Some(debugger) => debugger, - None => return false, - }; + let process = match std::process::Command::new(&config.command) + .args(&config.args) + .arg(arguments.args.join(" ")) + .spawn() + { + Ok(process) => process, + Err(err) => { + self.set_error(format!( + "Error starting external terminal: {}", + err + )); + return true; + } + }; - let process = match std::process::Command::new(config.command) - .args(config.args) - .arg(arguments.args.join(" ")) - .spawn() - { - Ok(process) => process, - Err(err) => { - self.set_error(format!("Error starting external terminal: {}", err)); - return true; - } - }; + Ok(json!(dap::requests::RunInTerminalResponse { + process_id: Some(process.id()), + shell_process_id: None, + })) + } + Err(err) => Err(err), + }; - let _ = debugger - .reply( - request.seq, - dap::requests::RunInTerminal::COMMAND, - serde_json::to_value(dap::requests::RunInTerminalResponse { - process_id: Some(process.id()), - shell_process_id: None, - }) - .map_err(|e| e.into()), - ) - .await; + if let Some(debugger) = self.debugger.as_mut() { + debugger + .reply(request.seq, &request.command, reply) + .await + .ok(); } - _ => log::error!("DAP reverse request not implemented: {:?}", request), - }, + } } true }