summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock18
-rw-r--r--Cargo.toml1
-rw-r--r--helix-core/Cargo.toml1
-rw-r--r--helix-core/src/indent.rs1
-rw-r--r--helix-core/src/lib.rs2
-rw-r--r--helix-core/src/syntax.rs37
-rw-r--r--helix-dap/Cargo.toml23
-rw-r--r--helix-dap/examples/dap-dlv.rs117
-rw-r--r--helix-dap/examples/dap-lldb.rs119
-rw-r--r--helix-dap/src/client.rs395
-rw-r--r--helix-dap/src/lib.rs24
-rw-r--r--helix-dap/src/transport.rs246
-rw-r--r--helix-dap/src/types.rs652
-rw-r--r--helix-lsp/Cargo.toml4
-rw-r--r--helix-term/Cargo.toml3
-rw-r--r--helix-term/src/application.rs96
-rw-r--r--helix-term/src/commands.rs203
-rw-r--r--helix-term/src/commands/dap.rs445
-rw-r--r--helix-term/src/keymap.rs17
-rw-r--r--helix-term/src/ui/editor.rs265
-rw-r--r--helix-view/Cargo.toml2
-rw-r--r--helix-view/src/editor.rs19
-rw-r--r--languages.toml88
23 files changed, 2764 insertions, 14 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 298ad15b..4ae20db5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -306,6 +306,7 @@ version = "0.4.1"
dependencies = [
"arc-swap",
"etcetera",
+ "helix-dap",
"helix-syntax",
"once_cell",
"quickcheck",
@@ -323,6 +324,19 @@ dependencies = [
]
[[package]]
+name = "helix-dap"
+version = "0.4.1"
+dependencies = [
+ "anyhow",
+ "fern",
+ "log",
+ "serde",
+ "serde_json",
+ "thiserror",
+ "tokio",
+]
+
+[[package]]
name = "helix-lsp"
version = "0.4.1"
dependencies = [
@@ -362,6 +376,7 @@ dependencies = [
"futures-util",
"fuzzy-matcher",
"helix-core",
+ "helix-dap",
"helix-lsp",
"helix-tui",
"helix-view",
@@ -375,6 +390,7 @@ dependencies = [
"signal-hook",
"signal-hook-tokio",
"tokio",
+ "tokio-stream",
"toml",
]
@@ -403,6 +419,7 @@ dependencies = [
"encoding_rs",
"futures-util",
"helix-core",
+ "helix-dap",
"helix-lsp",
"helix-tui",
"log",
@@ -410,6 +427,7 @@ dependencies = [
"serde",
"slotmap",
"tokio",
+ "tokio-stream",
"toml",
"url",
"which",
diff --git a/Cargo.toml b/Cargo.toml
index 22d29260..2f841c85 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,6 +6,7 @@ members = [
"helix-tui",
"helix-syntax",
"helix-lsp",
+ "helix-dap",
]
# Build helix-syntax in release mode to make the code path faster in development.
diff --git a/helix-core/Cargo.toml b/helix-core/Cargo.toml
index 8c83816c..d26ff953 100644
--- a/helix-core/Cargo.toml
+++ b/helix-core/Cargo.toml
@@ -14,6 +14,7 @@ include = ["src/**/*", "README.md"]
[dependencies]
helix-syntax = { version = "0.4", path = "../helix-syntax" }
+helix-dap = { version = "0.4", path = "../helix-dap" }
ropey = "1.3"
smallvec = "1.4"
diff --git a/helix-core/src/indent.rs b/helix-core/src/indent.rs
index f5f36aca..4b74aa7a 100644
--- a/helix-core/src/indent.rs
+++ b/helix-core/src/indent.rs
@@ -458,6 +458,7 @@ where
unit: String::from(" "),
}),
indent_query: OnceCell::new(),
+ debugger: None,
}],
});
diff --git a/helix-core/src/lib.rs b/helix-core/src/lib.rs
index d971464a..0854eb04 100644
--- a/helix-core/src/lib.rs
+++ b/helix-core/src/lib.rs
@@ -195,7 +195,7 @@ pub use {regex, tree_sitter};
pub use graphemes::RopeGraphemes;
pub use position::{coords_at_pos, pos_at_coords, Position};
pub use selection::{Range, Selection};
-pub use smallvec::SmallVec;
+pub use smallvec::{smallvec, SmallVec};
pub use syntax::Syntax;
pub use diagnostic::Diagnostic;
diff --git a/helix-core/src/syntax.rs b/helix-core/src/syntax.rs
index 64b921e6..cabfe083 100644
--- a/helix-core/src/syntax.rs
+++ b/helix-core/src/syntax.rs
@@ -55,6 +55,8 @@ pub struct LanguageConfiguration {
#[serde(skip)]
pub(crate) indent_query: OnceCell<Option<IndentQuery>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub debugger: Option<DebugAdapterConfig>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -66,6 +68,41 @@ pub struct LanguageServerConfiguration {
pub args: Vec<String>,
}
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct AdvancedCompletion {
+ pub name: Option<String>,
+ pub completion: Option<String>,
+ pub default: Option<String>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "kebab-case", untagged)]
+pub enum DebugConfigCompletion {
+ Named(String),
+ Advanced(AdvancedCompletion),
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct DebugTemplate {
+ pub name: String,
+ pub request: String,
+ pub completion: Vec<DebugConfigCompletion>,
+ pub args: HashMap<String, String>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct DebugAdapterConfig {
+ pub name: String,
+ pub transport: String,
+ pub command: String,
+ pub args: Vec<String>,
+ pub port_arg: Option<String>,
+ pub templates: Vec<DebugTemplate>,
+}
+
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct IndentationConfiguration {
diff --git a/helix-dap/Cargo.toml b/helix-dap/Cargo.toml
new file mode 100644
index 00000000..60115447
--- /dev/null
+++ b/helix-dap/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+name = "helix-dap"
+version = "0.4.1"
+authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
+edition = "2018"
+license = "MPL-2.0"
+description = "DAP client implementation for Helix project"
+categories = ["editor"]
+repository = "https://github.com/helix-editor/helix"
+homepage = "https://helix-editor.com"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+anyhow = "1.0"
+log = "0.4"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+thiserror = "1.0"
+tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "net", "sync"] }
+
+[dev-dependencies]
+fern = "0.6"
diff --git a/helix-dap/examples/dap-dlv.rs b/helix-dap/examples/dap-dlv.rs
new file mode 100644
index 00000000..eecc4318
--- /dev/null
+++ b/helix-dap/examples/dap-dlv.rs
@@ -0,0 +1,117 @@
+use helix_dap::{events, Client, Event, Payload, Result, SourceBreakpoint};
+use serde::{Deserialize, Serialize};
+use serde_json::to_value;
+use tokio::sync::mpsc::UnboundedReceiver;
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct LaunchArguments {
+ mode: String,
+ program: String,
+}
+
+async fn dispatch(mut rx: UnboundedReceiver<Payload>) {
+ loop {
+ match rx.recv().await.unwrap() {
+ Payload::Event(Event::Output(events::Output {
+ category, output, ..
+ })) => {
+ println!(
+ "> [{}] {}",
+ category.unwrap_or("unknown".to_owned()),
+ output
+ );
+ }
+ Payload::Event(Event::Stopped(_)) => {
+ println!("stopped");
+ }
+ _ => {}
+ };
+ }
+}
+
+#[tokio::main]
+pub async fn main() -> Result<()> {
+ let base_config = fern::Dispatch::new().level(log::LevelFilter::Info);
+
+ let stderr_config = fern::Dispatch::new()
+ .format(|out, message, record| out.finish(format_args!("[{}] {}", record.level(), message)))
+ .chain(std::io::stderr());
+
+ base_config
+ .chain(stderr_config)
+ .apply()
+ .expect("Failed to set up logging");
+
+ let (mut client, events) =
+ Client::tcp_process("dlv", vec!["dap"], "-l 127.0.0.1:{}", 0).await?;
+ println!("create: {:?}", client);
+
+ tokio::spawn(dispatch(events));
+
+ println!("init: {:?}", client.initialize("go".to_owned()).await);
+ println!("caps: {:?}", client.capabilities());
+
+ let args = LaunchArguments {
+ mode: "exec".to_owned(),
+ program: "/tmp/godebug/main".to_owned(),
+ };
+
+ println!("launch: {:?}", client.launch(to_value(args)?).await);
+
+ println!(
+ "breakpoints: {:#?}",
+ client
+ .set_breakpoints(
+ "/tmp/godebug/main.go".into(),
+ vec![SourceBreakpoint {
+ line: 8,
+ column: Some(2),
+ condition: None,
+ hit_condition: None,
+ log_message: None,
+ }]
+ )
+ .await
+ );
+
+ let mut _in = String::new();
+ std::io::stdin()
+ .read_line(&mut _in)
+ .expect("Failed to read line");
+
+ println!("configurationDone: {:?}", client.configuration_done().await);
+
+ let threads = client.threads().await?;
+ println!("threads: {:#?}", threads);
+ let bt = client
+ .stack_trace(threads[0].id)
+ .await
+ .expect("expected stack trace");
+ println!("stack trace: {:#?}", bt);
+ let scopes = client
+ .scopes(bt.0[0].id)
+ .await
+ .expect("expected scopes for thread");
+ println!("scopes: {:#?}", scopes);
+ println!(
+ "vars: {:#?}",
+ client.variables(scopes[1].variables_reference).await
+ );
+
+ let mut _in = String::new();
+ std::io::stdin()
+ .read_line(&mut _in)
+ .expect("Failed to read line");
+
+ println!("continued: {:?}", client.continue_thread(0).await);
+
+ let mut _in = String::new();
+ std::io::stdin()
+ .read_line(&mut _in)
+ .expect("Failed to read line");
+
+ println!("disconnect: {:?}", client.disconnect().await);
+
+ Ok(())
+}
diff --git a/helix-dap/examples/dap-lldb.rs b/helix-dap/examples/dap-lldb.rs
new file mode 100644
index 00000000..2022ef48
--- /dev/null
+++ b/helix-dap/examples/dap-lldb.rs
@@ -0,0 +1,119 @@
+use helix_dap::{events, Client, Event, Payload, Result, SourceBreakpoint};
+use serde::{Deserialize, Serialize};
+use serde_json::to_value;
+use tokio::sync::mpsc::UnboundedReceiver;
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct LaunchArguments {
+ program: String,
+ console: String,
+}
+
+async fn dispatch(mut rx: UnboundedReceiver<Payload>) {
+ loop {
+ match rx.recv().await.unwrap() {
+ Payload::Event(Event::Output(events::Output {
+ category, output, ..
+ })) => {
+ println!(
+ "> [{}] {}",
+ category.unwrap_or("unknown".to_owned()),
+ output
+ );
+ }
+ Payload::Event(Event::Stopped(_)) => {
+ println!("stopped");
+ }
+ _ => {}
+ };
+ }
+}
+
+#[tokio::main]
+pub async fn main() -> Result<()> {
+ let base_config = fern::Dispatch::new().level(log::LevelFilter::Info);
+
+ let stderr_config = fern::Dispatch::new()
+ .format(|out, message, record| out.finish(format_args!("[{}] {}", record.level(), message)))
+ .chain(std::io::stderr());
+
+ base_config
+ .chain(stderr_config)
+ .apply()
+ .expect("Failed to set up logging");
+
+ let (mut client, events) = Client::tcp_process("lldb-vscode", vec![], "-p {}", 0).await?;
+ println!("create: {:?}", client);
+
+ tokio::spawn(dispatch(events));
+
+ println!(
+ "init: {:?}",
+ client.initialize("lldb-vscode".to_owned()).await
+ );
+ println!("caps: {:?}", client.capabilities());
+
+ let args = LaunchArguments {
+ program: "/tmp/cdebug/main".to_owned(),
+ console: "internalConsole".to_owned(),
+ };
+
+ println!("launch: {:?}", client.launch(to_value(args)?).await);
+
+ println!(
+ "breakpoints: {:#?}",
+ client
+ .set_breakpoints(
+ "/tmp/cdebug/main.c".into(),
+ vec![SourceBreakpoint {
+ line: 6,
+ column: Some(2),
+ condition: None,
+ hit_condition: None,
+ log_message: None,
+ }]
+ )
+ .await
+ );
+
+ let mut _in = String::new();
+ std::io::stdin()
+ .read_line(&mut _in)
+ .expect("Failed to read line");
+
+ println!("configurationDone: {:?}", client.configuration_done().await);
+
+ let threads = client.threads().await?;
+ println!("threads: {:#?}", threads);
+ let bt = client
+ .stack_trace(threads[0].id)
+ .await
+ .expect("expected stack trace");
+ println!("stack trace: {:#?}", bt);
+ let scopes = client
+ .scopes(bt.0[0].id)
+ .await
+ .expect("expected scopes for thread");
+ println!("scopes: {:#?}", scopes);
+ println!(
+ "vars: {:#?}",
+ client.variables(scopes[0].variables_reference).await
+ );
+
+ let mut _in = String::new();
+ std::io::stdin()
+ .read_line(&mut _in)
+ .expect("Failed to read line");
+
+ println!("continued: {:?}", client.continue_thread(0).await);
+
+ let mut _in = String::new();
+ std::io::stdin()
+ .read_line(&mut _in)
+ .expect("Failed to read line");
+
+ println!("disconnect: {:?}", client.disconnect().await);
+
+ Ok(())
+}
diff --git a/helix-dap/src/client.rs b/helix-dap/src/client.rs
new file mode 100644
index 00000000..72f7e12c
--- /dev/null
+++ b/helix-dap/src/client.rs
@@ -0,0 +1,395 @@
+use crate::{
+ transport::{Payload, Request, Transport},
+ types::*,
+ Error, Result,
+};
+use anyhow::anyhow;
+pub use log::{error, info};
+use std::{
+ collections::HashMap,
+ net::{IpAddr, Ipv4Addr, SocketAddr},
+ path::PathBuf,
+ process::Stdio,
+ sync::atomic::{AtomicU64, Ordering},
+};
+use tokio::{
+ io::{AsyncBufRead, AsyncWrite, BufReader, BufWriter},
+ net::TcpStream,
+ process::{Child, Command},
+ sync::mpsc::{channel, unbounded_channel, UnboundedReceiver, UnboundedSender},
+ time,
+};
+
+#[derive(Debug)]
+pub struct Client {
+ id: usize,
+ _process: Option<Child>,
+ server_tx: UnboundedSender<Request>,
+ request_counter: AtomicU64,
+ pub caps: Option<DebuggerCapabilities>,
+ //
+ pub breakpoints: HashMap<PathBuf, Vec<SourceBreakpoint>>,
+ // thread_id -> frames
+ pub stack_frames: HashMap<usize, Vec<StackFrame>>,
+ pub thread_id: Option<usize>,
+ /// Currently active frame for the current thread.
+ pub active_frame: Option<usize>,
+ pub is_running: bool, // TODO: track is_running per thread
+}
+
+impl Client {
+ // Spawn a process and communicate with it by either TCP or stdio
+ pub async fn process(
+ transport: String,
+ command: String,
+ args: Vec<String>,
+ port_arg: Option<String>,
+ id: usize,
+ ) -> Result<(Self, UnboundedReceiver<Payload>)> {
+ if transport == "tcp" && port_arg.is_some() {
+ Self::tcp_process(
+ &command,
+ args.iter().map(|s| s.as_str()).collect(),
+ &port_arg.unwrap(),
+ id,
+ )
+ .await
+ } else if transport == "stdio" {
+ Self::stdio(&command, args.iter().map(|s| s.as_str()).collect(), id)
+ } else {
+ Result::Err(Error::Other(anyhow!("Incorrect transport {}", transport)))
+ }
+ }
+
+ pub fn streams(
+ rx: Box<dyn AsyncBufRead + Unpin + Send>,
+ tx: Box<dyn AsyncWrite + Unpin + Send>,
+ id: usize,
+ process: Option<Child>,
+ ) -> Result<(Self, UnboundedReceiver<Payload>)> {
+ let (server_rx, server_tx) = Transport::start(rx, tx, id);
+ let (client_rx, client_tx) = unbounded_channel();
+
+ let client = Self {
+ id,
+ _process: process,
+ server_tx,
+ request_counter: AtomicU64::new(0),
+ caps: None,
+ //
+ breakpoints: HashMap::new(),
+ stack_frames: HashMap::new(),
+ thread_id: None,
+ active_frame: None,
+ is_running: false,
+ };
+
+ tokio::spawn(Self::recv(server_rx, client_rx));
+
+ Ok((client, client_tx))
+ }
+
+ pub async fn tcp(
+ addr: std::net::SocketAddr,
+ id: usize,
+ ) -> Result<(Self, UnboundedReceiver<Payload>)> {
+ let stream = TcpStream::connect(addr).await?;
+ let (rx, tx) = stream.into_split();
+ Self::streams(Box::new(BufReader::new(rx)), Box::new(tx), id, None)
+ }
+
+ pub fn stdio(
+ cmd: &str,
+ args: Vec<&str>,
+ id: usize,
+ ) -> Result<(Self, UnboundedReceiver<Payload>)> {
+ let process = Command::new(cmd)
+ .args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ // make sure the process is reaped on drop
+ .kill_on_drop(true)
+ .spawn();
+
+ let mut process = process?;
+
+ // TODO: do we need bufreader/writer here? or do we use async wrappers on unblock?
+ let writer = BufWriter::new(process.stdin.take().expect("Failed to open stdin"));
+ let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
+
+ Self::streams(
+ Box::new(BufReader::new(reader)),
+ Box::new(writer),
+ id,
+ Some(process),
+ )
+ }
+
+ async fn get_port() -> Option<u16> {
+ Some(
+ tokio::net::TcpListener::bind(SocketAddr::new(
+ IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
+ 0,
+ ))
+ .await
+ .ok()?
+ .local_addr()
+ .ok()?
+ .port(),
+ )
+ }
+
+ pub async fn tcp_process(
+ cmd: &str,
+ args: Vec<&str>,
+ port_format: &str,
+ id: usize,
+ ) -> Result<(Self, UnboundedReceiver<Payload>)> {
+ let port = Self::get_port().await.unwrap();
+
+ let process = Command::new(cmd)
+ .args(args)
+ .args(port_format.replace("{}", &port.to_string()).split(' '))
+ // silence messages
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ // Do not kill debug adapter when leaving, it should exit automatically
+ .spawn()?;
+
+ // Wait for adapter to become ready for connection
+ time::sleep(time::Duration::from_millis(500)).await;
+
+ let stream = TcpStream::connect(SocketAddr::new(
+ IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
+ port,
+ ))
+ .await?;
+
+ let (rx, tx) = stream.into_split();
+ Self::streams(
+ Box::new(BufReader::new(rx)),
+ Box::new(tx),
+ id,
+ Some(process),
+ )
+ }
+
+ async fn recv(mut server_rx: UnboundedReceiver<Payload>, client_tx: UnboundedSender<Payload>) {
+ while let Some(msg) = server_rx.recv().await {
+ match msg {
+ Payload::Event(ev) => {
+ client_tx.send(Payload::Event(ev)).expect("Failed to send");
+ }
+ Payload::Response(_) => unreachable!(),
+ Payload::Request(req) => {
+ client_tx
+ .send(Payload::Request(req))
+ .expect("Failed to send");
+ }
+ }
+ }
+ }
+
+ pub fn id(&self) -> usize {
+ self.id
+ }
+
+ fn next_request_id(&self) -> u64 {
+ self.request_counter.fetch_add(1, Ordering::Relaxed)
+ }
+
+ async fn request<R: crate::types::Request>(
+ &self,
+ arguments: R::Arguments,
+ ) -> Result<R::Result> {
+ let (callback_tx, mut callback_rx) = channel(1);
+
+ let arguments = Some(serde_json::to_value(arguments)?);
+
+ let req = Request {
+ back_ch: Some(callback_tx),
+ seq: self.next_request_id(),
+ command: R::COMMAND.to_string(),
+ arguments,
+ };
+
+ self.server_tx
+ .send(req)
+ .expect("Failed to send request to debugger");
+
+ let response = callback_rx.recv().await.unwrap()?;
+ let response = serde_json::from_value(response.body.unwrap_or_default())?;
+ Ok(response)
+ }
+
+ pub fn capabilities(&self) -> &DebuggerCapabilities {
+ self.caps.as_ref().expect("debugger not yet initialized!")
+ }
+
+ pub async fn initialize(&mut self, adapter_id: String) -> Result<()> {
+ let args = requests::InitializeArguments {
+ client_id: Some("hx".to_owned()),
+ client_name: Some("helix".to_owned()),
+ adapter_id,
+ locale: Some("en-us".to_owned()),
+ lines_start_at_one: Some(true),
+ columns_start_at_one: Some(true),
+ path_format: Some("path".to_owned()),
+ supports_variable_type: Some(true),
+ supports_variable_paging: Some(false),
+ supports_run_in_terminal_request: Some(false),
+ supports_memory_references: Some(false),
+ supports_progress_reporting: Some(false),
+ supports_invalidated_event: Some(false),
+ };
+
+ let response = self.request::<requests::Initialize>(args).await?;
+ self.caps = Some(response);
+
+ Ok(())
+ }
+
+ pub async fn disconnect(&mut self) -> Result<()> {
+ self.request::<requests::Disconnect>(()).await
+ }
+
+ pub async fn launch(&mut self, args: serde_json::Value) -> Result<()> {
+ let response = self.request::<requests::Launch>(args).await?;
+ log::error!("launch response {}", response);
+
+ Ok(())
+ }
+
+ pub async fn attach(&mut self, args: serde_json::Value) -> Result<()> {
+ let response = self.request::<requests::Attach>(args).await?;
+ log::error!("attach response {}", response);
+
+ Ok(())
+ }
+
+ pub async fn set_breakpoints(
+ &mut self,
+ file: PathBuf,
+ breakpoints: Vec<SourceBreakpoint>,
+ ) -> Result<Option<Vec<Breakpoint>>> {
+ let args = requests::SetBreakpointsArguments {
+ source: Source {
+ path: Some(file),
+ name: None,
+ source_reference: None,
+ presentation_hint: None,
+ origin: None,
+ sources: None,
+ adapter_data: None,
+ checksums: None,
+ },
+ breakpoints: Some(breakpoints),
+ source_modified: Some(false),
+ };
+
+ let response = self.request::<requests::SetBreakpoints>(args).await?;
+
+ Ok(response.breakpoints)
+ }
+
+ pub async fn configuration_done(&mut self) -> Result<()> {
+ self.request::<requests::ConfigurationDone>(()).await
+ }
+
+ pub async fn continue_thread(&mut self, thread_id: usize) -> Result<Option<bool>> {
+ let args = requests::ContinueArguments { thread_id };
+
+ let response = self.request::<requests::Continue>(args).await?;
+ Ok(response.all_threads_continued)
+ }
+
+ pub async fn stack_trace(
+ &mut self,
+ thread_id: usize,
+ ) -> Result<(Vec<StackFrame>, Option<usize>)> {
+ let args = requests::StackTraceArguments {
+ thread_id,
+ start_frame: None,
+ levels: None,
+ format: None,
+ };
+
+ let response = self.request::<requests::StackTrace>(args).await?;
+ Ok((response.stack_frames, response.total_frames))
+ }
+
+ pub async fn threads(&mut self) -> Result<Vec<Thread>> {
+ let response = self.request::<requests::Threads>(()).await?;
+ Ok(response.threads)
+ }
+
+ pub async fn scopes(&mut self, frame_id: usize) -> Result<Vec<Scope>> {
+ let args = requests::ScopesArguments { frame_id };
+
+ let response = self.request::<requests::Scopes>(args).await?;
+ Ok(response.scopes)
+ }
+
+ pub async fn variables(&mut self, variables_reference: usize) -> Result<Vec<Variable>> {
+ let args = requests::VariablesArguments {
+ variables_reference,
+ filter: None,
+ start: None,
+ count: None,
+ format: None,
+ };
+
+ let response = self.request::<requests::Variables>(args).await?;
+ Ok(response.variables)
+ }
+
+ pub async fn step_in(&mut self, thread_id: usize) -> Result<()> {
+ let args = requests::StepInArguments {
+ thread_id,
+ target_id: None,
+ granularity: None,
+ };
+
+ self.request::<requests::StepIn>(args).await
+ }
+
+ pub async fn step_out(&mut self, thread_id: usize) -> Result<()> {
+ let args = requests::StepOutArguments {
+ thread_id,
+ granularity: None,
+ };
+
+ self.request::<requests::StepOut>(args).await
+ }
+
+ pub async fn next(&mut self, thread_id: usize) -> Result<()> {
+ let args = requests::NextArguments {
+ thread_id,
+ granularity: None,
+ };
+
+ self.request::<requests::Next>(args).await
+ }
+
+ pub async fn pause(&mut self, thread_id: usize) -> Result<()> {
+ let args = requests::PauseArguments { thread_id };
+
+ self.request::<requests::Pause>(args).await
+ }
+
+ pub async fn eval(
+ &mut self,
+ expression: String,
+ frame_id: Option<usize>,
+ ) -> Result<requests::EvaluateResponse> {
+ let args = requests::EvaluateArguments {
+ expression,
+ frame_id,
+ context: None,
+ format: None,
+ };
+
+ self.request::<requests::Evaluate>(args).await
+ }
+}
diff --git a/helix-dap/src/lib.rs b/helix-dap/src/lib.rs
new file mode 100644
index 00000000..f60b102c
--- /dev/null
+++ b/helix-dap/src/lib.rs
@@ -0,0 +1,24 @@
+mod client;
+mod transport;
+mod types;
+
+pub use client::Client;
+pub use events::Event;
+pub use transport::{Payload, Response, Transport};
+pub use types::*;
+
+use thiserror::Error;
+#[derive(Error, Debug)]
+pub enum Error {
+ #[error("failed to parse: {0}")]
+ Parse(#[from] serde_json::Error),
+ #[error("IO Error: {0}")]
+ IO(#[from] std::io::Error),
+ #[error("request timed out")]
+ Timeout,
+ #[error("server closed the stream")]
+ StreamClosed,
+ #[error(transparent)]
+ Other(#[from] anyhow::Error),
+}
+pub type Result<T> = core::result::Result<T, Error>;
diff --git a/helix-dap/src/transport.rs b/helix-dap/src/transport.rs
new file mode 100644
index 00000000..afb7694d
--- /dev/null
+++ b/helix-dap/src/transport.rs
@@ -0,0 +1,246 @@
+use crate::{Error, Event, Result};
+use anyhow::Context;
+use log::{error, info, warn};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::collections::HashMap;
+use std::sync::Arc;
+use tokio::{
+ io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWrite, AsyncWriteExt},
+ sync::{
+ mpsc::{unbounded_channel, Sender, UnboundedReceiver, UnboundedSender},
+ Mutex,
+ },
+};
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct Request {
+ #[serde(skip)]
+ pub back_ch: Option<Sender<Result<Response>>>,
+ pub seq: u64,
+ pub command: String,
+ pub arguments: Option<Value>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+pub struct Response {
+ // seq is omitted as unused and is not sent by some implementations
+ pub request_seq: u64,
+ pub success: bool,
+ pub command: String,
+ pub message: Option<String>,
+ pub body: Option<Value>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(tag = "type", rename_all = "camelCase")]
+pub enum Payload {
+ // type = "event"
+ Event(Event),
+ // type = "response"
+ Response(Response),
+ // type = "request"
+ Request(Request),
+}
+
+#[derive(Debug)]
+pub struct Transport {
+ id: usize,
+ pending_requests: Mutex<HashMap<u64, Sender<Result<Response>>>>,
+}
+
+impl Transport {
+ pub fn start(
+ server_stdout: Box<dyn AsyncBufRead + Unpin + Send>,
+ server_stdin: Box<dyn AsyncWrite + Unpin + Send>,
+ id: usize,
+ ) -> (UnboundedReceiver<Payload>, UnboundedSender<Request>) {
+ let (client_tx, rx) = unbounded_channel();
+ let (tx, client_rx) = unbounded_channel();
+
+ let transport = Self {
+ id,
+ pending_requests: Mutex::new(HashMap::default()),
+ };
+
+ let transport = Arc::new(transport);
+
+ tokio::spawn(Self::recv(transport.clone(), server_stdout, client_tx));
+ tokio::spawn(Self::send(transport, server_stdin, client_rx));
+
+ (rx, tx)
+ }
+
+ async fn recv_server_message(
+ reader: &mut Box<dyn AsyncBufRead + Unpin + Send>,
+ buffer: &mut String,
+ ) -> Result<Payload> {
+ let mut content_length = None;
+ loop {
+ buffer.truncate(0);
+ reader.read_line(buffer).await?;
+ let header = buffer.trim();
+
+ if header.is_empty() {
+ break;
+ }
+
+ let mut parts = header.split(": ");
+
+ match (parts.next(), parts.next(), parts.next()) {
+ (Some("Content-Length"), Some(value), None) => {
+ content_length = Some(value.parse().context("invalid content length")?);
+ }
+ (Some(_), Some(_), None) => {}
+ _ => {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "Failed to parse header",
+ )
+ .into());
+ }
+ }
+ }
+
+ let content_length = content_length.context("missing content length")?;
+
+ //TODO: reuse vector
+ let mut content = vec![0; content_length];
+ reader.read_exact(&mut content).await?;
+ let msg = std::str::from_utf8(&content).context("invalid utf8 from server")?;
+
+ info!("<- DAP {}", msg);
+
+ // try parsing as output (server response) or call (server request)
+ let output: serde_json::Result<Payload> = serde_json::from_str(msg);
+
+ Ok(output?)
+ }
+
+ async fn send_payload_to_server(
+ &self,
+ server_stdin: &mut Box<dyn AsyncWrite + Unpin + Send>,
+ mut req: Request,
+ ) -> Result<()> {
+ let back_ch = req.back_ch.take();
+ let seq = req.seq;
+ let json = serde_json::to_string(&Payload::Request(req))?;
+ if let Some(back) = back_ch {
+ self.pending_requests.lock().await.insert(seq, back);
+ }
+ self.send_string_to_server(server_stdin, json).await
+ }
+
+ async fn send_string_to_server(
+ &self,
+ server_stdin: &mut Box<dyn AsyncWrite + Unpin + Send>,
+ request: String,
+ ) -> Result<()> {
+ info!("-> DAP {}", request);
+
+ // send the headers
+ server_stdin
+ .write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
+ .await?;
+
+ // send the body
+ server_stdin.write_all(request.as_bytes()).await?;
+
+ server_stdin.flush().await?;
+
+ Ok(())
+ }
+
+ fn process_response(res: Response) -> Result<Response> {
+ if res.success {
+ info!("<- DAP success in response to {}", res.request_seq);
+
+ Ok(res)
+ } else {
+ error!(
+ "<- DAP error {:?} ({:?}) for command #{} {}",
+ res.message, res.body, res.request_seq, res.command
+ );
+
+ Err(Error::Other(anyhow::format_err!("{:?}", res.body)))
+ }
+ }
+
+ async fn process_server_message(
+ &self,
+ client_tx: &UnboundedSender<Payload>,
+ msg: Payload,
+ ) -> Result<()> {
+ match msg {
+ Payload::Response(res) => {
+ let request_seq = res.request_seq;
+ let tx = self.pending_requests.lock().await.remove(&request_seq);
+
+ match tx {
+ Some(tx) => match tx.send(Self::process_response(res)).await {
+ Ok(_) => (),
+ Err(_) => error!(
+ "Tried sending response into a closed channel (id={:?}), original request likely timed out",
+ request_seq
+ ),
+ }
+ None => {
+ warn!("Response to nonexistent request #{}", res.request_seq);
+ client_tx.send(Payload::Response(res)).expect("Failed to send");
+ }
+ }
+
+ Ok(())
+ }
+ Payload::Request(Request {
+ ref command,
+ ref seq,
+ ..
+ }) => {
+ info!("<- DAP request {} #{}", command, seq);
+ client_tx.send(msg).expect("Failed to send");
+ Ok(())
+ }
+ Payload::Event(ref event) => {
+ info!("<- DAP event {:?}", event);
+ client_tx.send(msg).expect("Failed to send");
+ Ok(())
+ }
+ }
+ }
+
+ async fn recv(
+ transport: Arc<Self>,
+ mut server_stdout: Box<dyn AsyncBufRead + Unpin + Send>,
+ client_tx: UnboundedSender<Payload>,
+ ) {
+ let mut recv_buffer = String::new();
+ loop {
+ match Self::recv_server_message(&mut server_stdout, &mut recv_buffer).await {
+ Ok(msg) => {
+ transport
+ .process_server_message(&client_tx, msg)
+ .await
+ .unwrap();
+ }
+ Err(err) => {
+ error!("err: <- {:?}", err);
+ break;
+ }
+ }
+ }
+ }
+
+ async fn send(
+ transport: Arc<Self>,
+ mut server_stdin: Box<dyn AsyncWrite + Unpin + Send>,
+ mut client_rx: UnboundedReceiver<Request>,
+ ) {
+ while let Some(req) = client_rx.recv().await {
+ transport
+ .send_payload_to_server(&mut server_stdin, req)
+ .await
+ .unwrap()
+ }
+ }
+}
diff --git a/helix-dap/src/types.rs b/helix-dap/src/types.rs
new file mode 100644
index 00000000..c1781243
--- /dev/null
+++ b/helix-dap/src/types.rs
@@ -0,0 +1,652 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::path::PathBuf;
+
+pub trait Request {
+ type Arguments: serde::de::DeserializeOwned + serde::Serialize;
+ type Result: serde::de::DeserializeOwned + serde::Serialize;
+ const COMMAND: &'static str;
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ColumnDescriptor {
+ pub attribute_name: String,
+ pub label: String,
+ pub format: Option<String>,
+ #[serde(rename = "type")]
+ pub col_type: Option<String>,
+ pub width: Option<usize>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ExceptionBreakpointsFilter {
+ pub filter: String,
+ pub label: String,
+ pub description: Option<String>,
+ pub default: Option<bool>,
+ pub supports_condition: Option<bool>,
+ pub condition_description: Option<String>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DebuggerCapabilities {
+ pub supports_configuration_done_request: Option<bool>,
+ pub supports_function_breakpoints: Option<bool>,
+ pub supports_conditional_breakpoints: Option<bool>,
+ pub supports_hit_conditional_breakpoints: Option<bool>,
+ pub supports_evaluate_for_hovers: Option<bool>,
+ pub supports_step_back: Option<bool>,
+ pub supports_set_variable: Option<bool>,
+ pub supports_restart_frame: Option<bool>,
+ pub supports_goto_targets_request: Option<bool>,
+ pub supports_step_in_targets_request: Option<bool>,
+ pub supports_completions_request: Option<bool>,
+ pub supports_modules_request: Option<bool>,
+ pub supports_restart_request: Option<bool>,
+ pub supports_exception_options: Option<bool>,
+ pub supports_value_formatting_options: Option<bool>,
+ pub supports_exception_info_request: Option<bool>,
+ pub support_terminate_debuggee: Option<bool>,
+ pub support_suspend_debuggee: Option<bool>,
+ pub supports_delayed_stack_trace_loading: Option<bool>,
+ pub supports_loaded_sources_request: Option<bool>,
+ pub supports_log_points: Option<bool>,
+ pub supports_terminate_threads_request: Option<bool>,
+ pub supports_set_expression: Option<bool>,
+ pub supports_terminate_request: Option<bool>,
+ pub supports_data_breakpoints: Option<bool>,
+ pub supports_read_memory_request: Option<bool>,
+ pub supports_write_memory_request: Option<bool>,
+ pub supports_disassemble_request: Option<bool>,
+ pub supports_cancel_request: Option<bool>,
+ pub supports_breakpoint_locations_request: Option<bool>,
+ pub supports_clipboard_context: Option<bool>,
+ pub supports_stepping_granularity: Option<bool>,
+ pub supports_instruction_breakpoints: Option<bool>,
+ pub supports_exception_filter_options: Option<bool>,
+ pub exception_breakpoint_filters: Option<Vec<ExceptionBreakpointsFilter>>,
+ pub completion_trigger_characters: Option<Vec<String>>,
+ pub additional_module_columns: Option<Vec<ColumnDescriptor>>,
+ pub supported_checksum_algorithms: Option<Vec<String>>,
+}
+
+impl std::ops::Deref for DebuggerCapabilities {
+ type Target = Option<bool>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.supports_exception_options
+ }
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Checksum {
+ pub algorithm: String,
+ pub checksum: String,
+}
+
+#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Source {
+ pub name: Option<String>,
+ pub path: Option<PathBuf>,
+ pub source_reference: Option<usize>,
+ pub presentation_hint: Option<String>,
+ pub origin: Option<String>,
+ pub sources: Option<Vec<Source>>,
+ pub adapter_data: Option<Value>,
+ pub checksums: Option<Vec<Checksum>>,
+}
+
+#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SourceBreakpoint {
+ pub line: usize,
+ pub column: Option<usize>,
+ pub condition: Option<String>,
+ pub hit_condition: Option<String>,
+ pub log_message: Option<String>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Breakpoint {
+ pub id: Option<usize>,
+ pub verified: bool,
+ pub message: Option<String>,
+ pub source: Option<Source>,
+ pub line: Option<usize>,
+ pub column: Option<usize>,
+ pub end_line: Option<usize>,
+ pub end_column: Option<usize>,
+ pub instruction_reference: Option<String>,
+ pub offset: Option<usize>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StackFrameFormat {
+ pub parameters: Option<bool>,
+ pub parameter_types: Option<bool>,
+ pub parameter_names: Option<bool>,
+ pub parameter_values: Option<bool>,
+ pub line: Option<bool>,
+ pub module: Option<bool>,
+ pub include_all: Option<bool>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StackFrame {
+ pub id: usize,
+ pub name: String,
+ pub source: Option<Source>,
+ pub line: usize,
+ pub column: usize,
+ pub end_line: Option<usize>,
+ pub end_column: Option<usize>,
+ pub can_restart: Option<bool>,
+ pub instruction_pointer_reference: Option<String>,
+ pub module_id: Option<Value>,
+ pub presentation_hint: Option<String>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Thread {
+ pub id: usize,
+ pub name: String,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Scope {
+ pub name: String,
+ pub presentation_hint: Option<String>,
+ pub variables_reference: usize,
+ pub named_variables: Option<usize>,
+ pub indexed_variables: Option<usize>,
+ pub expensive: bool,
+ pub source: Option<Source>,
+ pub line: Option<usize>,
+ pub column: Option<usize>,
+ pub end_line: Option<usize>,
+ pub end_column: Option<usize>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ValueFormat {
+ pub hex: Option<bool>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VariablePresentationHint {
+ pub kind: Option<String>,
+ pub attributes: Option<Vec<String>>,
+ pub visibility: Option<String>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Variable {
+ pub name: String,
+ pub value: String,
+ #[serde(rename = "type")]
+ pub data_type: Option<String>,
+ pub presentation_hint: Option<VariablePresentationHint>,
+ pub evaluate_name: Option<String>,
+ pub variables_reference: usize,
+ pub named_variables: Option<usize>,
+ pub indexed_variables: Option<usize>,
+ pub memory_reference: Option<String>,
+}
+
+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Module {
+ pub id: String, // TODO: || number
+ pub name: String,
+ pub path: Option<PathBuf>,
+ pub is_optimized: Option<bool>,
+ pub is_user_code: Option<bool>,
+ pub version: Option<String>,
+ pub symbol_status: Option<String>,
+ pub symbol_file_path: Option<String>,
+ pub date_time_stamp: Option<String>,
+ pub address_range: Option<String>,
+}
+
+pub mod requests {
+ use super::*;
+ #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct InitializeArguments {
+ #[serde(rename = "clientID")]
+ pub client_id: Option<String>,
+ pub client_name: Option<String>,
+ #[serde(rename = "adapterID")]
+ pub adapter_id: String,
+ pub locale: Option<String>,
+ #[serde(rename = "linesStartAt1")]
+ pub lines_start_at_one: Option<bool>,
+ #[serde(rename = "columnsStartAt1")]
+ pub columns_start_at_one: Option<bool>,
+ pub path_format: Option<String>,
+ pub supports_variable_type: Option<bool>,
+ pub supports_variable_paging: Option<bool>,
+ pub supports_run_in_terminal_request: Option<bool>,
+ pub supports_memory_references: Option<bool>,
+ pub supports_progress_reporting: Option<bool>,
+ pub supports_invalidated_event: Option<bool>,
+ }
+
+ #[derive(Debug)]
+ pub enum Initialize {}
+
+ impl Request for Initialize {
+ type Arguments = InitializeArguments;
+ type Result = DebuggerCapabilities;
+ const COMMAND: &'static str = "initialize";
+ }
+
+ #[derive(Debug)]
+ pub enum Launch {}
+
+ impl Request for Launch {
+ type Arguments = Value;
+ type Result = Value;
+ const COMMAND: &'static str = "launch";
+ }
+
+ #[derive(Debug)]
+ pub enum Attach {}
+
+ impl Request for Attach {
+ type Arguments = Value;
+ type Result = Value;
+ const COMMAND: &'static str = "attach";
+ }
+
+ #[derive(Debug)]
+ pub enum Disconnect {}
+
+ impl Request for Disconnect {
+ type Arguments = ();
+ type Result = ();
+ const COMMAND: &'static str = "disconnect";
+ }
+
+ #[derive(Debug)]
+ pub enum ConfigurationDone {}
+
+ impl Request for ConfigurationDone {
+ type Arguments = ();
+ type Result = ();
+ const COMMAND: &'static str = "configurationDone";
+ }
+
+ #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct SetBreakpointsArguments {
+ pub source: Source,
+ pub breakpoints: Option<Vec<SourceBreakpoint>>,
+ // lines is deprecated
+ pub source_modified: Option<bool>,
+ }
+
+ #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct SetBreakpointsResponse {
+ pub breakpoints: Option<Vec<Breakpoint>>,
+ }
+
+ #[derive(Debug)]
+ pub enum SetBreakpoints {}
+
+ impl Request for SetBreakpoints {
+ type Arguments = SetBreakpointsArguments;
+ type Result = SetBreakpointsResponse;
+ const COMMAND: &'static str = "setBreakpoints";
+ }
+
+ #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct ContinueArguments {
+ pub thread_id: usize,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct ContinueResponse {
+ pub all_threads_continued: Option<bool>,
+ }
+
+ #[derive(Debug)]
+ pub enum Continue {}
+
+ impl Request for Continue {
+ type Arguments = ContinueArguments;
+ type Result = ContinueResponse;
+ const COMMAND: &'static str = "continue";
+ }
+
+ #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct StackTraceArguments {
+ pub thread_id: usize,
+ pub start_frame: Option<usize>,
+ pub levels: Option<usize>,
+ pub format: Option<StackFrameFormat>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct StackTraceResponse {
+ pub total_frames: Option<usize>,
+ pub stack_frames: Vec<StackFrame>,
+ }
+
+ #[derive(Debug)]
+ pub enum StackTrace {}
+
+ impl Request for StackTrace {
+ type Arguments = StackTraceArguments;
+ type Result = StackTraceResponse;
+ const COMMAND: &'static str = "stackTrace";
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct ThreadsResponse {
+ pub threads: Vec<Thread>,
+ }
+
+ #[derive(Debug)]
+ pub enum Threads {}
+
+ impl Request for Threads {
+ type Arguments = ();
+ type Result = ThreadsResponse;
+ const COMMAND: &'static str = "threads";
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct ScopesArguments {
+ pub frame_id: usize,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct ScopesResponse {
+ pub scopes: Vec<Scope>,
+ }
+
+ #[derive(Debug)]
+ pub enum Scopes {}
+
+ impl Request for Scopes {
+ type Arguments = ScopesArguments;
+ type Result = ScopesResponse;
+ const COMMAND: &'static str = "scopes";
+ }
+
+ #[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct VariablesArguments {
+ pub variables_reference: usize,
+ pub filter: Option<String>,
+ pub start: Option<usize>,
+ pub count: Option<usize>,
+ pub format: Option<ValueFormat>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct VariablesResponse {
+ pub variables: Vec<Variable>,
+ }
+
+ #[derive(Debug)]
+ pub enum Variables {}
+
+ impl Request for Variables {
+ type Arguments = VariablesArguments;
+ type Result = VariablesResponse;
+ const COMMAND: &'static str = "variables";
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct StepInArguments {
+ pub thread_id: usize,
+ pub target_id: Option<usize>,
+ pub granularity: Option<String>,
+ }
+
+ #[derive(Debug)]
+ pub enum StepIn {}
+
+ impl Request for StepIn {
+ type Arguments = StepInArguments;
+ type Result = ();
+ const COMMAND: &'static str = "stepIn";
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct StepOutArguments {
+ pub thread_id: usize,
+ pub granularity: Option<String>,
+ }
+
+ #[derive(Debug)]
+ pub enum StepOut {}
+
+ impl Request for StepOut {
+ type Arguments = StepOutArguments;
+ type Result = ();
+ const COMMAND: &'static str = "stepOut";
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct NextArguments {
+ pub thread_id: usize,
+ pub granularity: Option<String>,
+ }
+
+ #[derive(Debug)]
+ pub enum Next {}
+
+ impl Request for Next {
+ type Arguments = NextArguments;
+ type Result = ();
+ const COMMAND: &'static str = "next";
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct PauseArguments {
+ pub thread_id: usize,
+ }
+
+ #[derive(Debug)]
+ pub enum Pause {}
+
+ impl Request for Pause {
+ type Arguments = PauseArguments;
+ type Result = ();
+ const COMMAND: &'static str = "pause";
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct EvaluateArguments {
+ pub expression: String,
+ pub frame_id: Option<usize>,
+ pub context: Option<String>,
+ pub format: Option<ValueFormat>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct EvaluateResponse {
+ pub result: String,
+ #[serde(rename = "type")]
+ pub data_type: Option<String>,
+ pub presentation_hint: Option<VariablePresentationHint>,
+ pub variables_reference: usize,
+ pub named_variables: Option<usize>,
+ pub indexed_variables: Option<usize>,
+ pub memory_reference: Option<String>,
+ }
+
+ #[derive(Debug)]
+ pub enum Evaluate {}
+
+ impl Request for Evaluate {
+ type Arguments = EvaluateArguments;
+ type Result = EvaluateResponse;
+ const COMMAND: &'static str = "evaluate";
+ }
+}
+
+// Events
+
+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,
+ Stopped(Stopped),
+ Continued(Continued),
+ Exited(Exited),
+ Terminated(Option<Terminated>),
+ Thread(Thread),
+ Output(Output),
+ Breakpoint(Breakpoint),
+ Module(Module),
+ LoadedSource(LoadedSource),
+ Process(Process),
+ Capabilities(Capabilities),
+ // ProgressStart(),
+ // ProgressUpdate(),
+ // ProgressEnd(),
+ // Invalidated(),
+ Memory(Memory),
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Stopped {
+ pub reason: String,
+ pub description: Option<String>,
+ pub thread_id: Option<usize>,
+ pub preserve_focus_hint: Option<bool>,
+ pub text: Option<String>,
+ pub all_threads_stopped: Option<bool>,
+ pub hit_breakpoint_ids: Option<Vec<usize>>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Continued {
+ pub thread_id: usize,
+ pub all_threads_continued: Option<bool>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Exited {
+ pub exit_code: usize,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Terminated {
+ pub restart: Option<Value>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Thread {
+ pub reason: String,
+ pub thread_id: usize,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Output {
+ pub output: String,
+ pub category: Option<String>,
+ pub group: Option<String>,
+ pub line: Option<usize>,
+ pub column: Option<usize>,
+ pub variables_reference: Option<usize>,
+ pub source: Option<Source>,
+ pub data: Option<Value>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Breakpoint {
+ pub reason: String,
+ pub breakpoint: super::Breakpoint,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Module {
+ pub reason: String,
+ pub module: super::Module,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct LoadedSource {
+ pub reason: String,
+ pub source: super::Source,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Process {
+ pub name: String,
+ pub system_process_id: Option<usize>,
+ pub is_local_process: Option<bool>,
+ pub start_method: Option<String>, // TODO: use enum
+ pub pointer_size: Option<usize>,
+ }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Capabilities {
+ pub capabilities: super::DebuggerCapabilities,
+ }
+
+ // #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ // #[serde(rename_all = "camelCase")]
+ // pub struct Invalidated {
+ // pub areas: Vec<InvalidatedArea>,
+ // pub thread_id: Option<usize>,
+ // pub stack_frame_id: Option<usize>,
+ // }
+
+ #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct Memory {
+ pub memory_reference: String,
+ pub offset: usize,
+ pub count: usize,
+ }
+}
diff --git a/helix-lsp/Cargo.toml b/helix-lsp/Cargo.toml
index 52e995f5..8aecba74 100644
--- a/helix-lsp/Cargo.toml
+++ b/helix-lsp/Cargo.toml
@@ -23,5 +23,5 @@ lsp-types = { version = "0.89", features = ["proposed"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "1.0"
-tokio = { version = "1.10", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot"] }
-tokio-stream = "0.1.7"
+tokio = { version = "1.10", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] }
+tokio-stream = "0.1"
diff --git a/helix-term/Cargo.toml b/helix-term/Cargo.toml
index 57d592cc..6e9c0daf 100644
--- a/helix-term/Cargo.toml
+++ b/helix-term/Cargo.toml
@@ -24,6 +24,7 @@ path = "src/main.rs"
helix-core = { version = "0.4", path = "../helix-core" }
helix-view = { version = "0.4", path = "../helix-view" }
helix-lsp = { version = "0.4", path = "../helix-lsp" }
+helix-dap = { version = "0.4", path = "../helix-dap" }
anyhow = "1"
once_cell = "1.8"
@@ -33,7 +34,7 @@ num_cpus = "1"
tui = { path = "../helix-tui", package = "helix-tui", default-features = false, features = ["crossterm"] }
crossterm = { version = "0.21", features = ["event-stream"] }
signal-hook = "0.3"
-
+tokio-stream = "0.1"
futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false }
# Logging
diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs
index 1fcca681..e64389ed 100644
--- a/helix-term/src/application.rs
+++ b/helix-term/src/application.rs
@@ -1,11 +1,11 @@
use helix_core::{merge_toml_values, syntax};
+use helix_dap::Payload;
use helix_lsp::{lsp, util::lsp_pos_to_pos, LspProgressMap};
use helix_view::{theme, Editor};
use crate::{args::Args, compositor::Compositor, config::Config, job::Jobs, ui};
use log::error;
-
use std::{
io::{stdout, Write},
sync::Arc,
@@ -191,6 +191,9 @@ impl Application {
last_render = Instant::now();
}
}
+ Some(payload) = self.editor.debugger_events.next() => {
+ self.handle_debugger_message(payload).await;
+ }
Some(callback) = self.jobs.futures.next() => {
self.jobs.handle_callback(&mut self.editor, &mut self.compositor, callback);
self.render();
@@ -252,6 +255,97 @@ impl Application {
}
}
+ pub async fn handle_debugger_message(&mut self, payload: helix_dap::Payload) {
+ use crate::commands::dap::select_thread_id;
+ use helix_dap::{events, Event};
+ let mut debugger = match self.editor.debugger.as_mut() {
+ Some(debugger) => debugger,
+ None => return,
+ };
+
+ match payload {
+ Payload::Event(ev) => match ev {
+ Event::Stopped(events::Stopped {
+ thread_id,
+ description,
+ text,
+ reason,
+ all_threads_stopped,
+ ..
+ }) => {
+ debugger.is_running = false;
+
+ // whichever thread stops is made "current" (if no previously selected thread).
+ if thread_id.is_none() || all_threads_stopped.unwrap_or_default() {
+ let main = debugger.threads().await.ok().and_then(|threads| {
+ // Workaround for debugging Go tests. Main thread has * in beginning of its name
+ let mut main =
+ threads.iter().find(|t| t.name.starts_with('*')).cloned();
+ if main.is_none() {
+ main = threads.get(0).cloned();
+ }
+ main.map(|t| t.id)
+ });
+ if let Some(id) = main {
+ select_thread_id(&mut self.editor, id, true).await;
+ }
+ } else {
+ select_thread_id(&mut self.editor, thread_id.unwrap(), true).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 {
+ status.push_str(&format!(" {}", desc));
+ }
+ if let Some(text) = text {
+ status.push_str(&format!(" {}", text));
+ }
+ if all_threads_stopped.unwrap_or_default() {
+ status.push_str(" (all threads stopped)");
+ }
+
+ self.editor.set_status(status);
+ }
+ Event::Output(events::Output {
+ category, output, ..
+ }) => {
+ let prefix = match category {
+ Some(category) => {
+ if &category == "telemetry" {
+ return;
+ }
+ format!("Debug ({}):", category)
+ }
+ None => "Debug:".to_owned(),
+ };
+
+ self.editor.set_status(format!("{} {}", prefix, output));
+ }
+ Event::Initialized => {
+ self.editor
+ .set_status("Debugged application started".to_owned());
+ }
+ Event::Continued(_) => {
+ debugger.is_running = true;
+ debugger.active_frame = None;
+ debugger.thread_id = None;
+ }
+ ev => {
+ log::warn!("Unhandled event {:?}", ev);
+ return; // return early to skip render
+ }
+ },
+ Payload::Response(_) => unreachable!(),
+ Payload::Request(_) => todo!(),
+ }
+ self.render();
+ }
+
pub async fn handle_language_server_message(
&mut self,
call: helix_lsp::Call,
diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index 116f39bd..7b2fd295 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -1,3 +1,7 @@
+pub(crate) mod dap;
+
+pub use dap::*;
+
use helix_core::{
comment, coords_at_pos, find_first_non_whitespace_char, find_root, graphemes, indent,
indent::IndentStyle,
@@ -33,7 +37,7 @@ use crate::{
use crate::job::{self, Job, Jobs};
use futures_util::FutureExt;
use std::num::NonZeroUsize;
-use std::{fmt, future::Future};
+use std::{collections::HashMap, fmt, future::Future};
use std::{
borrow::Cow,
@@ -97,13 +101,13 @@ impl<'a> Context<'a> {
}
}
-enum Align {
+pub enum Align {
Top,
Center,
Bottom,
}
-fn align_view(doc: &Document, view: &mut View, align: Align) {
+pub fn align_view(doc: &Document, view: &mut View, align: Align) {
let pos = doc
.selection(view.id)
.primary()
@@ -304,6 +308,17 @@ impl Command {
surround_delete, "Surround delete",
select_textobject_around, "Select around object",
select_textobject_inner, "Select inside object",
+ dap_launch, "Launch debug target",
+ dap_toggle_breakpoint, "Toggle breakpoint",
+ dap_run, "Begin program execution",
+ dap_continue, "Continue program execution",
+ dap_pause, "Pause program execution",
+ dap_step_in, "Step in",
+ dap_step_out, "Step out",
+ dap_next, "Step to next",
+ dap_variables, "List variables",
+ dap_terminate, "End debug session",
+ dap_switch_thread, "Switch current thread",
shell_pipe, "Pipe selections through shell command",
shell_pipe_to, "Pipe selections into shell command, ignoring command output",
shell_insert_output, "Insert output of shell command before each selection",
@@ -1339,7 +1354,6 @@ fn append_mode(cx: &mut Context) {
mod cmd {
use super::*;
- use std::collections::HashMap;
use helix_view::editor::Action;
use ui::completers::{self, Completer};
@@ -1941,6 +1955,152 @@ mod cmd {
Ok(())
}
+ fn debug_eval(
+ cx: &mut compositor::Context,
+ args: &[&str],
+ _event: PromptEvent,
+ ) -> anyhow::Result<()> {
+ use helix_lsp::block_on;
+ if let Some(debugger) = cx.editor.debugger.as_mut() {
+ let (frame, thread_id) = match (debugger.active_frame, debugger.thread_id) {
+ (Some(frame), Some(thread_id)) => (frame, thread_id),
+ _ => {
+ bail!("Cannot find current stack frame to access variables")
+ }
+ };
+
+ // TODO: support no frame_id
+
+ let frame_id = debugger.stack_frames[&thread_id][frame].id;
+ let response = block_on(debugger.eval(args.join(" "), Some(frame_id)))?;
+ cx.editor.set_status(response.result);
+ }
+ Ok(())
+ }
+
+ fn edit_breakpoint_impl(
+ cx: &mut compositor::Context,
+ condition: Option<String>,
+ log_message: Option<String>,
+ ) -> anyhow::Result<()> {
+ use helix_lsp::block_on;
+
+ let (view, doc) = current!(cx.editor);
+ let text = doc.text().slice(..);
+ let pos = doc.selection(view.id).primary().cursor(text);
+ let breakpoint = helix_dap::SourceBreakpoint {
+ line: text.char_to_line(pos) + 1, // convert from 0-indexing to 1-indexing (TODO: could set debugger to 0-indexing on init)
+ condition,
+ log_message,
+ ..Default::default()
+ };
+ let path = match doc.path() {
+ Some(path) => path.to_path_buf(),
+ None => {
+ bail!("Can't edit breakpoint: document has no path")
+ }
+ };
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if breakpoint.condition.is_some()
+ && !debugger
+ .caps
+ .as_ref()
+ .unwrap()
+ .supports_conditional_breakpoints
+ .unwrap_or_default()
+ {
+ bail!("Can't edit breakpoint: debugger does not support conditional breakpoints")
+ }
+ if breakpoint.log_message.is_some()
+ && !debugger
+ .caps
+ .as_ref()
+ .unwrap()
+ .supports_log_points
+ .unwrap_or_default()
+ {
+ bail!("Can't edit breakpoint: debugger does not support logpoints")
+ }
+
+ let breakpoints = debugger.breakpoints.entry(path.clone()).or_default();
+ if let Some(pos) = breakpoints.iter().position(|b| b.line == breakpoint.line) {
+ breakpoints.remove(pos);
+ breakpoints.push(breakpoint);
+
+ let breakpoints = breakpoints.clone();
+
+ let request = debugger.set_breakpoints(path, breakpoints);
+ if let Err(e) = block_on(request) {
+ bail!("Failed to set breakpoints: {:?}", e)
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn debug_start(
+ cx: &mut compositor::Context,
+ args: &[&str],
+ _event: PromptEvent,
+ ) -> anyhow::Result<()> {
+ let mut args = args.to_owned();
+ let name = match args.len() {
+ 0 => None,
+ _ => Some(args.remove(0)),
+ };
+ dap_start_impl(&mut cx.editor, name, None, Some(args));
+ Ok(())
+ }
+
+ fn debug_remote(
+ cx: &mut compositor::Context,
+ args: &[&str],
+ _event: PromptEvent,
+ ) -> anyhow::Result<()> {
+ let mut args = args.to_owned();
+ let address = match args.len() {
+ 0 => None,
+ _ => Some(args.remove(0).parse()?),
+ };
+ let name = match args.len() {
+ 0 => None,
+ _ => Some(args.remove(0)),
+ };
+ dap_start_impl(&mut cx.editor, name, address, Some(args));
+
+ Ok(())
+ }
+
+ fn debug_breakpoint_condition(
+ cx: &mut compositor::Context,
+ args: &[&str],
+ _event: PromptEvent,
+ ) -> anyhow::Result<()> {
+ let condition = args.join(" ");
+ let condition = if condition.is_empty() {
+ None
+ } else {
+ Some(condition)
+ };
+
+ edit_breakpoint_impl(cx, condition, None)
+ }
+
+ fn debug_set_logpoint(
+ cx: &mut compositor::Context,
+ args: &[&str],
+ _event: PromptEvent,
+ ) -> anyhow::Result<()> {
+ let log_message = args.join(" ");
+ let log_message = if log_message.is_empty() {
+ None
+ } else {
+ Some(log_message)
+ };
+
+ edit_breakpoint_impl(cx, None, log_message)
+ }
+
pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
TypableCommand {
name: "quit",
@@ -2181,6 +2341,41 @@ mod cmd {
completer: None,
},
TypableCommand {
+ name: "debug-start",
+ alias: Some("dbg"),
+ doc: "Start a debug session from a given template with given parameters.",
+ fun: debug_start,
+ completer: Some(completers::filename),
+ },
+ TypableCommand {
+ name: "debug-remote",
+ alias: Some("dbg-tcp"),
+ doc: "Connect to a debug adapter by TCP address and start a debugging session from a given template with given parameters.",
+ fun: debug_remote,
+ completer: Some(completers::filename),
+ },
+ TypableCommand {
+ name: "debug-eval",
+ alias: None,
+ doc: "Evaluate expression in current debug context.",
+ fun: debug_eval,
+ completer: None,
+ },
+ TypableCommand {
+ name: "debug-breakpoint-condition",
+ alias: None,
+ doc: "Set current breakpoint condition.",
+ fun: debug_breakpoint_condition,
+ completer: None,
+ },
+ TypableCommand {
+ name: "debug-set-logpoint",
+ alias: None,
+ doc: "Make current breakpoint a log point.",
+ fun: debug_set_logpoint,
+ completer: None,
+ },
+ TypableCommand {
name: "vsplit",
alias: Some("vs"),
doc: "Open the file in a vertical split.",
diff --git a/helix-term/src/commands/dap.rs b/helix-term/src/commands/dap.rs
new file mode 100644
index 00000000..a1558dde
--- /dev/null
+++ b/helix-term/src/commands/dap.rs
@@ -0,0 +1,445 @@
+use super::{align_view, Align, Context, Editor};
+use crate::ui::Picker;
+use helix_core::Selection;
+use helix_dap::Client;
+use helix_lsp::block_on;
+
+use serde_json::{to_value, Value};
+use tokio_stream::wrappers::UnboundedReceiverStream;
+
+use std::collections::HashMap;
+
+// general utils:
+pub fn dap_pos_to_pos(doc: &helix_core::Rope, line: usize, column: usize) -> Option<usize> {
+ // 1-indexing to 0 indexing
+ let line = doc.try_line_to_char(line - 1).ok()?;
+ let pos = line + column;
+ // TODO: this is probably utf-16 offsets
+ Some(pos)
+}
+
+pub async fn select_thread_id(editor: &mut Editor, thread_id: usize, force: bool) {
+ let debugger = match &mut editor.debugger {
+ Some(debugger) => debugger,
+ None => return,
+ };
+
+ if !force && debugger.thread_id.is_some() {
+ return;
+ }
+
+ debugger.thread_id = Some(thread_id);
+
+ // fetch stack trace
+ // TODO: handle requesting more total frames
+ let (frames, _) = debugger.stack_trace(thread_id).await.unwrap();
+ debugger.stack_frames.insert(thread_id, frames);
+ debugger.active_frame = Some(0); // TODO: check how to determine this
+
+ let frame = debugger.stack_frames[&thread_id].get(0).cloned();
+ if let Some(frame) = &frame {
+ jump_to_stack_frame(editor, frame);
+ }
+}
+
+pub fn jump_to_stack_frame(editor: &mut Editor, frame: &helix_dap::StackFrame) {
+ let path = if let Some(helix_dap::Source {
+ path: Some(ref path),
+ ..
+ }) = frame.source
+ {
+ path.clone()
+ } else {
+ return;
+ };
+
+ editor
+ .open(path, helix_view::editor::Action::Replace)
+ .unwrap(); // TODO: there should be no unwrapping!
+
+ let (view, doc) = current!(editor);
+
+ let text_end = doc.text().len_chars().saturating_sub(1);
+ let start = dap_pos_to_pos(doc.text(), frame.line, frame.column).unwrap_or(0);
+ let end = frame
+ .end_line
+ .and_then(|end_line| dap_pos_to_pos(doc.text(), end_line, frame.end_column.unwrap_or(0)))
+ .unwrap_or(start);
+
+ let selection = Selection::single(start.min(text_end), end.min(text_end));
+ doc.set_selection(view.id, selection);
+ align_view(doc, view, Align::Center);
+}
+
+// DAP
+pub fn dap_start_impl(
+ editor: &mut Editor,
+ name: Option<&str>,
+ socket: Option<std::net::SocketAddr>,
+ params: Option<Vec<&str>>,
+) {
+ let (_, doc) = current!(editor);
+
+ let path = match doc.path() {
+ Some(path) => path.to_path_buf(),
+ None => {
+ editor.set_error("Can't start debug: document has no path".to_string());
+ return;
+ }
+ };
+
+ let config = editor
+ .syn_loader
+ .language_config_for_file_name(&path)
+ .and_then(|x| x.debugger.clone());
+ let config = match config {
+ Some(c) => c,
+ None => {
+ editor.set_error(
+ "Can't start debug: no debug adapter available for language".to_string(),
+ );
+ return;
+ }
+ };
+
+ let result = match socket {
+ Some(socket) => block_on(Client::tcp(socket, 0)),
+ None => block_on(Client::process(
+ config.transport.clone(),
+ config.command.clone(),
+ config.args.clone(),
+ config.port_arg.clone(),
+ 0,
+ )),
+ };
+
+ let (mut debugger, events) = match result {
+ Ok(r) => r,
+ Err(e) => {
+ editor.set_error(format!("Failed to start debug session: {:?}", e));
+ return;
+ }
+ };
+
+ let request = debugger.initialize(config.name.clone());
+ if let Err(e) = block_on(request) {
+ editor.set_error(format!("Failed to initialize debug adapter: {:?}", e));
+ return;
+ }
+
+ let start_config = match name {
+ Some(name) => config.templates.iter().find(|t| t.name == name),
+ None => config.templates.get(0),
+ };
+ let start_config = match start_config {
+ Some(c) => c,
+ None => {
+ editor.set_error("Can't start debug: no debug config with given name".to_string());
+ return;
+ }
+ };
+
+ let template = start_config.args.clone();
+ let mut args: HashMap<String, Value> = HashMap::new();
+
+ if let Some(params) = params {
+ for (k, t) in template {
+ let mut value = t;
+ for (i, x) in params.iter().enumerate() {
+ // For param #0 replace {0} in args
+ value = value.replace(format!("{{{}}}", i).as_str(), x);
+ }
+
+ if let Ok(integer) = value.parse::<usize>() {
+ args.insert(k, Value::Number(serde_json::Number::from(integer)));
+ } else {
+ args.insert(k, Value::String(value));
+ }
+ }
+ }
+
+ let args = to_value(args).unwrap();
+
+ let result = match &start_config.request[..] {
+ "launch" => block_on(debugger.launch(args)),
+ "attach" => block_on(debugger.attach(args)),
+ _ => {
+ editor.set_error("Unsupported request".to_string());
+ return;
+ }
+ };
+ if let Err(e) = result {
+ editor.set_error(format!("Failed {} target: {:?}", start_config.request, e));
+ return;
+ }
+
+ // TODO: either await "initialized" or buffer commands until event is received
+ editor.debugger = Some(debugger);
+ let stream = UnboundedReceiverStream::new(events);
+ editor.debugger_events.push(stream);
+}
+
+pub fn dap_launch(cx: &mut Context) {
+ if cx.editor.debugger.is_some() {
+ cx.editor
+ .set_error("Can't start debug: debugger is running".to_string());
+ return;
+ }
+
+ let (_, doc) = current!(cx.editor);
+ let path = match doc.path() {
+ Some(path) => path.to_path_buf(),
+ None => {
+ cx.editor
+ .set_error("Can't start debug: document has no path".to_string());
+ return;
+ }
+ };
+
+ let config = cx
+ .editor
+ .syn_loader
+ .language_config_for_file_name(&path)
+ .and_then(|x| x.debugger.clone());
+ let config = match config {
+ Some(c) => c,
+ None => {
+ cx.editor.set_error(
+ "Can't start debug: no debug adapter available for language".to_string(),
+ );
+ return;
+ }
+ };
+
+ cx.editor.debug_config_picker = Some(config.templates.iter().map(|t| t.name.clone()).collect());
+ cx.editor.debug_config_completions = Some(
+ config
+ .templates
+ .iter()
+ .map(|t| t.completion.clone())
+ .collect(),
+ );
+}
+
+pub fn dap_toggle_breakpoint(cx: &mut Context) {
+ let (view, doc) = current!(cx.editor);
+ let text = doc.text().slice(..);
+ let pos = doc.selection(view.id).primary().cursor(text);
+
+ let breakpoint = helix_dap::SourceBreakpoint {
+ line: text.char_to_line(pos) + 1, // convert from 0-indexing to 1-indexing (TODO: could set debugger to 0-indexing on init)
+ ..Default::default()
+ };
+
+ let path = match doc.path() {
+ Some(path) => path.to_path_buf(),
+ None => {
+ cx.editor
+ .set_error("Can't set breakpoint: document has no path".to_string());
+ return;
+ }
+ };
+
+ // TODO: need to map breakpoints over edits and update them?
+ // we shouldn't really allow editing while debug is running though
+
+ if let Some(debugger) = &mut cx.editor.debugger {
+ let breakpoints = debugger.breakpoints.entry(path.clone()).or_default();
+ if let Some(pos) = breakpoints.iter().position(|b| b.line == breakpoint.line) {
+ breakpoints.remove(pos);
+ } else {
+ breakpoints.push(breakpoint);
+ }
+
+ let breakpoints = breakpoints.clone();
+
+ let request = debugger.set_breakpoints(path, breakpoints);
+ if let Err(e) = block_on(request) {
+ cx.editor
+ .set_error(format!("Failed to set breakpoints: {:?}", e));
+ }
+ }
+}
+
+pub fn dap_run(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if debugger.is_running {
+ cx.editor
+ .set_status("Debuggee is already running".to_owned());
+ return;
+ }
+ let request = debugger.configuration_done();
+ if let Err(e) = block_on(request) {
+ cx.editor.set_error(format!("Failed to run: {:?}", e));
+ return;
+ }
+ debugger.is_running = true;
+ }
+}
+
+pub fn dap_continue(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if debugger.is_running {
+ cx.editor
+ .set_status("Debuggee is already running".to_owned());
+ return;
+ }
+
+ if let Some(thread_id) = debugger.thread_id {
+ let request = debugger.continue_thread(debugger.thread_id.unwrap());
+ if let Err(e) = block_on(request) {
+ cx.editor.set_error(format!("Failed to continue: {:?}", e));
+ return;
+ }
+ debugger.is_running = true;
+ debugger.stack_frames.remove(&thread_id);
+ } else {
+ cx.editor
+ .set_error("Currently active thread is not stopped. Switch the thread.".into());
+ }
+ }
+}
+
+pub fn dap_pause(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if !debugger.is_running {
+ cx.editor.set_status("Debuggee is not running".to_owned());
+ return;
+ }
+
+ // FIXME: correct number here
+ let request = debugger.pause(0);
+ if let Err(e) = block_on(request) {
+ cx.editor.set_error(format!("Failed to pause: {:?}", e));
+ }
+ }
+}
+
+pub fn dap_step_in(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if debugger.is_running {
+ cx.editor
+ .set_status("Debuggee is already running".to_owned());
+ return;
+ }
+
+ let request = debugger.step_in(debugger.thread_id.unwrap());
+ if let Err(e) = block_on(request) {
+ cx.editor.set_error(format!("Failed to step: {:?}", e));
+ }
+ }
+}
+
+pub fn dap_step_out(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if debugger.is_running {
+ cx.editor
+ .set_status("Debuggee is already running".to_owned());
+ return;
+ }
+
+ let request = debugger.step_out(debugger.thread_id.unwrap());
+ if let Err(e) = block_on(request) {
+ cx.editor.set_error(format!("Failed to step: {:?}", e));
+ }
+ }
+}
+
+pub fn dap_next(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if debugger.is_running {
+ cx.editor
+ .set_status("Debuggee is already running".to_owned());
+ return;
+ }
+
+ let request = debugger.next(debugger.thread_id.unwrap());
+ if let Err(e) = block_on(request) {
+ cx.editor.set_error(format!("Failed to step: {:?}", e));
+ }
+ }
+}
+
+pub fn dap_variables(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ if debugger.is_running {
+ cx.editor
+ .set_status("Cannot access variables while target is running".to_owned());
+ return;
+ }
+ let (frame, thread_id) = match (debugger.active_frame, debugger.thread_id) {
+ (Some(frame), Some(thread_id)) => (frame, thread_id),
+ _ => {
+ cx.editor
+ .set_status("Cannot find current stack frame to access variables".to_owned());
+ return;
+ }
+ };
+
+ let frame_id = debugger.stack_frames[&thread_id][frame].id;
+ let scopes = match block_on(debugger.scopes(frame_id)) {
+ Ok(s) => s,
+ Err(e) => {
+ cx.editor
+ .set_error(format!("Failed to get scopes: {:?}", e));
+ return;
+ }
+ };
+ let mut variables = Vec::new();
+
+ for scope in scopes.iter() {
+ let response = block_on(debugger.variables(scope.variables_reference));
+
+ if let Ok(vars) = response {
+ for var in vars {
+ let prefix = match var.data_type {
+ Some(data_type) => format!("{} ", data_type),
+ None => "".to_owned(),
+ };
+ variables.push(format!("{}{} = {}\n", prefix, var.name, var.value));
+ }
+ }
+ }
+
+ if !variables.is_empty() {
+ cx.editor.variables = Some(variables);
+ cx.editor.variables_page = 0;
+ }
+ }
+}
+
+pub fn dap_terminate(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ let request = debugger.disconnect();
+ if let Err(e) = block_on(request) {
+ cx.editor
+ .set_error(format!("Failed to disconnect: {:?}", e));
+ return;
+ }
+ cx.editor.debugger = None;
+ }
+}
+
+pub fn dap_switch_thread(cx: &mut Context) {
+ if let Some(debugger) = &mut cx.editor.debugger {
+ let request = debugger.threads();
+ let threads = match block_on(request) {
+ Ok(threads) => threads,
+ Err(e) => {
+ cx.editor
+ .set_error(format!("Failed to retrieve threads: {:?}", e));
+ return;
+ }
+ };
+
+ let picker = Picker::new(
+ true,
+ threads,
+ |thread| thread.name.clone().into(),
+ |editor, thread, _action| {
+ block_on(select_thread_id(editor, thread.id, true));
+ },
+ );
+ cx.push_layer(Box::new(picker))
+ }
+}
diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs
index 71ac01a9..1b04b5cd 100644
--- a/helix-term/src/keymap.rs
+++ b/helix-term/src/keymap.rs
@@ -487,6 +487,23 @@ impl Default for Keymaps {
"s" => symbol_picker,
"a" => code_action,
"'" => last_picker,
+ "d" => { "Debug"
+ "l" => dap_launch,
+ "b" => dap_toggle_breakpoint,
+ "r" => dap_run,
+ "c" => dap_continue,
+ "h" => dap_pause,
+ "i" => dap_step_in,
+ "o" => dap_step_out,
+ "n" => dap_next,
+ "v" => dap_variables,
+ "t" => dap_terminate,
+ "s" => { "Switch"
+ "t" => dap_switch_thread,
+ // f = stack frame
+ // sl, sb
+ },
+ },
"w" => { "Window"
"C-w" | "w" => rotate_view,
"C-h" | "h" => hsplit,
diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs
index 4b9c56e7..17a2df3d 100644
--- a/helix-term/src/ui/editor.rs
+++ b/helix-term/src/ui/editor.rs
@@ -1,6 +1,7 @@
use crate::{
commands,
- compositor::{Component, Context, EventResult},
+ compositor::{Component, Compositor, Context, EventResult},
+ job::Callback,
key,
keymap::{KeymapResult, Keymaps},
ui::{Completion, ProgressSpinners},
@@ -10,11 +11,12 @@ use helix_core::{
coords_at_pos,
graphemes::{ensure_grapheme_boundary_next, next_grapheme_boundary, prev_grapheme_boundary},
movement::Direction,
- syntax::{self, HighlightEvent},
+ syntax::{self, DebugConfigCompletion, HighlightEvent},
unicode::segmentation::UnicodeSegmentation,
unicode::width::UnicodeWidthStr,
LineEnding, Position, Range, Selection,
};
+use helix_dap::{SourceBreakpoint, StackFrame};
use helix_view::{
document::Mode,
editor::LineNumber,
@@ -29,6 +31,8 @@ use std::borrow::Cow;
use crossterm::event::{Event, MouseButton, MouseEvent, MouseEventKind};
use tui::buffer::Buffer as Surface;
+use super::{Prompt, PromptEvent};
+
pub struct EditorView {
keymaps: Keymaps,
on_next_key: Option<Box<dyn FnOnce(&mut commands::Context, KeyEvent)>>,
@@ -71,6 +75,7 @@ impl EditorView {
is_focused: bool,
loader: &syntax::Loader,
config: &helix_view::editor::Config,
+ debugger: &Option<helix_dap::Client>,
) {
let inner = view.inner_area();
let area = view.area;
@@ -87,7 +92,9 @@ impl EditorView {
};
Self::render_text_highlights(doc, view.offset, inner, surface, theme, highlights);
- Self::render_gutter(doc, view, view.area, surface, theme, is_focused, config);
+ Self::render_gutter(
+ doc, view, view.area, surface, theme, is_focused, config, debugger,
+ );
if is_focused {
Self::render_focused_view_elements(view, doc, inner, theme, surface);
@@ -106,7 +113,7 @@ impl EditorView {
}
}
- self.render_diagnostics(doc, view, inner, surface, theme);
+ self.render_diagnostics(doc, view, inner, surface, theme, debugger);
let statusline_area = view
.area
@@ -409,6 +416,7 @@ impl EditorView {
theme: &Theme,
is_focused: bool,
config: &helix_view::editor::Config,
+ debugger: &Option<helix_dap::Client>,
) {
let text = doc.text().slice(..);
let last_line = view.last_line(doc);
@@ -438,6 +446,32 @@ impl EditorView {
.map(|range| range.cursor_line(text))
.collect();
+ let mut breakpoints: Option<&Vec<SourceBreakpoint>> = None;
+ let mut stack_frame: Option<&StackFrame> = None;
+ if let Some(debugger) = debugger {
+ if let Some(path) = doc.path() {
+ breakpoints = debugger.breakpoints.get(path);
+
+ // if we have a frame, and the frame path matches document
+ if let (Some(frame), Some(thread_id)) = (debugger.active_frame, debugger.thread_id)
+ {
+ let frame = debugger
+ .stack_frames
+ .get(&thread_id)
+ .and_then(|bt| bt.get(frame)); // TODO: drop the clone..
+ if let Some(StackFrame {
+ source: Some(source),
+ ..
+ }) = &frame
+ {
+ if source.path.as_ref() == Some(path) {
+ stack_frame = frame;
+ }
+ };
+ };
+ }
+ }
+
for (i, line) in (view.offset.row..(last_line + 1)).enumerate() {
use helix_core::diagnostic::Severity;
if let Some(diagnostic) = doc.diagnostics().iter().find(|d| d.line == line) {
@@ -457,6 +491,30 @@ impl EditorView {
let selected = cursors.contains(&line);
+ if let Some(bps) = breakpoints.as_ref() {
+ if let Some(breakpoint) = bps.iter().find(|breakpoint| breakpoint.line - 1 == line)
+ {
+ let style = if breakpoint.condition.is_some() {
+ error
+ } else if breakpoint.log_message.is_some() {
+ info
+ } else {
+ warning
+ };
+ surface.set_stringn(viewport.x, viewport.y + i as u16, "▲", 1, style);
+ }
+ }
+
+ if let Some(frame) = stack_frame {
+ if frame.line - 1 == line {
+ surface.set_style(
+ Rect::new(viewport.x, viewport.y + i as u16, 6, 1),
+ helix_view::graphics::Style::default()
+ .bg(helix_view::graphics::Color::LightYellow),
+ );
+ }
+ }
+
let text = if line == last_line && !draw_last {
" ~".into()
} else {
@@ -493,6 +551,7 @@ impl EditorView {
viewport: Rect,
surface: &mut Surface,
theme: &Theme,
+ debugger: &Option<helix_dap::Client>,
) {
use helix_core::diagnostic::Severity;
use tui::{
@@ -530,6 +589,31 @@ impl EditorView {
lines.extend(text.lines);
}
+ if let Some(debugger) = debugger {
+ if let Some(path) = doc.path() {
+ if let Some(breakpoints) = debugger.breakpoints.get(path) {
+ let line = doc.text().char_to_line(cursor);
+ if let Some(breakpoint) = breakpoints
+ .iter()
+ .find(|breakpoint| breakpoint.line - 1 == line)
+ {
+ if let Some(condition) = &breakpoint.condition {
+ lines.extend(
+ Text::styled(condition, info.add_modifier(Modifier::UNDERLINED))
+ .lines,
+ );
+ }
+ if let Some(log_message) = &breakpoint.log_message {
+ lines.extend(
+ Text::styled(log_message, info.add_modifier(Modifier::UNDERLINED))
+ .lines,
+ );
+ }
+ }
+ }
+ }
+ }
+
let paragraph = Paragraph::new(lines).alignment(Alignment::Right);
let width = 80.min(viewport.width);
let height = 15.min(viewport.height);
@@ -636,6 +720,78 @@ impl EditorView {
);
}
+ fn debug_parameter_prompt(
+ completions: Vec<DebugConfigCompletion>,
+ config_name: String,
+ mut params: Vec<String>,
+ ) -> Prompt {
+ let i = params.len();
+ let completion = completions.get(i).unwrap();
+ let field_type = if let DebugConfigCompletion::Advanced(cfg) = completion {
+ cfg.completion.clone().unwrap_or_else(|| "".to_owned())
+ } else {
+ "".to_owned()
+ };
+ let name = match completion {
+ DebugConfigCompletion::Advanced(cfg) => {
+ cfg.name.clone().unwrap_or_else(|| field_type.to_owned())
+ }
+ DebugConfigCompletion::Named(name) => name.clone(),
+ };
+ let default_val = match completion {
+ DebugConfigCompletion::Advanced(cfg) => {
+ cfg.default.clone().unwrap_or_else(|| "".to_owned())
+ }
+ _ => "".to_owned(),
+ };
+
+ let noop = |_input: &str| Vec::new();
+ let completer = match &field_type[..] {
+ "filename" => super::completers::filename,
+ "directory" => super::completers::directory,
+ _ => noop,
+ };
+ Prompt::new(
+ format!("{}: ", name).into(),
+ None,
+ completer,
+ move |cx: &mut crate::compositor::Context, input: &str, event: PromptEvent| {
+ if event != PromptEvent::Validate {
+ return;
+ }
+
+ let mut value = input.to_owned();
+ if value.is_empty() {
+ value = default_val.clone();
+ }
+ params.push(value);
+
+ if params.len() < completions.len() {
+ let completions = completions.clone();
+ let config_name = config_name.clone();
+ let params = params.clone();
+ let callback = Box::pin(async move {
+ let call: Callback =
+ Box::new(move |_editor: &mut Editor, compositor: &mut Compositor| {
+ let prompt =
+ Self::debug_parameter_prompt(completions, config_name, params);
+ compositor.push(Box::new(prompt));
+ });
+ Ok(call)
+ });
+ cx.jobs.callback(callback);
+ } else {
+ commands::dap_start_impl(
+ cx.editor,
+ Some(&config_name),
+ None,
+ Some(params.iter().map(|x| x.as_str()).collect()),
+ );
+ }
+ },
+ )
+ }
+
/// Handle events by looking them up in `self.keymaps`. Returns None
/// if event was handled (a command was executed or a subkeymap was
/// activated). Only KeymapResult::{NotFound, Cancelled} is returned
@@ -647,6 +803,57 @@ impl EditorView {
event: KeyEvent,
) -> Option<KeymapResult> {
self.autoinfo = None;
+
+ if let Some(picker) = cxt.editor.debug_config_picker.clone() {
+ match event {
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {}
+ KeyEvent {
+ code: KeyCode::Char(char),
+ ..
+ } => {
+ let (i, name) = match picker.iter().position(|t| t.starts_with(char)) {
+ Some(pos) => (pos, picker.get(pos).unwrap().clone()),
+ None => return None,
+ };
+ let completions = cxt.editor.debug_config_completions.clone().unwrap();
+ let completion = completions.get(i).unwrap().clone();
+ if !completion.is_empty() {
+ let prompt = Self::debug_parameter_prompt(completion, name, Vec::new());
+ cxt.push_layer(Box::new(prompt));
+ }
+ }
+ _ => return None,
+ }
+ cxt.editor.debug_config_picker = None;
+ return None;
+ }
+
+ if cxt.editor.variables.is_some() {
+ match event {
+ KeyEvent {
+ code: KeyCode::Char('h'),
+ ..
+ } => {
+ cxt.editor.variables_page = cxt.editor.variables_page.saturating_sub(1);
+ }
+ KeyEvent {
+ code: KeyCode::Char('l'),
+ ..
+ } => {
+ cxt.editor.variables_page = cxt.editor.variables_page.saturating_add(1);
+ }
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {
+ cxt.editor.variables = None;
+ }
+ _ => {}
+ }
+ return None;
+ }
+
match self.keymaps.get_mut(&mode).unwrap().get(event) {
KeymapResult::Matched(command) => command.execute(cxt),
KeymapResult::Pending(node) => self.autoinfo = Some(node.into()),
@@ -1016,9 +1223,59 @@ impl Component for EditorView {
is_focused,
loader,
&cx.editor.config,
+ &cx.editor.debugger,
);
}
+ if let Some(ref vars) = cx.editor.variables {
+ let mut text = String::new();
+ let mut height = 0;
+ let mut max_len = 20;
+
+ let per_page = 15;
+ let num_vars = vars.len();
+ let start = (per_page * cx.editor.variables_page).min(num_vars);
+ let end = (start + per_page).min(num_vars);
+ for line in vars[start..end].to_vec() {
+ max_len = max_len.max(line.len() as u16);
+ height += 1;
+ text.push_str(&line);
+ }
+
+ if vars.len() > per_page {
+ text += "\nMove h, l";
+ height += 1;
+ }
+
+ let mut info = Info {
+ height: 20.min(height + 2),
+ width: 70.min(max_len),
+ title: format!("{} variables", num_vars),
+ text: text + "\nExit Esc",
+ };
+ info.render(area, surface, cx);
+ }
+
+ if let Some(ref configs) = cx.editor.debug_config_picker {
+ let mut text = String::new();
+ let mut height = 0;
+ let mut max_len = 20;
+
+ for line in configs {
+ max_len = max_len.max(line.len() as u16 + 2);
+ height += 1;
+ text.push_str(&format!("{} {}\n", line.chars().next().unwrap(), line));
+ }
+
+ let mut info = Info {
+ height: 20.min(height + 1),
+ width: 70.min(max_len),
+ title: "Debug targets".to_owned(),
+ text: text + "Exit Esc",
+ };
+ info.render(area, surface, cx);
+ }
+
if let Some(ref mut info) = self.autoinfo {
info.render(area, surface, cx);
}
diff --git a/helix-view/Cargo.toml b/helix-view/Cargo.toml
index c0a39700..1f55a36b 100644
--- a/helix-view/Cargo.toml
+++ b/helix-view/Cargo.toml
@@ -18,6 +18,7 @@ bitflags = "1.3"
anyhow = "1"
helix-core = { version = "0.4", path = "../helix-core" }
helix-lsp = { version = "0.4", path = "../helix-lsp"}
+helix-dap = { version = "0.4", path = "../helix-dap"}
crossterm = { version = "0.21", optional = true }
# Conversion traits
@@ -25,6 +26,7 @@ once_cell = "1.8"
url = "2"
tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot"] }
+tokio-stream = "0.1"
futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false }
slotmap = "1"
diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs
index e5ff93ad..f87ae318 100644
--- a/helix-view/src/editor.rs
+++ b/helix-view/src/editor.rs
@@ -7,6 +7,9 @@ use crate::{
};
use futures_util::future;
+use futures_util::stream::select_all::SelectAll;
+use tokio_stream::wrappers::UnboundedReceiverStream;
+
use std::{
path::{Path, PathBuf},
sync::Arc,
@@ -19,7 +22,7 @@ use anyhow::Error;
pub use helix_core::diagnostic::Severity;
pub use helix_core::register::Registers;
-use helix_core::syntax;
+use helix_core::syntax::{self, DebugConfigCompletion};
use helix_core::Position;
use serde::Deserialize;
@@ -77,6 +80,14 @@ pub struct Editor {
pub registers: Registers,
pub theme: Theme,
pub language_servers: helix_lsp::Registry,
+
+ pub debugger: Option<helix_dap::Client>,
+ pub debugger_events: SelectAll<UnboundedReceiverStream<helix_dap::Payload>>,
+ pub debug_config_picker: Option<Vec<String>>,
+ pub debug_config_completions: Option<Vec<Vec<DebugConfigCompletion>>>,
+ pub variables: Option<Vec<String>>,
+ pub variables_page: usize,
+
pub clipboard_provider: Box<dyn ClipboardProvider>,
pub syn_loader: Arc<syntax::Loader>,
@@ -114,6 +125,12 @@ impl Editor {
selected_register: RegisterSelection::default(),
theme: themes.default(),
language_servers,
+ debugger: None,
+ debugger_events: SelectAll::new(),
+ debug_config_picker: None,
+ debug_config_completions: None,
+ variables: None,
+ variables_page: 0,
syn_loader: config_loader,
theme_loader: themes,
registers: Registers::default(),
diff --git a/languages.toml b/languages.toml
index c04435fe..1a557943 100644
--- a/languages.toml
+++ b/languages.toml
@@ -20,6 +20,25 @@ config = """
language-server = { command = "rust-analyzer" }
indent = { tab-width = 4, unit = " " }
+[language.debugger]
+name = "lldb-vscode"
+transport = "tcp"
+command = "lldb-vscode"
+args = []
+port-arg = "-p {}"
+
+[[language.debugger.templates]]
+name = "binary"
+request = "launch"
+completion = [ { name = "binary", completion = "filename" } ]
+args = { console = "internalConsole", program = "{0}" }
+
+[[language.debugger.templates]]
+name = "attach"
+request = "attach"
+completion = [ "pid" ]
+args = { console = "internalConsole", pid = "{0}" }
+
[[language]]
name = "toml"
scope = "source.toml"
@@ -70,6 +89,25 @@ comment-token = "//"
language-server = { command = "clangd" }
indent = { tab-width = 2, unit = " " }
+[language.debugger]
+name = "lldb-vscode"
+transport = "tcp"
+command = "lldb-vscode"
+args = []
+port-arg = "-p {}"
+
+[[language.debugger.templates]]
+name = "binary"
+request = "launch"
+completion = [ { name = "binary", completion = "filename" } ]
+args = { console = "internalConsole", program = "{0}" }
+
+[[language.debugger.templates]]
+name = "attach"
+request = "attach"
+completion = [ "pid" ]
+args = { console = "internalConsole", pid = "{0}" }
+
[[language]]
name = "cpp"
scope = "source.cpp"
@@ -81,6 +119,25 @@ comment-token = "//"
language-server = { command = "clangd" }
indent = { tab-width = 2, unit = " " }
+[language.debugger]
+name = "lldb-vscode"
+transport = "tcp"
+command = "lldb-vscode"
+args = []
+port-arg = "-p {}"
+
+[[language.debugger.templates]]
+name = "binary"
+request = "launch"
+completion = [ { name = "binary", completion = "filename" } ]
+args = { console = "internalConsole", program = "{0}" }
+
+[[language.debugger.templates]]
+name = "attach"
+request = "attach"
+completion = [ "pid" ]
+args = { console = "internalConsole", pid = "{0}" }
+
[[language]]
name = "go"
scope = "source.go"
@@ -94,6 +151,37 @@ language-server = { command = "gopls" }
# TODO: gopls needs utf-8 offsets?
indent = { tab-width = 4, unit = "\t" }
+[language.debugger]
+name = "go"
+transport = "tcp"
+command = "dlv"
+args = ["dap"]
+port-arg = "-l 127.0.0.1:{}"
+
+[[language.debugger.templates]]
+name = "source"
+request = "launch"
+completion = [ { name = "entrypoint", completion = "filename", default = "." } ]
+args = { mode = "debug", program = "{0}" }
+
+[[language.debugger.templates]]
+name = "binary"
+request = "launch"
+completion = [ { name = "binary", completion = "filename" } ]
+args = { mode = "exec", program = "{0}" }
+
+[[language.debugger.templates]]
+name = "test"
+request = "launch"
+completion = [ { name = "tests", completion = "directory", default = "." } ]
+args = { mode = "test", program = "{0}" }
+
+[[language.debugger.templates]]
+name = "attach"
+request = "attach"
+completion = [ "pid" ]
+args = { mode = "local", processId = "{0}" }
+
[[language]]
name = "javascript"
scope = "source.js"