1use super::breakpoint_store::{
2 BreakpointStore, BreakpointStoreEvent, BreakpointUpdatedReason, SourceBreakpoint,
3};
4use super::dap_command::{
5 self, Attach, ConfigurationDone, ContinueCommand, DapCommand, DisconnectCommand,
6 EvaluateCommand, Initialize, Launch, LoadedSourcesCommand, LocalDapCommand, LocationsCommand,
7 ModulesCommand, NextCommand, PauseCommand, RestartCommand, RestartStackFrameCommand,
8 ScopesCommand, SetExceptionBreakpoints, SetVariableValueCommand, StackTraceCommand,
9 StepBackCommand, StepCommand, StepInCommand, StepOutCommand, TerminateCommand,
10 TerminateThreadsCommand, ThreadsCommand, VariablesCommand,
11};
12use super::dap_store::DapStore;
13use anyhow::{Context as _, Result, anyhow};
14use collections::{HashMap, HashSet, IndexMap, IndexSet};
15use dap::adapters::{DebugAdapterBinary, DebugAdapterName};
16use dap::messages::Response;
17use dap::requests::{Request, RunInTerminal, StartDebugging};
18use dap::{
19 Capabilities, ContinueArguments, EvaluateArgumentsContext, Module, Source, StackFrameId,
20 SteppingGranularity, StoppedEvent, VariableReference,
21 client::{DebugAdapterClient, SessionId},
22 messages::{Events, Message},
23};
24use dap::{
25 ExceptionBreakpointsFilter, ExceptionFilterOptions, OutputEventCategory,
26 RunInTerminalRequestArguments, StartDebuggingRequestArguments,
27};
28use futures::channel::{mpsc, oneshot};
29use futures::{FutureExt, future::Shared};
30use gpui::{
31 App, AppContext, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, SharedString,
32 Task, WeakEntity,
33};
34
35use serde_json::Value;
36use smol::stream::StreamExt;
37use std::any::TypeId;
38use std::collections::BTreeMap;
39use std::u64;
40use std::{
41 any::Any,
42 collections::hash_map::Entry,
43 hash::{Hash, Hasher},
44 path::Path,
45 sync::Arc,
46};
47use text::{PointUtf16, ToPointUtf16};
48use util::ResultExt;
49use worktree::Worktree;
50
51#[derive(Debug, Copy, Clone, Hash, PartialEq, PartialOrd, Ord, Eq)]
52#[repr(transparent)]
53pub struct ThreadId(pub u64);
54
55impl ThreadId {
56 pub const MIN: ThreadId = ThreadId(u64::MIN);
57 pub const MAX: ThreadId = ThreadId(u64::MAX);
58}
59
60impl From<u64> for ThreadId {
61 fn from(id: u64) -> Self {
62 Self(id)
63 }
64}
65
66#[derive(Clone, Debug)]
67pub struct StackFrame {
68 pub dap: dap::StackFrame,
69 pub scopes: Vec<dap::Scope>,
70}
71
72impl From<dap::StackFrame> for StackFrame {
73 fn from(stack_frame: dap::StackFrame) -> Self {
74 Self {
75 scopes: vec![],
76 dap: stack_frame,
77 }
78 }
79}
80
81#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
82pub enum ThreadStatus {
83 #[default]
84 Running,
85 Stopped,
86 Stepping,
87 Exited,
88 Ended,
89}
90
91impl ThreadStatus {
92 pub fn label(&self) -> &'static str {
93 match self {
94 ThreadStatus::Running => "Running",
95 ThreadStatus::Stopped => "Stopped",
96 ThreadStatus::Stepping => "Stepping",
97 ThreadStatus::Exited => "Exited",
98 ThreadStatus::Ended => "Ended",
99 }
100 }
101}
102
103#[derive(Debug)]
104pub struct Thread {
105 dap: dap::Thread,
106 stack_frame_ids: IndexSet<StackFrameId>,
107 _has_stopped: bool,
108}
109
110impl From<dap::Thread> for Thread {
111 fn from(dap: dap::Thread) -> Self {
112 Self {
113 dap,
114 stack_frame_ids: Default::default(),
115 _has_stopped: false,
116 }
117 }
118}
119
120pub enum Mode {
121 Building,
122 Running(LocalMode),
123}
124
125#[derive(Clone)]
126pub struct LocalMode {
127 client: Arc<DebugAdapterClient>,
128 binary: DebugAdapterBinary,
129 tmp_breakpoint: Option<SourceBreakpoint>,
130 worktree: WeakEntity<Worktree>,
131 executor: BackgroundExecutor,
132}
133
134fn client_source(abs_path: &Path) -> dap::Source {
135 dap::Source {
136 name: abs_path
137 .file_name()
138 .map(|filename| filename.to_string_lossy().to_string()),
139 path: Some(abs_path.to_string_lossy().to_string()),
140 source_reference: None,
141 presentation_hint: None,
142 origin: None,
143 sources: None,
144 adapter_data: None,
145 checksums: None,
146 }
147}
148
149impl LocalMode {
150 async fn new(
151 session_id: SessionId,
152 parent_session: Option<Entity<Session>>,
153 worktree: WeakEntity<Worktree>,
154 binary: DebugAdapterBinary,
155 messages_tx: futures::channel::mpsc::UnboundedSender<Message>,
156 cx: AsyncApp,
157 ) -> Result<Self> {
158 let message_handler = Box::new(move |message| {
159 messages_tx.unbounded_send(message).ok();
160 });
161
162 let client = Arc::new(
163 if let Some(client) = parent_session
164 .and_then(|session| cx.update(|cx| session.read(cx).adapter_client()).ok())
165 .flatten()
166 {
167 client
168 .reconnect(session_id, binary.clone(), message_handler, cx.clone())
169 .await?
170 } else {
171 DebugAdapterClient::start(session_id, binary.clone(), message_handler, cx.clone())
172 .await
173 .with_context(|| "Failed to start communication with debug adapter")?
174 },
175 );
176
177 Ok(Self {
178 client,
179 worktree,
180 tmp_breakpoint: None,
181 binary,
182 executor: cx.background_executor().clone(),
183 })
184 }
185
186 pub(crate) fn worktree(&self) -> &WeakEntity<Worktree> {
187 &self.worktree
188 }
189
190 fn unset_breakpoints_from_paths(&self, paths: &Vec<Arc<Path>>, cx: &mut App) -> Task<()> {
191 let tasks: Vec<_> = paths
192 .into_iter()
193 .map(|path| {
194 self.request(dap_command::SetBreakpoints {
195 source: client_source(path),
196 source_modified: None,
197 breakpoints: vec![],
198 })
199 })
200 .collect();
201
202 cx.background_spawn(async move {
203 futures::future::join_all(tasks)
204 .await
205 .iter()
206 .for_each(|res| match res {
207 Ok(_) => {}
208 Err(err) => {
209 log::warn!("Set breakpoints request failed: {}", err);
210 }
211 });
212 })
213 }
214
215 fn send_breakpoints_from_path(
216 &self,
217 abs_path: Arc<Path>,
218 reason: BreakpointUpdatedReason,
219 breakpoint_store: &Entity<BreakpointStore>,
220 cx: &mut App,
221 ) -> Task<()> {
222 let breakpoints = breakpoint_store
223 .read_with(cx, |store, cx| store.breakpoints_from_path(&abs_path, cx))
224 .into_iter()
225 .filter(|bp| bp.state.is_enabled())
226 .chain(self.tmp_breakpoint.clone())
227 .map(Into::into)
228 .collect();
229
230 let task = self.request(dap_command::SetBreakpoints {
231 source: client_source(&abs_path),
232 source_modified: Some(matches!(reason, BreakpointUpdatedReason::FileSaved)),
233 breakpoints,
234 });
235
236 cx.background_spawn(async move {
237 match task.await {
238 Ok(_) => {}
239 Err(err) => log::warn!("Set breakpoints request failed for path: {}", err),
240 }
241 })
242 }
243
244 fn send_exception_breakpoints(
245 &self,
246 filters: Vec<ExceptionBreakpointsFilter>,
247 supports_filter_options: bool,
248 ) -> Task<Result<Vec<dap::Breakpoint>>> {
249 let arg = if supports_filter_options {
250 SetExceptionBreakpoints::WithOptions {
251 filters: filters
252 .into_iter()
253 .map(|filter| ExceptionFilterOptions {
254 filter_id: filter.filter,
255 condition: None,
256 mode: None,
257 })
258 .collect(),
259 }
260 } else {
261 SetExceptionBreakpoints::Plain {
262 filters: filters.into_iter().map(|filter| filter.filter).collect(),
263 }
264 };
265 self.request(arg)
266 }
267
268 fn send_source_breakpoints(
269 &self,
270 ignore_breakpoints: bool,
271 breakpoint_store: &Entity<BreakpointStore>,
272 cx: &App,
273 ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
274 let mut breakpoint_tasks = Vec::new();
275 let breakpoints = breakpoint_store.read_with(cx, |store, cx| store.all_breakpoints(cx));
276
277 for (path, breakpoints) in breakpoints {
278 let breakpoints = if ignore_breakpoints {
279 vec![]
280 } else {
281 breakpoints
282 .into_iter()
283 .filter(|bp| bp.state.is_enabled())
284 .map(Into::into)
285 .collect()
286 };
287
288 breakpoint_tasks.push(
289 self.request(dap_command::SetBreakpoints {
290 source: client_source(&path),
291 source_modified: Some(false),
292 breakpoints,
293 })
294 .map(|result| result.map_err(|e| (path, e))),
295 );
296 }
297
298 cx.background_spawn(async move {
299 futures::future::join_all(breakpoint_tasks)
300 .await
301 .into_iter()
302 .filter_map(Result::err)
303 .collect::<HashMap<_, _>>()
304 })
305 }
306
307 fn initialize_sequence(
308 &self,
309 capabilities: &Capabilities,
310 initialized_rx: oneshot::Receiver<()>,
311 dap_store: WeakEntity<DapStore>,
312 cx: &App,
313 ) -> Task<Result<()>> {
314 let raw = self.binary.request_args.clone();
315
316 // Of relevance: https://github.com/microsoft/vscode/issues/4902#issuecomment-368583522
317 let launch = match raw.request {
318 dap::StartDebuggingRequestArgumentsRequest::Launch => self.request(Launch {
319 raw: raw.configuration,
320 }),
321 dap::StartDebuggingRequestArgumentsRequest::Attach => self.request(Attach {
322 raw: raw.configuration,
323 }),
324 };
325
326 let configuration_done_supported = ConfigurationDone::is_supported(capabilities);
327 let exception_filters = capabilities
328 .exception_breakpoint_filters
329 .as_ref()
330 .map(|exception_filters| {
331 exception_filters
332 .iter()
333 .filter(|filter| filter.default == Some(true))
334 .cloned()
335 .collect::<Vec<_>>()
336 })
337 .unwrap_or_default();
338 let supports_exception_filters = capabilities
339 .supports_exception_filter_options
340 .unwrap_or_default();
341 let this = self.clone();
342 let worktree = self.worktree().clone();
343 let configuration_sequence = cx.spawn({
344 async move |cx| {
345 let breakpoint_store =
346 dap_store.update(cx, |dap_store, _| dap_store.breakpoint_store().clone())?;
347 initialized_rx.await?;
348 let errors_by_path = cx
349 .update(|cx| this.send_source_breakpoints(false, &breakpoint_store, cx))?
350 .await;
351
352 dap_store.update(cx, |_, cx| {
353 let Some(worktree) = worktree.upgrade() else {
354 return;
355 };
356
357 for (path, error) in &errors_by_path {
358 log::error!("failed to set breakpoints for {path:?}: {error}");
359 }
360
361 if let Some(failed_path) = errors_by_path.keys().next() {
362 let failed_path = failed_path
363 .strip_prefix(worktree.read(cx).abs_path())
364 .unwrap_or(failed_path)
365 .display();
366 let message = format!(
367 "Failed to set breakpoints for {failed_path}{}",
368 match errors_by_path.len() {
369 0 => unreachable!(),
370 1 => "".into(),
371 2 => " and 1 other path".into(),
372 n => format!(" and {} other paths", n - 1),
373 }
374 );
375 cx.emit(super::dap_store::DapStoreEvent::Notification(message));
376 }
377 })?;
378
379 this.send_exception_breakpoints(exception_filters, supports_exception_filters)
380 .await
381 .ok();
382 let ret = if configuration_done_supported {
383 this.request(ConfigurationDone {})
384 } else {
385 Task::ready(Ok(()))
386 }
387 .await;
388 ret
389 }
390 });
391
392 cx.background_spawn(async move {
393 futures::future::try_join(launch, configuration_sequence).await?;
394 Ok(())
395 })
396 }
397
398 fn request<R: LocalDapCommand>(&self, request: R) -> Task<Result<R::Response>>
399 where
400 <R::DapRequest as dap::requests::Request>::Response: 'static,
401 <R::DapRequest as dap::requests::Request>::Arguments: 'static + Send,
402 {
403 let request = Arc::new(request);
404
405 let request_clone = request.clone();
406 let connection = self.client.clone();
407 self.executor.spawn(async move {
408 let args = request_clone.to_dap();
409 let response = connection.request::<R::DapRequest>(args).await?;
410 request.response_from_dap(response)
411 })
412 }
413}
414
415impl Mode {
416 pub(super) fn request_dap<R: DapCommand>(&self, request: R) -> Task<Result<R::Response>>
417 where
418 <R::DapRequest as dap::requests::Request>::Response: 'static,
419 <R::DapRequest as dap::requests::Request>::Arguments: 'static + Send,
420 {
421 match self {
422 Mode::Running(debug_adapter_client) => debug_adapter_client.request(request),
423 Mode::Building => Task::ready(Err(anyhow!(
424 "no adapter running to send request: {:?}",
425 request
426 ))),
427 }
428 }
429}
430
431#[derive(Default)]
432struct ThreadStates {
433 global_state: Option<ThreadStatus>,
434 known_thread_states: IndexMap<ThreadId, ThreadStatus>,
435}
436
437impl ThreadStates {
438 fn stop_all_threads(&mut self) {
439 self.global_state = Some(ThreadStatus::Stopped);
440 self.known_thread_states.clear();
441 }
442
443 fn exit_all_threads(&mut self) {
444 self.global_state = Some(ThreadStatus::Exited);
445 self.known_thread_states.clear();
446 }
447
448 fn continue_all_threads(&mut self) {
449 self.global_state = Some(ThreadStatus::Running);
450 self.known_thread_states.clear();
451 }
452
453 fn stop_thread(&mut self, thread_id: ThreadId) {
454 self.known_thread_states
455 .insert(thread_id, ThreadStatus::Stopped);
456 }
457
458 fn continue_thread(&mut self, thread_id: ThreadId) {
459 self.known_thread_states
460 .insert(thread_id, ThreadStatus::Running);
461 }
462
463 fn process_step(&mut self, thread_id: ThreadId) {
464 self.known_thread_states
465 .insert(thread_id, ThreadStatus::Stepping);
466 }
467
468 fn thread_status(&self, thread_id: ThreadId) -> ThreadStatus {
469 self.thread_state(thread_id)
470 .unwrap_or(ThreadStatus::Running)
471 }
472
473 fn thread_state(&self, thread_id: ThreadId) -> Option<ThreadStatus> {
474 self.known_thread_states
475 .get(&thread_id)
476 .copied()
477 .or(self.global_state)
478 }
479
480 fn exit_thread(&mut self, thread_id: ThreadId) {
481 self.known_thread_states
482 .insert(thread_id, ThreadStatus::Exited);
483 }
484
485 fn any_stopped_thread(&self) -> bool {
486 self.global_state
487 .is_some_and(|state| state == ThreadStatus::Stopped)
488 || self
489 .known_thread_states
490 .values()
491 .any(|status| *status == ThreadStatus::Stopped)
492 }
493}
494const MAX_TRACKED_OUTPUT_EVENTS: usize = 5000;
495
496type IsEnabled = bool;
497
498#[derive(Copy, Clone, Default, Debug, PartialEq, PartialOrd, Eq, Ord)]
499pub struct OutputToken(pub usize);
500/// Represents a current state of a single debug adapter and provides ways to mutate it.
501pub struct Session {
502 pub mode: Mode,
503 id: SessionId,
504 label: SharedString,
505 adapter: DebugAdapterName,
506 pub(super) capabilities: Capabilities,
507 child_session_ids: HashSet<SessionId>,
508 parent_session: Option<Entity<Session>>,
509 modules: Vec<dap::Module>,
510 loaded_sources: Vec<dap::Source>,
511 output_token: OutputToken,
512 output: Box<circular_buffer::CircularBuffer<MAX_TRACKED_OUTPUT_EVENTS, dap::OutputEvent>>,
513 threads: IndexMap<ThreadId, Thread>,
514 thread_states: ThreadStates,
515 variables: HashMap<VariableReference, Vec<dap::Variable>>,
516 stack_frames: IndexMap<StackFrameId, StackFrame>,
517 locations: HashMap<u64, dap::LocationsResponse>,
518 is_session_terminated: bool,
519 requests: HashMap<TypeId, HashMap<RequestSlot, Shared<Task<Option<()>>>>>,
520 pub(crate) breakpoint_store: Entity<BreakpointStore>,
521 ignore_breakpoints: bool,
522 exception_breakpoints: BTreeMap<String, (ExceptionBreakpointsFilter, IsEnabled)>,
523 background_tasks: Vec<Task<()>>,
524}
525
526trait CacheableCommand: Any + Send + Sync {
527 fn dyn_eq(&self, rhs: &dyn CacheableCommand) -> bool;
528 fn dyn_hash(&self, hasher: &mut dyn Hasher);
529 fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
530}
531
532impl<T> CacheableCommand for T
533where
534 T: DapCommand + PartialEq + Eq + Hash,
535{
536 fn dyn_eq(&self, rhs: &dyn CacheableCommand) -> bool {
537 (rhs as &dyn Any)
538 .downcast_ref::<Self>()
539 .map_or(false, |rhs| self == rhs)
540 }
541
542 fn dyn_hash(&self, mut hasher: &mut dyn Hasher) {
543 T::hash(self, &mut hasher);
544 }
545
546 fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
547 self
548 }
549}
550
551pub(crate) struct RequestSlot(Arc<dyn CacheableCommand>);
552
553impl<T: DapCommand + PartialEq + Eq + Hash> From<T> for RequestSlot {
554 fn from(request: T) -> Self {
555 Self(Arc::new(request))
556 }
557}
558
559impl PartialEq for RequestSlot {
560 fn eq(&self, other: &Self) -> bool {
561 self.0.dyn_eq(other.0.as_ref())
562 }
563}
564
565impl Eq for RequestSlot {}
566
567impl Hash for RequestSlot {
568 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
569 self.0.dyn_hash(state);
570 (&*self.0 as &dyn Any).type_id().hash(state)
571 }
572}
573
574#[derive(Debug, Clone, Hash, PartialEq, Eq)]
575pub struct CompletionsQuery {
576 pub query: String,
577 pub column: u64,
578 pub line: Option<u64>,
579 pub frame_id: Option<u64>,
580}
581
582impl CompletionsQuery {
583 pub fn new(
584 buffer: &language::Buffer,
585 cursor_position: language::Anchor,
586 frame_id: Option<u64>,
587 ) -> Self {
588 let PointUtf16 { row, column } = cursor_position.to_point_utf16(&buffer.snapshot());
589 Self {
590 query: buffer.text(),
591 column: column as u64,
592 frame_id,
593 line: Some(row as u64),
594 }
595 }
596}
597
598#[derive(Debug)]
599pub enum SessionEvent {
600 Modules,
601 LoadedSources,
602 Stopped(Option<ThreadId>),
603 StackTrace,
604 Variables,
605 Threads,
606 InvalidateInlineValue,
607 CapabilitiesLoaded,
608 RunInTerminal {
609 request: RunInTerminalRequestArguments,
610 sender: mpsc::Sender<Result<u32>>,
611 },
612}
613
614#[derive(Clone, Debug, PartialEq, Eq)]
615pub enum SessionStateEvent {
616 Running,
617 Shutdown,
618 Restart,
619 SpawnChildSession {
620 request: StartDebuggingRequestArguments,
621 },
622}
623
624impl EventEmitter<SessionEvent> for Session {}
625impl EventEmitter<SessionStateEvent> for Session {}
626
627// local session will send breakpoint updates to DAP for all new breakpoints
628// remote side will only send breakpoint updates when it is a breakpoint created by that peer
629// BreakpointStore notifies session on breakpoint changes
630impl Session {
631 pub(crate) fn new(
632 breakpoint_store: Entity<BreakpointStore>,
633 session_id: SessionId,
634 parent_session: Option<Entity<Session>>,
635 label: SharedString,
636 adapter: DebugAdapterName,
637 cx: &mut App,
638 ) -> Entity<Self> {
639 cx.new::<Self>(|cx| {
640 cx.subscribe(&breakpoint_store, |this, store, event, cx| match event {
641 BreakpointStoreEvent::BreakpointsUpdated(path, reason) => {
642 if let Some(local) = (!this.ignore_breakpoints)
643 .then(|| this.as_local_mut())
644 .flatten()
645 {
646 local
647 .send_breakpoints_from_path(path.clone(), *reason, &store, cx)
648 .detach();
649 };
650 }
651 BreakpointStoreEvent::BreakpointsCleared(paths) => {
652 if let Some(local) = (!this.ignore_breakpoints)
653 .then(|| this.as_local_mut())
654 .flatten()
655 {
656 local.unset_breakpoints_from_paths(paths, cx).detach();
657 }
658 }
659 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
660 })
661 .detach();
662 cx.on_app_quit(Self::on_app_quit).detach();
663
664 let this = Self {
665 mode: Mode::Building,
666 id: session_id,
667 child_session_ids: HashSet::default(),
668 parent_session,
669 capabilities: Capabilities::default(),
670 variables: Default::default(),
671 stack_frames: Default::default(),
672 thread_states: ThreadStates::default(),
673 output_token: OutputToken(0),
674 output: circular_buffer::CircularBuffer::boxed(),
675 requests: HashMap::default(),
676 modules: Vec::default(),
677 loaded_sources: Vec::default(),
678 threads: IndexMap::default(),
679 background_tasks: Vec::default(),
680 locations: Default::default(),
681 is_session_terminated: false,
682 ignore_breakpoints: false,
683 breakpoint_store,
684 exception_breakpoints: Default::default(),
685 label,
686 adapter,
687 };
688
689 this
690 })
691 }
692
693 pub fn worktree(&self) -> Option<Entity<Worktree>> {
694 match &self.mode {
695 Mode::Building => None,
696 Mode::Running(local_mode) => local_mode.worktree.upgrade(),
697 }
698 }
699
700 pub fn boot(
701 &mut self,
702 binary: DebugAdapterBinary,
703 worktree: Entity<Worktree>,
704 dap_store: WeakEntity<DapStore>,
705 cx: &mut Context<Self>,
706 ) -> Task<Result<()>> {
707 let (message_tx, mut message_rx) = futures::channel::mpsc::unbounded();
708 let (initialized_tx, initialized_rx) = futures::channel::oneshot::channel();
709
710 let background_tasks = vec![cx.spawn(async move |this: WeakEntity<Session>, cx| {
711 let mut initialized_tx = Some(initialized_tx);
712 while let Some(message) = message_rx.next().await {
713 if let Message::Event(event) = message {
714 if let Events::Initialized(_) = *event {
715 if let Some(tx) = initialized_tx.take() {
716 tx.send(()).ok();
717 }
718 } else {
719 let Ok(_) = this.update(cx, |session, cx| {
720 session.handle_dap_event(event, cx);
721 }) else {
722 break;
723 };
724 }
725 } else if let Message::Request(request) = message {
726 let Ok(_) = this.update(cx, |this, cx| {
727 if request.command == StartDebugging::COMMAND {
728 this.handle_start_debugging_request(request, cx)
729 .detach_and_log_err(cx);
730 } else if request.command == RunInTerminal::COMMAND {
731 this.handle_run_in_terminal_request(request, cx)
732 .detach_and_log_err(cx);
733 }
734 }) else {
735 break;
736 };
737 }
738 }
739 })];
740 self.background_tasks = background_tasks;
741 let id = self.id;
742 let parent_session = self.parent_session.clone();
743
744 cx.spawn(async move |this, cx| {
745 let mode = LocalMode::new(
746 id,
747 parent_session,
748 worktree.downgrade(),
749 binary,
750 message_tx,
751 cx.clone(),
752 )
753 .await?;
754 this.update(cx, |this, cx| {
755 this.mode = Mode::Running(mode);
756 cx.emit(SessionStateEvent::Running);
757 })?;
758
759 this.update(cx, |session, cx| session.request_initialize(cx))?
760 .await?;
761
762 this.update(cx, |session, cx| {
763 session.initialize_sequence(initialized_rx, dap_store.clone(), cx)
764 })?
765 .await
766 })
767 }
768
769 pub fn session_id(&self) -> SessionId {
770 self.id
771 }
772
773 pub fn child_session_ids(&self) -> HashSet<SessionId> {
774 self.child_session_ids.clone()
775 }
776
777 pub fn add_child_session_id(&mut self, session_id: SessionId) {
778 self.child_session_ids.insert(session_id);
779 }
780
781 pub fn remove_child_session_id(&mut self, session_id: SessionId) {
782 self.child_session_ids.remove(&session_id);
783 }
784
785 pub fn parent_id(&self, cx: &App) -> Option<SessionId> {
786 self.parent_session
787 .as_ref()
788 .map(|session| session.read(cx).id)
789 }
790
791 pub fn parent_session(&self) -> Option<&Entity<Self>> {
792 self.parent_session.as_ref()
793 }
794
795 pub fn capabilities(&self) -> &Capabilities {
796 &self.capabilities
797 }
798
799 pub fn binary(&self) -> &DebugAdapterBinary {
800 let Mode::Running(local_mode) = &self.mode else {
801 panic!("Session is not local");
802 };
803 &local_mode.binary
804 }
805
806 pub fn adapter(&self) -> DebugAdapterName {
807 self.adapter.clone()
808 }
809
810 pub fn label(&self) -> SharedString {
811 self.label.clone()
812 }
813
814 pub fn is_terminated(&self) -> bool {
815 self.is_session_terminated
816 }
817
818 pub fn is_local(&self) -> bool {
819 matches!(self.mode, Mode::Running(_))
820 }
821
822 pub fn as_local_mut(&mut self) -> Option<&mut LocalMode> {
823 match &mut self.mode {
824 Mode::Running(local_mode) => Some(local_mode),
825 Mode::Building => None,
826 }
827 }
828
829 pub fn as_local(&self) -> Option<&LocalMode> {
830 match &self.mode {
831 Mode::Running(local_mode) => Some(local_mode),
832 Mode::Building => None,
833 }
834 }
835
836 fn handle_start_debugging_request(
837 &mut self,
838 request: dap::messages::Request,
839 cx: &mut Context<Self>,
840 ) -> Task<Result<()>> {
841 let request_seq = request.seq;
842
843 let launch_request: Option<Result<StartDebuggingRequestArguments, _>> = request
844 .arguments
845 .as_ref()
846 .map(|value| serde_json::from_value(value.clone()));
847
848 let mut success = true;
849 if let Some(Ok(request)) = launch_request {
850 cx.emit(SessionStateEvent::SpawnChildSession { request });
851 } else {
852 log::error!(
853 "Failed to parse launch request arguments: {:?}",
854 request.arguments
855 );
856 success = false;
857 }
858
859 cx.spawn(async move |this, cx| {
860 this.update(cx, |this, cx| {
861 this.respond_to_client(
862 request_seq,
863 success,
864 StartDebugging::COMMAND.to_string(),
865 None,
866 cx,
867 )
868 })?
869 .await
870 })
871 }
872
873 fn handle_run_in_terminal_request(
874 &mut self,
875 request: dap::messages::Request,
876 cx: &mut Context<Self>,
877 ) -> Task<Result<()>> {
878 let request_args = serde_json::from_value::<RunInTerminalRequestArguments>(
879 request.arguments.unwrap_or_default(),
880 )
881 .expect("To parse StartDebuggingRequestArguments");
882
883 let seq = request.seq;
884
885 let (tx, mut rx) = mpsc::channel::<Result<u32>>(1);
886 cx.emit(SessionEvent::RunInTerminal {
887 request: request_args,
888 sender: tx,
889 });
890 cx.notify();
891
892 cx.spawn(async move |session, cx| {
893 let result = util::maybe!(async move {
894 rx.next().await.ok_or_else(|| {
895 anyhow!("failed to receive response from spawn terminal".to_string())
896 })?
897 })
898 .await;
899 let (success, body) = match result {
900 Ok(pid) => (
901 true,
902 serde_json::to_value(dap::RunInTerminalResponse {
903 process_id: None,
904 shell_process_id: Some(pid as u64),
905 })
906 .ok(),
907 ),
908 Err(error) => (
909 false,
910 serde_json::to_value(dap::ErrorResponse {
911 error: Some(dap::Message {
912 id: seq,
913 format: error.to_string(),
914 variables: None,
915 send_telemetry: None,
916 show_user: None,
917 url: None,
918 url_label: None,
919 }),
920 })
921 .ok(),
922 ),
923 };
924
925 session
926 .update(cx, |session, cx| {
927 session.respond_to_client(
928 seq,
929 success,
930 RunInTerminal::COMMAND.to_string(),
931 body,
932 cx,
933 )
934 })?
935 .await
936 })
937 }
938
939 pub(super) fn request_initialize(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
940 let adapter_id = self.adapter().to_string();
941 let request = Initialize { adapter_id };
942 match &self.mode {
943 Mode::Running(local_mode) => {
944 let capabilities = local_mode.request(request);
945
946 cx.spawn(async move |this, cx| {
947 let capabilities = capabilities.await?;
948 this.update(cx, |session, cx| {
949 session.capabilities = capabilities;
950 let filters = session
951 .capabilities
952 .exception_breakpoint_filters
953 .clone()
954 .unwrap_or_default();
955 for filter in filters {
956 let default = filter.default.unwrap_or_default();
957 session
958 .exception_breakpoints
959 .entry(filter.filter.clone())
960 .or_insert_with(|| (filter, default));
961 }
962 cx.emit(SessionEvent::CapabilitiesLoaded);
963 })?;
964 Ok(())
965 })
966 }
967 Mode::Building => Task::ready(Err(anyhow!(
968 "Cannot send initialize request, task still building"
969 ))),
970 }
971 }
972
973 pub(super) fn initialize_sequence(
974 &mut self,
975 initialize_rx: oneshot::Receiver<()>,
976 dap_store: WeakEntity<DapStore>,
977 cx: &mut Context<Self>,
978 ) -> Task<Result<()>> {
979 match &self.mode {
980 Mode::Running(local_mode) => {
981 local_mode.initialize_sequence(&self.capabilities, initialize_rx, dap_store, cx)
982 }
983 Mode::Building => Task::ready(Err(anyhow!("cannot initialize, still building"))),
984 }
985 }
986
987 pub fn run_to_position(
988 &mut self,
989 breakpoint: SourceBreakpoint,
990 active_thread_id: ThreadId,
991 cx: &mut Context<Self>,
992 ) {
993 match &mut self.mode {
994 Mode::Running(local_mode) => {
995 if !matches!(
996 self.thread_states.thread_state(active_thread_id),
997 Some(ThreadStatus::Stopped)
998 ) {
999 return;
1000 };
1001 let path = breakpoint.path.clone();
1002 local_mode.tmp_breakpoint = Some(breakpoint);
1003 let task = local_mode.send_breakpoints_from_path(
1004 path,
1005 BreakpointUpdatedReason::Toggled,
1006 &self.breakpoint_store,
1007 cx,
1008 );
1009
1010 cx.spawn(async move |this, cx| {
1011 task.await;
1012 this.update(cx, |this, cx| {
1013 this.continue_thread(active_thread_id, cx);
1014 })
1015 })
1016 .detach();
1017 }
1018 Mode::Building => {}
1019 }
1020 }
1021
1022 pub fn has_new_output(&self, last_update: OutputToken) -> bool {
1023 self.output_token.0.checked_sub(last_update.0).unwrap_or(0) != 0
1024 }
1025
1026 pub fn output(
1027 &self,
1028 since: OutputToken,
1029 ) -> (impl Iterator<Item = &dap::OutputEvent>, OutputToken) {
1030 if self.output_token.0 == 0 {
1031 return (self.output.range(0..0), OutputToken(0));
1032 };
1033
1034 let events_since = self.output_token.0.checked_sub(since.0).unwrap_or(0);
1035
1036 let clamped_events_since = events_since.clamp(0, self.output.len());
1037 (
1038 self.output
1039 .range(self.output.len() - clamped_events_since..),
1040 self.output_token,
1041 )
1042 }
1043
1044 pub fn respond_to_client(
1045 &self,
1046 request_seq: u64,
1047 success: bool,
1048 command: String,
1049 body: Option<serde_json::Value>,
1050 cx: &mut Context<Self>,
1051 ) -> Task<Result<()>> {
1052 let Some(local_session) = self.as_local() else {
1053 unreachable!("Cannot respond to remote client");
1054 };
1055 let client = local_session.client.clone();
1056
1057 cx.background_spawn(async move {
1058 client
1059 .send_message(Message::Response(Response {
1060 body,
1061 success,
1062 command,
1063 seq: request_seq + 1,
1064 request_seq,
1065 message: None,
1066 }))
1067 .await
1068 })
1069 }
1070
1071 fn handle_stopped_event(&mut self, event: StoppedEvent, cx: &mut Context<Self>) {
1072 // todo(debugger): Find a clean way to get around the clone
1073 let breakpoint_store = self.breakpoint_store.clone();
1074 if let Some((local, path)) = self.as_local_mut().and_then(|local| {
1075 let breakpoint = local.tmp_breakpoint.take()?;
1076 let path = breakpoint.path.clone();
1077 Some((local, path))
1078 }) {
1079 local
1080 .send_breakpoints_from_path(
1081 path,
1082 BreakpointUpdatedReason::Toggled,
1083 &breakpoint_store,
1084 cx,
1085 )
1086 .detach();
1087 };
1088
1089 if event.all_threads_stopped.unwrap_or_default() || event.thread_id.is_none() {
1090 self.thread_states.stop_all_threads();
1091
1092 self.invalidate_command_type::<StackTraceCommand>();
1093 }
1094
1095 // Event if we stopped all threads we still need to insert the thread_id
1096 // to our own data
1097 if let Some(thread_id) = event.thread_id {
1098 self.thread_states.stop_thread(ThreadId(thread_id));
1099
1100 self.invalidate_state(
1101 &StackTraceCommand {
1102 thread_id,
1103 start_frame: None,
1104 levels: None,
1105 }
1106 .into(),
1107 );
1108 }
1109
1110 self.invalidate_generic();
1111 self.threads.clear();
1112 self.variables.clear();
1113 cx.emit(SessionEvent::Stopped(
1114 event
1115 .thread_id
1116 .map(Into::into)
1117 .filter(|_| !event.preserve_focus_hint.unwrap_or(false)),
1118 ));
1119 cx.emit(SessionEvent::InvalidateInlineValue);
1120 cx.notify();
1121 }
1122
1123 pub(crate) fn handle_dap_event(&mut self, event: Box<Events>, cx: &mut Context<Self>) {
1124 match *event {
1125 Events::Initialized(_) => {
1126 debug_assert!(
1127 false,
1128 "Initialized event should have been handled in LocalMode"
1129 );
1130 }
1131 Events::Stopped(event) => self.handle_stopped_event(event, cx),
1132 Events::Continued(event) => {
1133 if event.all_threads_continued.unwrap_or_default() {
1134 self.thread_states.continue_all_threads();
1135 self.breakpoint_store.update(cx, |store, cx| {
1136 store.remove_active_position(Some(self.session_id()), cx)
1137 });
1138 } else {
1139 self.thread_states
1140 .continue_thread(ThreadId(event.thread_id));
1141 }
1142 // todo(debugger): We should be able to get away with only invalidating generic if all threads were continued
1143 self.invalidate_generic();
1144 }
1145 Events::Exited(_event) => {
1146 self.clear_active_debug_line(cx);
1147 }
1148 Events::Terminated(_) => {
1149 self.is_session_terminated = true;
1150 self.clear_active_debug_line(cx);
1151 }
1152 Events::Thread(event) => {
1153 let thread_id = ThreadId(event.thread_id);
1154
1155 match event.reason {
1156 dap::ThreadEventReason::Started => {
1157 self.thread_states.continue_thread(thread_id);
1158 }
1159 dap::ThreadEventReason::Exited => {
1160 self.thread_states.exit_thread(thread_id);
1161 }
1162 reason => {
1163 log::error!("Unhandled thread event reason {:?}", reason);
1164 }
1165 }
1166 self.invalidate_state(&ThreadsCommand.into());
1167 cx.notify();
1168 }
1169 Events::Output(event) => {
1170 if event
1171 .category
1172 .as_ref()
1173 .is_some_and(|category| *category == OutputEventCategory::Telemetry)
1174 {
1175 return;
1176 }
1177
1178 self.output.push_back(event);
1179 self.output_token.0 += 1;
1180 cx.notify();
1181 }
1182 Events::Breakpoint(_) => {}
1183 Events::Module(event) => {
1184 match event.reason {
1185 dap::ModuleEventReason::New => {
1186 self.modules.push(event.module);
1187 }
1188 dap::ModuleEventReason::Changed => {
1189 if let Some(module) = self
1190 .modules
1191 .iter_mut()
1192 .find(|other| event.module.id == other.id)
1193 {
1194 *module = event.module;
1195 }
1196 }
1197 dap::ModuleEventReason::Removed => {
1198 self.modules.retain(|other| event.module.id != other.id);
1199 }
1200 }
1201
1202 // todo(debugger): We should only send the invalidate command to downstream clients.
1203 // self.invalidate_state(&ModulesCommand.into());
1204 }
1205 Events::LoadedSource(_) => {
1206 self.invalidate_state(&LoadedSourcesCommand.into());
1207 }
1208 Events::Capabilities(event) => {
1209 self.capabilities = self.capabilities.merge(event.capabilities);
1210 cx.notify();
1211 }
1212 Events::Memory(_) => {}
1213 Events::Process(_) => {}
1214 Events::ProgressEnd(_) => {}
1215 Events::ProgressStart(_) => {}
1216 Events::ProgressUpdate(_) => {}
1217 Events::Invalidated(_) => {}
1218 Events::Other(_) => {}
1219 }
1220 }
1221
1222 /// Ensure that there's a request in flight for the given command, and if not, send it. Use this to run requests that are idempotent.
1223 fn fetch<T: DapCommand + PartialEq + Eq + Hash>(
1224 &mut self,
1225 request: T,
1226 process_result: impl FnOnce(
1227 &mut Self,
1228 Result<T::Response>,
1229 &mut Context<Self>,
1230 ) -> Option<T::Response>
1231 + 'static,
1232 cx: &mut Context<Self>,
1233 ) {
1234 const {
1235 assert!(
1236 T::CACHEABLE,
1237 "Only requests marked as cacheable should invoke `fetch`"
1238 );
1239 }
1240
1241 if !self.thread_states.any_stopped_thread()
1242 && request.type_id() != TypeId::of::<ThreadsCommand>()
1243 || self.is_session_terminated
1244 {
1245 return;
1246 }
1247
1248 let request_map = self
1249 .requests
1250 .entry(std::any::TypeId::of::<T>())
1251 .or_default();
1252
1253 if let Entry::Vacant(vacant) = request_map.entry(request.into()) {
1254 let command = vacant.key().0.clone().as_any_arc().downcast::<T>().unwrap();
1255
1256 let task = Self::request_inner::<Arc<T>>(
1257 &self.capabilities,
1258 &self.mode,
1259 command,
1260 process_result,
1261 cx,
1262 );
1263 let task = cx
1264 .background_executor()
1265 .spawn(async move {
1266 let _ = task.await?;
1267 Some(())
1268 })
1269 .shared();
1270
1271 vacant.insert(task);
1272 cx.notify();
1273 }
1274 }
1275
1276 pub async fn request2<T: DapCommand + PartialEq + Eq + Hash>(
1277 &self,
1278 request: T,
1279 ) -> Result<T::Response> {
1280 if !T::is_supported(&self.capabilities) {
1281 anyhow::bail!("DAP request {:?} is not supported", request);
1282 }
1283
1284 self.mode.request_dap(request).await
1285 }
1286
1287 fn request_inner<T: DapCommand + PartialEq + Eq + Hash>(
1288 capabilities: &Capabilities,
1289 mode: &Mode,
1290 request: T,
1291 process_result: impl FnOnce(
1292 &mut Self,
1293 Result<T::Response>,
1294 &mut Context<Self>,
1295 ) -> Option<T::Response>
1296 + 'static,
1297 cx: &mut Context<Self>,
1298 ) -> Task<Option<T::Response>> {
1299 if !T::is_supported(&capabilities) {
1300 log::warn!(
1301 "Attempted to send a DAP request that isn't supported: {:?}",
1302 request
1303 );
1304 let error = Err(anyhow::Error::msg(
1305 "Couldn't complete request because it's not supported",
1306 ));
1307 return cx.spawn(async move |this, cx| {
1308 this.update(cx, |this, cx| process_result(this, error, cx))
1309 .log_err()
1310 .flatten()
1311 });
1312 }
1313
1314 let request = mode.request_dap(request);
1315 cx.spawn(async move |this, cx| {
1316 let result = request.await;
1317 this.update(cx, |this, cx| process_result(this, result, cx))
1318 .log_err()
1319 .flatten()
1320 })
1321 }
1322
1323 fn request<T: DapCommand + PartialEq + Eq + Hash>(
1324 &self,
1325 request: T,
1326 process_result: impl FnOnce(
1327 &mut Self,
1328 Result<T::Response>,
1329 &mut Context<Self>,
1330 ) -> Option<T::Response>
1331 + 'static,
1332 cx: &mut Context<Self>,
1333 ) -> Task<Option<T::Response>> {
1334 Self::request_inner(&self.capabilities, &self.mode, request, process_result, cx)
1335 }
1336
1337 fn invalidate_command_type<Command: DapCommand>(&mut self) {
1338 self.requests.remove(&std::any::TypeId::of::<Command>());
1339 }
1340
1341 fn invalidate_generic(&mut self) {
1342 self.invalidate_command_type::<ModulesCommand>();
1343 self.invalidate_command_type::<LoadedSourcesCommand>();
1344 self.invalidate_command_type::<ThreadsCommand>();
1345 }
1346
1347 fn invalidate_state(&mut self, key: &RequestSlot) {
1348 self.requests
1349 .entry((&*key.0 as &dyn Any).type_id())
1350 .and_modify(|request_map| {
1351 request_map.remove(&key);
1352 });
1353 }
1354
1355 pub fn any_stopped_thread(&self) -> bool {
1356 self.thread_states.any_stopped_thread()
1357 }
1358
1359 pub fn thread_status(&self, thread_id: ThreadId) -> ThreadStatus {
1360 self.thread_states.thread_status(thread_id)
1361 }
1362
1363 pub fn threads(&mut self, cx: &mut Context<Self>) -> Vec<(dap::Thread, ThreadStatus)> {
1364 self.fetch(
1365 dap_command::ThreadsCommand,
1366 |this, result, cx| {
1367 let result = result.log_err()?;
1368
1369 this.threads = result
1370 .iter()
1371 .map(|thread| (ThreadId(thread.id), Thread::from(thread.clone())))
1372 .collect();
1373
1374 this.invalidate_command_type::<StackTraceCommand>();
1375 cx.emit(SessionEvent::Threads);
1376 cx.notify();
1377
1378 Some(result)
1379 },
1380 cx,
1381 );
1382
1383 self.threads
1384 .values()
1385 .map(|thread| {
1386 (
1387 thread.dap.clone(),
1388 self.thread_states.thread_status(ThreadId(thread.dap.id)),
1389 )
1390 })
1391 .collect()
1392 }
1393
1394 pub fn modules(&mut self, cx: &mut Context<Self>) -> &[Module] {
1395 self.fetch(
1396 dap_command::ModulesCommand,
1397 |this, result, cx| {
1398 let result = result.log_err()?;
1399
1400 this.modules = result.iter().cloned().collect();
1401 cx.emit(SessionEvent::Modules);
1402 cx.notify();
1403
1404 Some(result)
1405 },
1406 cx,
1407 );
1408
1409 &self.modules
1410 }
1411
1412 pub fn ignore_breakpoints(&self) -> bool {
1413 self.ignore_breakpoints
1414 }
1415
1416 pub fn toggle_ignore_breakpoints(
1417 &mut self,
1418 cx: &mut App,
1419 ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
1420 self.set_ignore_breakpoints(!self.ignore_breakpoints, cx)
1421 }
1422
1423 pub(crate) fn set_ignore_breakpoints(
1424 &mut self,
1425 ignore: bool,
1426 cx: &mut App,
1427 ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
1428 if self.ignore_breakpoints == ignore {
1429 return Task::ready(HashMap::default());
1430 }
1431
1432 self.ignore_breakpoints = ignore;
1433
1434 if let Some(local) = self.as_local() {
1435 local.send_source_breakpoints(ignore, &self.breakpoint_store, cx)
1436 } else {
1437 // todo(debugger): We need to propagate this change to downstream sessions and send a message to upstream sessions
1438 unimplemented!()
1439 }
1440 }
1441
1442 pub fn exception_breakpoints(
1443 &self,
1444 ) -> impl Iterator<Item = &(ExceptionBreakpointsFilter, IsEnabled)> {
1445 self.exception_breakpoints.values()
1446 }
1447
1448 pub fn toggle_exception_breakpoint(&mut self, id: &str, cx: &App) {
1449 if let Some((_, is_enabled)) = self.exception_breakpoints.get_mut(id) {
1450 *is_enabled = !*is_enabled;
1451 self.send_exception_breakpoints(cx);
1452 }
1453 }
1454
1455 fn send_exception_breakpoints(&mut self, cx: &App) {
1456 if let Some(local) = self.as_local() {
1457 let exception_filters = self
1458 .exception_breakpoints
1459 .values()
1460 .filter_map(|(filter, is_enabled)| is_enabled.then(|| filter.clone()))
1461 .collect();
1462
1463 let supports_exception_filters = self
1464 .capabilities
1465 .supports_exception_filter_options
1466 .unwrap_or_default();
1467 local
1468 .send_exception_breakpoints(exception_filters, supports_exception_filters)
1469 .detach_and_log_err(cx);
1470 } else {
1471 debug_assert!(false, "Not implemented");
1472 }
1473 }
1474
1475 pub fn breakpoints_enabled(&self) -> bool {
1476 self.ignore_breakpoints
1477 }
1478
1479 pub fn loaded_sources(&mut self, cx: &mut Context<Self>) -> &[Source] {
1480 self.fetch(
1481 dap_command::LoadedSourcesCommand,
1482 |this, result, cx| {
1483 let result = result.log_err()?;
1484 this.loaded_sources = result.iter().cloned().collect();
1485 cx.emit(SessionEvent::LoadedSources);
1486 cx.notify();
1487 Some(result)
1488 },
1489 cx,
1490 );
1491
1492 &self.loaded_sources
1493 }
1494
1495 fn fallback_to_manual_restart(
1496 &mut self,
1497 res: Result<()>,
1498 cx: &mut Context<Self>,
1499 ) -> Option<()> {
1500 if res.log_err().is_none() {
1501 cx.emit(SessionStateEvent::Restart);
1502 return None;
1503 }
1504 Some(())
1505 }
1506
1507 fn empty_response(&mut self, res: Result<()>, _cx: &mut Context<Self>) -> Option<()> {
1508 res.log_err()?;
1509 Some(())
1510 }
1511
1512 fn on_step_response<T: DapCommand + PartialEq + Eq + Hash>(
1513 thread_id: ThreadId,
1514 ) -> impl FnOnce(&mut Self, Result<T::Response>, &mut Context<Self>) -> Option<T::Response> + 'static
1515 {
1516 move |this, response, cx| match response.log_err() {
1517 Some(response) => {
1518 this.breakpoint_store.update(cx, |store, cx| {
1519 store.remove_active_position(Some(this.session_id()), cx)
1520 });
1521 Some(response)
1522 }
1523 None => {
1524 this.thread_states.stop_thread(thread_id);
1525 cx.notify();
1526 None
1527 }
1528 }
1529 }
1530
1531 fn clear_active_debug_line_response(
1532 &mut self,
1533 response: Result<()>,
1534 cx: &mut Context<Session>,
1535 ) -> Option<()> {
1536 response.log_err()?;
1537 self.clear_active_debug_line(cx);
1538 Some(())
1539 }
1540
1541 fn clear_active_debug_line(&mut self, cx: &mut Context<Session>) {
1542 self.breakpoint_store.update(cx, |store, cx| {
1543 store.remove_active_position(Some(self.id), cx)
1544 });
1545 }
1546
1547 pub fn pause_thread(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) {
1548 self.request(
1549 PauseCommand {
1550 thread_id: thread_id.0,
1551 },
1552 Self::empty_response,
1553 cx,
1554 )
1555 .detach();
1556 }
1557
1558 pub fn restart_stack_frame(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) {
1559 self.request(
1560 RestartStackFrameCommand { stack_frame_id },
1561 Self::empty_response,
1562 cx,
1563 )
1564 .detach();
1565 }
1566
1567 pub fn restart(&mut self, args: Option<Value>, cx: &mut Context<Self>) {
1568 if self.capabilities.supports_restart_request.unwrap_or(false) && !self.is_terminated() {
1569 self.request(
1570 RestartCommand {
1571 raw: args.unwrap_or(Value::Null),
1572 },
1573 Self::fallback_to_manual_restart,
1574 cx,
1575 )
1576 .detach();
1577 } else {
1578 cx.emit(SessionStateEvent::Restart);
1579 }
1580 }
1581
1582 fn on_app_quit(&mut self, cx: &mut Context<Self>) -> Task<()> {
1583 let debug_adapter = self.adapter_client();
1584
1585 cx.background_spawn(async move {
1586 if let Some(client) = debug_adapter {
1587 client.shutdown().await.log_err();
1588 }
1589 })
1590 }
1591
1592 pub fn shutdown(&mut self, cx: &mut Context<Self>) -> Task<()> {
1593 self.is_session_terminated = true;
1594 self.thread_states.exit_all_threads();
1595 cx.notify();
1596
1597 let task = if self
1598 .capabilities
1599 .supports_terminate_request
1600 .unwrap_or_default()
1601 {
1602 self.request(
1603 TerminateCommand {
1604 restart: Some(false),
1605 },
1606 Self::clear_active_debug_line_response,
1607 cx,
1608 )
1609 } else {
1610 self.request(
1611 DisconnectCommand {
1612 restart: Some(false),
1613 terminate_debuggee: Some(true),
1614 suspend_debuggee: Some(false),
1615 },
1616 Self::clear_active_debug_line_response,
1617 cx,
1618 )
1619 };
1620
1621 cx.emit(SessionStateEvent::Shutdown);
1622
1623 let debug_client = self.adapter_client();
1624
1625 cx.background_spawn(async move {
1626 let _ = task.await;
1627
1628 if let Some(client) = debug_client {
1629 client.shutdown().await.log_err();
1630 }
1631 })
1632 }
1633
1634 pub fn completions(
1635 &mut self,
1636 query: CompletionsQuery,
1637 cx: &mut Context<Self>,
1638 ) -> Task<Result<Vec<dap::CompletionItem>>> {
1639 let task = self.request(query, |_, result, _| result.log_err(), cx);
1640
1641 cx.background_executor().spawn(async move {
1642 anyhow::Ok(
1643 task.await
1644 .map(|response| response.targets)
1645 .ok_or_else(|| anyhow!("failed to fetch completions"))?,
1646 )
1647 })
1648 }
1649
1650 pub fn continue_thread(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) {
1651 self.thread_states.continue_thread(thread_id);
1652 self.request(
1653 ContinueCommand {
1654 args: ContinueArguments {
1655 thread_id: thread_id.0,
1656 single_thread: Some(true),
1657 },
1658 },
1659 Self::on_step_response::<ContinueCommand>(thread_id),
1660 cx,
1661 )
1662 .detach();
1663 }
1664
1665 pub fn adapter_client(&self) -> Option<Arc<DebugAdapterClient>> {
1666 match self.mode {
1667 Mode::Running(ref local) => Some(local.client.clone()),
1668 Mode::Building => None,
1669 }
1670 }
1671
1672 pub fn step_over(
1673 &mut self,
1674 thread_id: ThreadId,
1675 granularity: SteppingGranularity,
1676 cx: &mut Context<Self>,
1677 ) {
1678 let supports_single_thread_execution_requests =
1679 self.capabilities.supports_single_thread_execution_requests;
1680 let supports_stepping_granularity = self
1681 .capabilities
1682 .supports_stepping_granularity
1683 .unwrap_or_default();
1684
1685 let command = NextCommand {
1686 inner: StepCommand {
1687 thread_id: thread_id.0,
1688 granularity: supports_stepping_granularity.then(|| granularity),
1689 single_thread: supports_single_thread_execution_requests,
1690 },
1691 };
1692
1693 self.thread_states.process_step(thread_id);
1694 self.request(
1695 command,
1696 Self::on_step_response::<NextCommand>(thread_id),
1697 cx,
1698 )
1699 .detach();
1700 }
1701
1702 pub fn step_in(
1703 &mut self,
1704 thread_id: ThreadId,
1705 granularity: SteppingGranularity,
1706 cx: &mut Context<Self>,
1707 ) {
1708 let supports_single_thread_execution_requests =
1709 self.capabilities.supports_single_thread_execution_requests;
1710 let supports_stepping_granularity = self
1711 .capabilities
1712 .supports_stepping_granularity
1713 .unwrap_or_default();
1714
1715 let command = StepInCommand {
1716 inner: StepCommand {
1717 thread_id: thread_id.0,
1718 granularity: supports_stepping_granularity.then(|| granularity),
1719 single_thread: supports_single_thread_execution_requests,
1720 },
1721 };
1722
1723 self.thread_states.process_step(thread_id);
1724 self.request(
1725 command,
1726 Self::on_step_response::<StepInCommand>(thread_id),
1727 cx,
1728 )
1729 .detach();
1730 }
1731
1732 pub fn step_out(
1733 &mut self,
1734 thread_id: ThreadId,
1735 granularity: SteppingGranularity,
1736 cx: &mut Context<Self>,
1737 ) {
1738 let supports_single_thread_execution_requests =
1739 self.capabilities.supports_single_thread_execution_requests;
1740 let supports_stepping_granularity = self
1741 .capabilities
1742 .supports_stepping_granularity
1743 .unwrap_or_default();
1744
1745 let command = StepOutCommand {
1746 inner: StepCommand {
1747 thread_id: thread_id.0,
1748 granularity: supports_stepping_granularity.then(|| granularity),
1749 single_thread: supports_single_thread_execution_requests,
1750 },
1751 };
1752
1753 self.thread_states.process_step(thread_id);
1754 self.request(
1755 command,
1756 Self::on_step_response::<StepOutCommand>(thread_id),
1757 cx,
1758 )
1759 .detach();
1760 }
1761
1762 pub fn step_back(
1763 &mut self,
1764 thread_id: ThreadId,
1765 granularity: SteppingGranularity,
1766 cx: &mut Context<Self>,
1767 ) {
1768 let supports_single_thread_execution_requests =
1769 self.capabilities.supports_single_thread_execution_requests;
1770 let supports_stepping_granularity = self
1771 .capabilities
1772 .supports_stepping_granularity
1773 .unwrap_or_default();
1774
1775 let command = StepBackCommand {
1776 inner: StepCommand {
1777 thread_id: thread_id.0,
1778 granularity: supports_stepping_granularity.then(|| granularity),
1779 single_thread: supports_single_thread_execution_requests,
1780 },
1781 };
1782
1783 self.thread_states.process_step(thread_id);
1784
1785 self.request(
1786 command,
1787 Self::on_step_response::<StepBackCommand>(thread_id),
1788 cx,
1789 )
1790 .detach();
1791 }
1792
1793 pub fn stack_frames(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) -> Vec<StackFrame> {
1794 if self.thread_states.thread_status(thread_id) == ThreadStatus::Stopped
1795 && self.requests.contains_key(&ThreadsCommand.type_id())
1796 && self.threads.contains_key(&thread_id)
1797 // ^ todo(debugger): We need a better way to check that we're not querying stale data
1798 // We could still be using an old thread id and have sent a new thread's request
1799 // This isn't the biggest concern right now because it hasn't caused any issues outside of tests
1800 // But it very well could cause a minor bug in the future that is hard to track down
1801 {
1802 self.fetch(
1803 super::dap_command::StackTraceCommand {
1804 thread_id: thread_id.0,
1805 start_frame: None,
1806 levels: None,
1807 },
1808 move |this, stack_frames, cx| {
1809 let stack_frames = stack_frames.log_err()?;
1810
1811 let entry = this.threads.entry(thread_id).and_modify(|thread| {
1812 thread.stack_frame_ids =
1813 stack_frames.iter().map(|frame| frame.id).collect();
1814 });
1815 debug_assert!(
1816 matches!(entry, indexmap::map::Entry::Occupied(_)),
1817 "Sent request for thread_id that doesn't exist"
1818 );
1819
1820 this.stack_frames.extend(
1821 stack_frames
1822 .iter()
1823 .cloned()
1824 .map(|frame| (frame.id, StackFrame::from(frame))),
1825 );
1826
1827 this.invalidate_command_type::<ScopesCommand>();
1828 this.invalidate_command_type::<VariablesCommand>();
1829
1830 cx.emit(SessionEvent::StackTrace);
1831 cx.notify();
1832 Some(stack_frames)
1833 },
1834 cx,
1835 );
1836 }
1837
1838 self.threads
1839 .get(&thread_id)
1840 .map(|thread| {
1841 thread
1842 .stack_frame_ids
1843 .iter()
1844 .filter_map(|id| self.stack_frames.get(id))
1845 .cloned()
1846 .collect()
1847 })
1848 .unwrap_or_default()
1849 }
1850
1851 pub fn scopes(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) -> &[dap::Scope] {
1852 if self.requests.contains_key(&TypeId::of::<ThreadsCommand>())
1853 && self
1854 .requests
1855 .contains_key(&TypeId::of::<StackTraceCommand>())
1856 {
1857 self.fetch(
1858 ScopesCommand { stack_frame_id },
1859 move |this, scopes, cx| {
1860 let scopes = scopes.log_err()?;
1861
1862 for scope in scopes .iter(){
1863 this.variables(scope.variables_reference, cx);
1864 }
1865
1866 let entry = this
1867 .stack_frames
1868 .entry(stack_frame_id)
1869 .and_modify(|stack_frame| {
1870 stack_frame.scopes = scopes.clone();
1871 });
1872
1873 cx.emit(SessionEvent::Variables);
1874
1875 debug_assert!(
1876 matches!(entry, indexmap::map::Entry::Occupied(_)),
1877 "Sent scopes request for stack_frame_id that doesn't exist or hasn't been fetched"
1878 );
1879
1880 Some(scopes)
1881 },
1882 cx,
1883 );
1884 }
1885
1886 self.stack_frames
1887 .get(&stack_frame_id)
1888 .map(|frame| frame.scopes.as_slice())
1889 .unwrap_or_default()
1890 }
1891
1892 pub fn variables_by_stack_frame_id(&self, stack_frame_id: StackFrameId) -> Vec<dap::Variable> {
1893 let Some(stack_frame) = self.stack_frames.get(&stack_frame_id) else {
1894 return Vec::new();
1895 };
1896
1897 stack_frame
1898 .scopes
1899 .iter()
1900 .filter_map(|scope| self.variables.get(&scope.variables_reference))
1901 .flatten()
1902 .cloned()
1903 .collect()
1904 }
1905
1906 pub fn variables(
1907 &mut self,
1908 variables_reference: VariableReference,
1909 cx: &mut Context<Self>,
1910 ) -> Vec<dap::Variable> {
1911 let command = VariablesCommand {
1912 variables_reference,
1913 filter: None,
1914 start: None,
1915 count: None,
1916 format: None,
1917 };
1918
1919 self.fetch(
1920 command,
1921 move |this, variables, cx| {
1922 let variables = variables.log_err()?;
1923 this.variables
1924 .insert(variables_reference, variables.clone());
1925
1926 cx.emit(SessionEvent::Variables);
1927 cx.emit(SessionEvent::InvalidateInlineValue);
1928 Some(variables)
1929 },
1930 cx,
1931 );
1932
1933 self.variables
1934 .get(&variables_reference)
1935 .cloned()
1936 .unwrap_or_default()
1937 }
1938
1939 pub fn set_variable_value(
1940 &mut self,
1941 variables_reference: u64,
1942 name: String,
1943 value: String,
1944 cx: &mut Context<Self>,
1945 ) {
1946 if self.capabilities.supports_set_variable.unwrap_or_default() {
1947 self.request(
1948 SetVariableValueCommand {
1949 name,
1950 value,
1951 variables_reference,
1952 },
1953 move |this, response, cx| {
1954 let response = response.log_err()?;
1955 this.invalidate_command_type::<VariablesCommand>();
1956 cx.notify();
1957 Some(response)
1958 },
1959 cx,
1960 )
1961 .detach()
1962 }
1963 }
1964
1965 pub fn evaluate(
1966 &mut self,
1967 expression: String,
1968 context: Option<EvaluateArgumentsContext>,
1969 frame_id: Option<u64>,
1970 source: Option<Source>,
1971 cx: &mut Context<Self>,
1972 ) -> Task<()> {
1973 let request = self.mode.request_dap(EvaluateCommand {
1974 expression,
1975 context,
1976 frame_id,
1977 source,
1978 });
1979 cx.spawn(async move |this, cx| {
1980 let response = request.await;
1981 this.update(cx, |this, cx| {
1982 match response {
1983 Ok(response) => {
1984 this.output_token.0 += 1;
1985 this.output.push_back(dap::OutputEvent {
1986 category: None,
1987 output: format!("< {}", &response.result),
1988 group: None,
1989 variables_reference: Some(response.variables_reference),
1990 source: None,
1991 line: None,
1992 column: None,
1993 data: None,
1994 location_reference: None,
1995 });
1996 }
1997 Err(e) => {
1998 this.output_token.0 += 1;
1999 this.output.push_back(dap::OutputEvent {
2000 category: None,
2001 output: format!("{}", e),
2002 group: None,
2003 variables_reference: None,
2004 source: None,
2005 line: None,
2006 column: None,
2007 data: None,
2008 location_reference: None,
2009 });
2010 }
2011 };
2012 this.invalidate_command_type::<ScopesCommand>();
2013 cx.notify();
2014 })
2015 .ok();
2016 })
2017 }
2018
2019 pub fn location(
2020 &mut self,
2021 reference: u64,
2022 cx: &mut Context<Self>,
2023 ) -> Option<dap::LocationsResponse> {
2024 self.fetch(
2025 LocationsCommand { reference },
2026 move |this, response, _| {
2027 let response = response.log_err()?;
2028 this.locations.insert(reference, response.clone());
2029 Some(response)
2030 },
2031 cx,
2032 );
2033 self.locations.get(&reference).cloned()
2034 }
2035
2036 pub fn disconnect_client(&mut self, cx: &mut Context<Self>) {
2037 let command = DisconnectCommand {
2038 restart: Some(false),
2039 terminate_debuggee: Some(true),
2040 suspend_debuggee: Some(false),
2041 };
2042
2043 self.request(command, Self::empty_response, cx).detach()
2044 }
2045
2046 pub fn terminate_threads(&mut self, thread_ids: Option<Vec<ThreadId>>, cx: &mut Context<Self>) {
2047 if self
2048 .capabilities
2049 .supports_terminate_threads_request
2050 .unwrap_or_default()
2051 {
2052 self.request(
2053 TerminateThreadsCommand {
2054 thread_ids: thread_ids.map(|ids| ids.into_iter().map(|id| id.0).collect()),
2055 },
2056 Self::clear_active_debug_line_response,
2057 cx,
2058 )
2059 .detach();
2060 } else {
2061 self.shutdown(cx).detach();
2062 }
2063 }
2064}