Skip to content

Visual Studio Code, rebuilt in Rust

Rust
12.8 KB
Raw Blame
//! callStackView.ts `onContextMenu`: a Call Stack row's context menu (`MenuId.DebugCallStackContext`), and the
//! debugCommands.ts `CallStackContext` its commands run on.

use std::collections::HashMap;
use std::path::Path;

use gpui::{Bounds, Context, Pixels, Window};
use serde_json::{Value, json};

use super::Workbench;
use crate::debug::session::{Session, StackFrame, State, Thread};
use crate::menus::{MenuId, menu_group_actions};

/// A Call Stack row: a session, a thread, or a frame by its index in the thread's call stack.
#[derive(Clone)]
pub(super) enum CallStackItem {
    Session(String),
    Thread(String, i64),
    Frame(String, i64, usize),
}

impl Workbench {
    /// `onContextMenu`: the menu but its `inline` group over the row's context keys, run with
    /// `getContextForContributedActions` and `getContext`.
    pub(super) fn show_call_stack_menu(&mut self, item: &CallStackItem, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let mut context = self.key_context(window);
        let Some(args) = self.call_stack_item_context(item, &mut context) else { return };
        let actions = menu_group_actions(&self.menus, MenuId::DebugCallStackContext, &context, |group| group != "inline");
        self.show_context_menu_actions(actions, &context, anchor, args, window, cx);
    }

    /// `getSessionContextOverlay`, `getThreadContextOverlay` or `getStackFrameContextOverlay` into `context`, and the
    /// row's command arguments.
    pub(super) fn call_stack_item_context(&self, item: &CallStackItem, context: &mut HashMap<String, Value>) -> Option<Vec<Value>> {
        let (session_id, thread_id, frame_index) = match item {
            CallStackItem::Session(session) => (session, None, None),
            CallStackItem::Thread(session, thread) => (session, Some(*thread), None),
            CallStackItem::Frame(session, thread, index) => (session, Some(*thread), Some(*index)),
        };
        let session = self.debug.session(session_id)?;
        let session_context = json!({ "sessionId": session.id });
        let Some(thread_id) = thread_id else {
            let one_thread = (session.threads.len() == 1).then(|| &session.threads[0]);
            context.insert("callStackItemType".into(), json!("session"));
            context.insert("callStackSessionIsAttach".into(), json!(self.is_session_attach(session)));
            context.insert("callStackItemStopped".into(), json!(session.state(None) == State::Stopped));
            context.insert("callStackSessionHasOneThread".into(), json!(one_thread.is_some()));
            context.insert("threadHasMultipleStackFrames".into(), json!(one_thread.is_some_and(has_multiple_stack_frames)));
            return Some(vec![json!(session.id), session_context]);
        };
        let thread = session.thread(thread_id)?;
        let thread_context = json!({ "sessionId": session.id, "threadId": thread_context_id(session, thread) });
        let Some(index) = frame_index else {
            context.insert("callStackItemType".into(), json!("thread"));
            context.insert("callStackItemStopped".into(), json!(thread.stopped));
            context.insert("threadHasMultipleStackFrames".into(), json!(has_multiple_stack_frames(thread)));
            return Some(vec![json!(thread.id), thread_context]);
        };
        let frame = thread.frames.get(index)?;
        context.insert("callStackItemType".into(), json!("stackFrame"));
        context.insert("stackFrameSupportsRestart".into(), json!(frame.can_restart));
        let range = json!({ "startLineNumber": frame.line, "startColumn": frame.column, "endLineNumber": frame.end_line, "endColumn": frame.end_column });
        let frame_context = json!({
            "sessionId": session.id,
            "threadId": thread_context["threadId"],
            "frameId": frame_context_id(session, thread, index, frame),
            "frameName": frame.name,
            "frameLocation": { "range": range, "source": frame.source },
        });
        // `getContextForContributedActions`: an in-memory source's path, reference or name, else its uri.
        let contributed = match frame.path() {
            Some(path) => json!(crate::editor_history::file_uri_string(Path::new(path))),
            None => [&frame.source["path"], &frame.source["sourceReference"], &frame.source["name"]].into_iter().find(|value| !value.is_null()).cloned().unwrap_or(Value::Null),
        };
        Some(vec![contributed, frame_context])
    }

    /// debugUtils.ts `isSessionAttach`: an attach outside an extension host debug session, its parents too.
    fn is_session_attach(&self, session: &Session) -> bool {
        session.configuration["request"] == "attach"
            && self.extension_host_debug_session(&session.id).is_none()
            && session.parent.as_deref().and_then(|parent| self.debug.session(parent)).is_none_or(|parent| self.is_session_attach(parent))
    }

    /// debugCommands.ts `isSessionContext`: the context's session, else the focused one.
    pub(super) fn context_session(&self, args: &[Value]) -> Option<String> {
        match args.get(1).and_then(|context| context["sessionId"].as_str()) {
            Some(session) => Some(session.to_owned()),
            None => self.debug.focus.session.clone(),
        }
    }

    /// debugCommands.ts `getThreadAndRun`'s thread: the context's, a session context's first, else the focused
    /// thread or the focused session's first.
    pub(super) fn context_thread(&self, args: &[Value]) -> Option<(String, i64)> {
        let context = args.get(1).unwrap_or(&Value::Null);
        if let Some(session) = context["sessionId"].as_str().and_then(|id| self.debug.session(id)) {
            let thread = match context["threadId"].as_str() {
                Some(id) => session.threads.iter().find(|thread| thread_context_id(session, thread) == id),
                None => session.threads.first(),
            };
            if let Some(thread) = thread {
                return Some((session.id.clone(), thread.id));
            }
        }
        let session = self.debug.focused_session()?;
        let thread = self.debug.focus.thread.or_else(|| session.threads.first().map(|thread| thread.id))?;
        Some((session.id.clone(), thread))
    }

    /// debugCommands.ts `getFrame`: the context's frame, else (without a frame context) the focused one.
    pub(super) fn context_frame(&self, args: &[Value]) -> Option<(&Session, &Thread, &StackFrame)> {
        let context = args.get(1).unwrap_or(&Value::Null);
        if let (Some(session), Some(thread), Some(frame)) = (context["sessionId"].as_str(), context["threadId"].as_str(), context["frameId"].as_str()) {
            let session = self.debug.session(session)?;
            let thread = session.threads.iter().find(|candidate| thread_context_id(session, candidate) == thread)?;
            let index = thread.frames.iter().enumerate().position(|(index, candidate)| frame_context_id(session, thread, index, candidate) == frame)?;
            return Some((session, thread, &thread.frames[index]));
        }
        let session = self.debug.focused_session()?;
        let thread = session.thread(self.debug.focus.thread?)?;
        let frame = thread.frames.iter().find(|frame| Some(frame.id) == self.debug.focus.frame)?;
        Some((session, thread, frame))
    }
}

/// callStackView.ts `hasMultipleStackFrames`.
pub(super) fn has_multiple_stack_frames(thread: &Thread) -> bool {
    thread.frames.len() > 1 || thread.total_frames.is_some()
}

/// debugModel.ts `StackFrame.toString`: the name and its file or in-memory source's name with the line.
pub(super) fn stack_frame_label(frame: &StackFrame) -> String {
    let source = frame.path().map(str::to_owned).unwrap_or_else(|| frame.source_name());
    match source.as_str() {
        "Unknown Source" => frame.name.clone(),
        _ => format!("{} ({source}:{})", frame.name, frame.line),
    }
}

/// debugModel.ts `Thread.getId`.
fn thread_context_id(session: &Session, thread: &Thread) -> String {
    format!("thread:{}:{}", session.id, thread.id)
}

/// debugModel.ts `StackFrame.getId`.
fn frame_context_id(session: &Session, thread: &Thread, index: usize, frame: &StackFrame) -> String {
    format!("stackframe:{}:{index}:{}", thread_context_id(session, thread), frame.source_name())
}
#[cfg(test)]
mod tests {
    use gpui::TestAppContext;

    use super::*;
    use crate::menus::MenuAction;

    fn frame(id: i64, name: &str, line: u32) -> StackFrame {
        StackFrame { id, name: name.into(), source: json!({ "name": "a.js", "path": "/tmp/a.js" }), line, column: 1, end_line: line, end_column: 1, can_restart: true, instruction_pointer_reference: Some("0x1".into()), ..Default::default() }
    }

    /// callStackView.ts `onContextMenu` with debug.contribution.ts's `DebugCallStackContext` items, and the
    /// debugCommands.ts handlers on the row's `CallStackContext` rather than the focused thread.
    #[gpui::test]
    fn a_call_stack_row_menu_shows_its_kind_of_items_and_runs_them_on_the_row(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let (sender, host) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx));
        let titles = |item: CallStackItem, cx: &mut gpui::VisualTestContext| {
            workbench.update_in(cx, |workbench, window, cx| {
                workbench.show_call_stack_menu(&item, Bounds::default(), window, cx);
                let menu = workbench.context_menu.take().expect("a context menu shows");
                menu.levels[0].actions.iter().map(|action| match action {
                    MenuAction::Command { title, enabled, .. } => format!("{title}{}", if *enabled { "" } else { " (disabled)" }),
                    _ => "-".to_owned(),
                }).collect::<Vec<_>>()
            })
        };
        workbench.update_in(cx, |workbench, _, _| {
            let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.initialized = true;
            session.capabilities = json!({ "supportsRestartFrame": true, "supportTerminateDebuggee": true, "supportSuspendDebuggee": true, "supportsDisassembleRequest": true });
            session.set_threads(&[json!({ "id": 1, "name": "main" }), json!({ "id": 2, "name": "worker" })]);
            session.stop_threads(&json!({ "reason": "pause", "allThreadsStopped": true }));
            session.threads[0].frames = vec![frame(10, "main", 3)];
            session.threads[1].frames = vec![frame(20, "work", 7), frame(21, "run", 9)];
            workbench.debug.sessions.push(session);
            workbench.debug.focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(10) };
        });
        assert_eq!(titles(CallStackItem::Session("s".into()), cx), ["Restart", "Disconnect", "Disconnect and Suspend", "Stop"]);
        assert_eq!(titles(CallStackItem::Thread("s".into(), 2), cx), ["Continue", "Step Over", "Step Into", "Step Out", "-", "Terminate Thread (disabled)"]);
        assert_eq!(titles(CallStackItem::Frame("s".into(), 2, 0), cx), ["Restart Frame", "-", "Copy Call Stack", "-", "Open Disassembly View"]);

        let run = |command: &str, item: CallStackItem, cx: &mut gpui::VisualTestContext| {
            workbench.update_in(cx, |workbench, window, cx| {
                let args = workbench.call_stack_item_context(&item, &mut HashMap::new()).unwrap();
                drop(workbench.execute_command(command, args, window, cx));
            });
            cx.run_until_parked();
            let request = host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).last();
            request.map(|request| (request["command"].clone(), request["arguments"].clone()))
        };
        assert_eq!(run("debug.copyStackTrace", CallStackItem::Frame("s".into(), 2, 1), cx), None);
        assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("work (/tmp/a.js:7)\nrun (/tmp/a.js:9)"));
        assert_eq!(run("workbench.action.debug.restartFrame", CallStackItem::Frame("s".into(), 2, 1), cx), Some((json!("restartFrame"), json!({ "frameId": 21 }))));
        assert_eq!(run("workbench.action.debug.stepOver", CallStackItem::Thread("s".into(), 2), cx), Some((json!("next"), json!({ "threadId": 2 }))), "the row's thread, not the focused one");
        assert_eq!(run("workbench.action.debug.disconnectAndSuspend", CallStackItem::Session("s".into()), cx), Some((json!("disconnect"), json!({ "restart": false, "terminateDebuggee": false, "suspendDebuggee": true }))));
    }
}