on master help sign in
dap: Significantly simplify code using the Request trait
commit184abdc51061bd1636f31edcb51d71d0362a3d83 authorBlaž Hrastnik <blaz@mxxn.io> dateMon 16 Aug 2021, 13:59 (5 years ago) parent3a9e1c3
4 files changed+82−62
helix-dap/examples/dap-dlv.rs+3−3 helix-dap/examples/dap-lldb.rs+3−3 helix-dap/src/client.rs+31−56 helix-dap/src/types.rs+45
helix-dap/examples/dap-dlv.rs+3−3
@@ -1,4 +1,4 @@
1−use helix_dap::{Client, Event, OutputEventBody, Result, SourceBreakpoint, StoppedEventBody};
1+use helix_dap::{events, Client, Event, Result, SourceBreakpoint};
22use serde::{Deserialize, Serialize};
33use serde_json::from_value;
44use tokio::sync::mpsc::Receiver;
@@ -12,7 +12,7 @@ struct LaunchArguments {
1212
1313async fn output(mut output_event: Receiver<Event>) {
1414 loop {
15− let body: OutputEventBody =
15+ let body: events::Output =
1616 from_value(output_event.recv().await.unwrap().body.unwrap()).unwrap();
1717 println!(
1818 "> [{}] {}",
@@ -77,7 +77,7 @@ pub async fn main() -> Result<()> {
7777
7878 println!("configurationDone: {:?}", client.configuration_done().await);
7979
80− let stop: StoppedEventBody =
80+ let stop: events::Stopped =
8181 from_value(stopped_event.recv().await.unwrap().body.unwrap()).unwrap();
8282 println!("stopped: {:?}", stop);
8383
helix-dap/examples/dap-lldb.rs+3−3
@@ -1,4 +1,4 @@
1−use helix_dap::{Client, Event, OutputEventBody, Result, SourceBreakpoint, StoppedEventBody};
1+use helix_dap::{events, Client, Event, Result, SourceBreakpoint};
22use serde::{Deserialize, Serialize};
33use serde_json::from_value;
44use tokio::sync::mpsc::Receiver;
@@ -12,7 +12,7 @@ struct LaunchArguments {
1212
1313async fn output(mut output_event: Receiver<Event>) {
1414 loop {
15− let body: OutputEventBody =
15+ let body: events::Output =
1616 from_value(output_event.recv().await.unwrap().body.unwrap()).unwrap();
1717 println!(
1818 "> [{}] {}",
@@ -77,7 +77,7 @@ pub async fn main() -> Result<()> {
7777
7878 println!("configurationDone: {:?}", client.configuration_done().await);
7979
80− let stop: StoppedEventBody =
80+ let stop: events::Stopped =
8181 from_value(stopped_event.recv().await.unwrap().body.unwrap()).unwrap();
8282 println!("stopped: {:?}", stop);
8383
helix-dap/src/client.rs+31−56
@@ -1,11 +1,9 @@
11use crate::{
2− transport::{Event, Payload, Request, Response, Transport},
2+ transport::{Event, Payload, Request, Transport},
33 types::*,
44 Result,
55};
66pub use log::{error, info};
7−use serde::Serialize;
8−use serde_json::{from_value, to_value, Value};
97use std::{
108 collections::HashMap,
119 net::{IpAddr, Ipv4Addr},
@@ -184,13 +182,18 @@ impl Client {
184182 self.request_counter.fetch_add(1, Ordering::Relaxed)
185183 }
186184
187− async fn request(&self, command: String, arguments: Option<Value>) -> Result<Response> {
185+ async fn request<R: crate::types::Request>(
186+ &self,
187+ arguments: R::Arguments,
188+ ) -> Result<R::Result> {
188189 let (callback_rx, mut callback_tx) = channel(1);
189190
191+ let arguments = Some(serde_json::to_value(arguments)?);
192+
190193 let req = Request {
191194 back_ch: Some(callback_rx),
192195 seq: self.next_request_id(),
193− command,
196+ command: R::COMMAND.to_string(),
194197 arguments,
195198 };
196199
@@ -198,7 +201,9 @@ impl Client {
198201 .send(req)
199202 .expect("Failed to send request to debugger");
200203
201− Ok(callback_tx.recv().await.unwrap()?)
204+ let response = callback_tx.recv().await.unwrap()?;
205+ let response = serde_json::from_value(response.body.unwrap_or_default())?;
206+ Ok(response)
202207 }
203208
204209 pub fn capabilities(&self) -> &DebuggerCapabilities {
@@ -224,33 +229,30 @@ impl Client {
224229 supports_invalidated_event: Some(false),
225230 };
226231
227− let response = self
228− .request("initialize".to_owned(), to_value(args).ok())
229− .await?;
230− self.capabilities = from_value(response.body.unwrap()).ok();
232+ let response = self.request::<requests::Initialize>(args).await?;
233+ self.capabilities = Some(response);
231234
232235 Ok(())
233236 }
234237
235238 pub async fn disconnect(&mut self) -> Result<()> {
236− self.request("disconnect".to_owned(), None).await?;
237− Ok(())
239+ self.request::<requests::Disconnect>(()).await
238240 }
239241
240− pub async fn launch(&mut self, args: impl Serialize) -> Result<()> {
242+ pub async fn launch(&mut self, args: serde_json::Value) -> Result<()> {
241243 let mut initialized = self.listen_for_event("initialized".to_owned()).await;
242244
243− let res = self.request("launch".to_owned(), to_value(args).ok());
245+ let res = self.request::<requests::Launch>(args);
244246 let ev = initialized.recv();
245247 join!(res, ev).0?;
246248
247249 Ok(())
248250 }
249251
250− pub async fn attach(&mut self, args: impl Serialize) -> Result<()> {
252+ pub async fn attach(&mut self, args: serde_json::Value) -> Result<()> {
251253 let mut initialized = self.listen_for_event("initialized".to_owned()).await;
252254
253− let res = self.request("attach".to_owned(), to_value(args).ok());
255+ let res = self.request::<requests::Attach>(args);
254256 let ev = initialized.recv();
255257 join!(res, ev).0?;
256258
@@ -277,29 +279,20 @@ impl Client {
277279 source_modified: Some(false),
278280 };
279281
280− let response = self
281− .request("setBreakpoints".to_owned(), to_value(args).ok())
282− .await?;
283− let body: Option<requests::SetBreakpointsResponse> = from_value(response.body.unwrap()).ok();
282+ let response = self.request::<requests::SetBreakpoints>(args).await?;
284283
285− Ok(body.map(|b| b.breakpoints).unwrap())
284+ Ok(response.breakpoints)
286285 }
287286
288287 pub async fn configuration_done(&mut self) -> Result<()> {
289− self.request("configurationDone".to_owned(), None).await?;
290− Ok(())
288+ self.request::<requests::ConfigurationDone>(()).await
291289 }
292290
293291 pub async fn continue_thread(&mut self, thread_id: usize) -> Result<Option<bool>> {
294292 let args = requests::ContinueArguments { thread_id };
295293
296− let response = self
297− .request("continue".to_owned(), to_value(args).ok())
298− .await?;
299−
300− let body: Option<requests::ContinueResponse> = from_value(response.body.unwrap()).ok();
301−
302− Ok(body.map(|b| b.all_threads_continued).unwrap())
294+ let response = self.request::<requests::Continue>(args).await?;
295+ Ok(response.all_threads_continued)
303296 }
304297
305298 pub async fn stack_trace(
@@ -313,33 +306,20 @@ impl Client {
313306 format: None,
314307 };
315308
316− let response = self
317− .request("stackTrace".to_owned(), to_value(args).ok())
318− .await?;
319−
320− let body: requests::StackTraceResponse = from_value(response.body.unwrap()).unwrap();
321−
322− Ok((body.stack_frames, body.total_frames))
309+ let response = self.request::<requests::StackTrace>(args).await?;
310+ Ok((response.stack_frames, response.total_frames))
323311 }
324312
325313 pub async fn threads(&mut self) -> Result<Vec<Thread>> {
326− let response = self.request("threads".to_owned(), None).await?;
327−
328− let body: requests::ThreadsResponse = from_value(response.body.unwrap()).unwrap();
329−
330− Ok(body.threads)
314+ let response = self.request::<requests::Threads>(()).await?;
315+ Ok(response.threads)
331316 }
332317
333318 pub async fn scopes(&mut self, frame_id: usize) -> Result<Vec<Scope>> {
334319 let args = requests::ScopesArguments { frame_id };
335320
336− let response = self
337− .request("scopes".to_owned(), to_value(args).ok())
338− .await?;
339−
340− let body: requests::ScopesResponse = from_value(response.body.unwrap()).unwrap();
341−
342− Ok(body.scopes)
321+ let response = self.request::<requests::Scopes>(args).await?;
322+ Ok(response.scopes)
343323 }
344324
345325 pub async fn variables(&mut self, variables_reference: usize) -> Result<Vec<Variable>> {
@@ -351,12 +331,7 @@ impl Client {
351331 format: None,
352332 };
353333
354− let response = self
355− .request("variables".to_owned(), to_value(args).ok())
356− .await?;
357−
358− let body: requests::VariablesResponse = from_value(response.body.unwrap()).unwrap();
359−
360− Ok(body.variables)
334+ let response = self.request::<requests::Variables>(args).await?;
335+ Ok(response.variables)
361336 }
362337}
helix-dap/src/types.rs+45
@@ -229,6 +229,51 @@ pub mod requests {
229229 pub supports_invalidated_event: Option<bool>,
230230 }
231231
232+ #[derive(Debug)]
233+ pub enum Initialize {}
234+
235+ impl Request for Initialize {
236+ type Arguments = InitializeArguments;
237+ type Result = DebuggerCapabilities;
238+ const COMMAND: &'static str = "initialize";
239+ }
240+
241+ #[derive(Debug)]
242+ pub enum Launch {}
243+
244+ impl Request for Launch {
245+ type Arguments = Value;
246+ type Result = Value;
247+ const COMMAND: &'static str = "launch";
248+ }
249+
250+ #[derive(Debug)]
251+ pub enum Attach {}
252+
253+ impl Request for Attach {
254+ type Arguments = Value;
255+ type Result = Value;
256+ const COMMAND: &'static str = "attach";
257+ }
258+
259+ #[derive(Debug)]
260+ pub enum Disconnect {}
261+
262+ impl Request for Disconnect {
263+ type Arguments = ();
264+ type Result = ();
265+ const COMMAND: &'static str = "disconnect";
266+ }
267+
268+ #[derive(Debug)]
269+ pub enum ConfigurationDone {}
270+
271+ impl Request for ConfigurationDone {
272+ type Arguments = ();
273+ type Result = ();
274+ const COMMAND: &'static str = "configurationDone";
275+ }
276+
232277 #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
233278 #[serde(rename_all = "camelCase")]
234279 pub struct SetBreakpointsArguments {