VS Code:如何从扩展中访问调试变量?

VS Code: How to access debug variables from within extension?

我正在为 visual studio 代码编写扩展,我想在其中评估 javascript 调试会话的当前变量。这些变量通常在打开 VARIABLES 部分下的调试窗格时显示。请参阅随附的屏幕截图。

我想在用户右键单击编辑器时访问这些变量,但我不知道如何。

我当前的扩展设置是这样的:在 package.json 我已经注册了一个菜单贡献和一个命令:

"contributes": {
    "menus": {
        "editor/context": [{
            "command": "extension.showVariables",
            "group": "navigation"
        }]
    }
}

在我的 extension.ts 中,我注册了这样的命令:

export function activate(context: vscode.ExtensionContext) {

    let disposable = vscode.commands.registerCommand('extension.showVariables', () => {

        // TODO: let variables = vscode.debug.activeDebugSession.variables.toString();

        vscode.window.showInformationMessage(variables);
    });
}

我试图让他们通过 vscode.debug.activeDebugSession 但这里没有 API 变量。我还尝试为 vscode.debug.onDidReceiveDebugSessionCustomEvent 注册一个事件处理程序,但我不知道在哪里搜索调试变量。

甚至可以在 vs 扩展中访问这些变量,还是我需要实现自己的调试器?

我已经设法访问了局部变量,尽管这不是一个通用的解决方案——它可能只适用于单线程调试器。如果您有更好的方法,请回答或评论。

例如,调试器中断了一个具有局部变量 car.

的方法

要获取 car 的值,我在活动调试会话中使用 customRequest 方法:

const session = vscode.debug.activeDebugSession;
const response = await session.customRequest('evaluate', { expression: 'car', frameId: frameId });
const car = response.result;

为了获取 frameId,我使用了另一个调用 customRequest:

const session = vscode.debug.activeDebugSession;
const response = await session.customRequest('stackTrace', { threadId: 1 })
const frameId = response.stackFrames[0].id;

为了在我的扩展中获得一个真正的汽车对象(不是字符串表示),我在 evaluate 自定义请求中将 "JSON.stringify(car)" 作为表达式传递。然后,我可以使用 JSON.parse(response.result).

要获取所有作用域、堆栈和变量,请查看 Debug Session API and the specification of the DebugProtocol.

您必须直接使用调试适配器协议与调试适配器对话 vscode.debug.activeDebugSession.customRequest(command: string, args?: any) (Ref)

这个函数接收2个参数:command和args。查看 this resource to find all possible values of those parameters. One example is the 'evaluate' command that Michael Hilus uses in :

如果要在多线程调试会话中获取变量,则必须按此顺序执行这些请求

  1. Threads Request: 获取线程id
  2. StackTrace Request: 获取帧ID
  3. Scopes Request: 获取变量引用
  4. Variables Request: Finally, get the variable names with their values. If a variable is an object you might want to use Variables Request 再次使用具有对象值的变量的变量引用。

PS:在DAP规范中很难找到你想要的,所以这里有一个提示:

  1. 转到右侧菜单中的 'Types' 部分,找到您想要的内容。例如,断点。
  2. Ctrl+F 并搜索“: Breakpoint”
  3. 查看每个请求的响应部分中的所有匹配项。

variablesReference 的情况下,我必须搜索 variablesReference: number 才能在评估请求、范围(类型)和变量(也是类型)的响应中找到它。