-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathdebuggingExecutor.ts
More file actions
355 lines (313 loc) · 12.7 KB
/
debuggingExecutor.ts
File metadata and controls
355 lines (313 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (c) Microsoft Corporation.
import * as vscode from 'vscode';
import { DebugState } from './debugState';
/**
* Interface for debugging execution operations
*/
export interface IDebuggingExecutor {
startDebugging(workingDirectory: string, config: vscode.DebugConfiguration): Promise<boolean>;
stopDebugging(session?: vscode.DebugSession): Promise<void>;
stepOver(): Promise<void>;
stepInto(): Promise<void>;
stepOut(): Promise<void>;
continue(): Promise<void>;
restart(): Promise<void>;
addBreakpoint(uri: vscode.Uri, line: number): Promise<void>;
removeBreakpoint(uri: vscode.Uri, line: number): Promise<void>;
getCurrentDebugState(numNextLines: number): Promise<DebugState>;
getVariables(frameId: number, scope?: 'local' | 'global' | 'all'): Promise<any>;
evaluateExpression(expression: string, frameId: number): Promise<any>;
getBreakpoints(): readonly vscode.Breakpoint[];
clearAllBreakpoints(): void;
hasActiveSession(): Promise<boolean>;
getActiveSession(): vscode.DebugSession | undefined;
}
/**
* Responsible for executing VS Code debugging commands and managing debug sessions
*/
export class DebuggingExecutor implements IDebuggingExecutor {
/**
* Start a debugging session
*/
public async startDebugging(
workingDirectory: string,
config: vscode.DebugConfiguration
): Promise<boolean> {
try {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(workingDirectory));
// Handle compound configurations - pass the name directly to VS Code
if ((config as any).__isCompound) {
const compoundName = (config as any).__compoundName;
return await vscode.debug.startDebugging(workspaceFolder, compoundName);
}
// Special handling for coreclr launch configurations (not attach)
// Attach configurations use processName/processId instead of program
if (config.type === 'coreclr' && config.request !== 'attach') {
// Open the specific test file instead of the workspace folder
const testFileUri = vscode.Uri.file(config.program);
await vscode.commands.executeCommand('vscode.open', testFileUri);
vscode.commands.executeCommand('testing.debugCurrentFile');
return true;
}
return await vscode.debug.startDebugging(workspaceFolder, config);
} catch (error) {
throw new Error(`Failed to start debugging: ${error}`);
}
}
/**
* Stop the debugging session
*/
public async stopDebugging(session?: vscode.DebugSession): Promise<void> {
try {
const activeSession = session || vscode.debug.activeDebugSession;
if (activeSession) {
await vscode.debug.stopDebugging(activeSession);
}
} catch (error) {
throw new Error(`Failed to stop debugging: ${error}`);
}
}
/**
* Execute step over command
*/
public async stepOver(): Promise<void> {
try {
await vscode.commands.executeCommand('workbench.action.debug.stepOver');
} catch (error) {
throw new Error(`Failed to step over: ${error}`);
}
}
/**
* Execute step into command
*/
public async stepInto(): Promise<void> {
try {
await vscode.commands.executeCommand('workbench.action.debug.stepInto');
} catch (error) {
throw new Error(`Failed to step into: ${error}`);
}
}
/**
* Execute step out command
*/
public async stepOut(): Promise<void> {
try {
await vscode.commands.executeCommand('workbench.action.debug.stepOut');
} catch (error) {
throw new Error(`Failed to step out: ${error}`);
}
}
/**
* Execute continue command
*/
public async continue(): Promise<void> {
try {
await vscode.commands.executeCommand('workbench.action.debug.continue');
} catch (error) {
throw new Error(`Failed to continue: ${error}`);
}
}
/**
* Execute restart command
*/
public async restart(): Promise<void> {
try {
await vscode.commands.executeCommand('workbench.action.debug.restart');
} catch (error) {
throw new Error(`Failed to restart: ${error}`);
}
}
/**
* Add a breakpoint at specified location
*/
public async addBreakpoint(uri: vscode.Uri, line: number): Promise<void> {
try {
const breakpoint = new vscode.SourceBreakpoint(
new vscode.Location(uri, new vscode.Position(line - 1, 0))
);
vscode.debug.addBreakpoints([breakpoint]);
} catch (error) {
throw new Error(`Failed to add breakpoint: ${error}`);
}
}
/**
* Remove a breakpoint from specified location
*/
public async removeBreakpoint(uri: vscode.Uri, line: number): Promise<void> {
try {
const breakpoints = vscode.debug.breakpoints.filter(bp => {
if (bp instanceof vscode.SourceBreakpoint) {
return bp.location.uri.toString() === uri.toString() &&
bp.location.range.start.line === line - 1;
}
return false;
});
if (breakpoints.length > 0) {
vscode.debug.removeBreakpoints(breakpoints);
}
} catch (error) {
throw new Error(`Failed to remove breakpoint: ${error}`);
}
}
/**
* Get current debugging state
*/
public async getCurrentDebugState(numNextLines: number = 3): Promise<DebugState> {
const state = new DebugState();
try {
const activeSession = vscode.debug.activeDebugSession;
if (activeSession) {
state.sessionActive = true;
const activeStackItem = vscode.debug.activeStackItem;
if (activeStackItem && 'frameId' in activeStackItem) {
state.updateContext(activeStackItem.frameId, activeStackItem.threadId);
// Extract frame name from stack frame
await this.extractFrameName(activeSession, activeStackItem.frameId, state);
// Get the active editor
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
const fileName = activeEditor.document.fileName.split(/[/\\]/).pop() || '';
const currentLine = activeEditor.selection.active.line + 1; // 1-based line number
const currentLineContent = activeEditor.document.lineAt(activeEditor.selection.active.line).text.trim();
// Get next lines
const nextLines = [];
for (let i = 1; i <= numNextLines; i++) {
if (activeEditor.selection.active.line + i < activeEditor.document.lineCount) {
nextLines.push(activeEditor.document.lineAt(activeEditor.selection.active.line + i).text.trim());
}
}
state.updateLocation(
activeEditor.document.fileName,
fileName,
currentLine,
currentLineContent,
nextLines
);
}
}
}
} catch (error) {
console.log('Unable to get debug state:', error);
}
return state;
}
/**
* Extract frame name from the current stack frame
*/
private async extractFrameName(session: vscode.DebugSession, frameId: number, state: DebugState): Promise<void> {
try {
// Get stack trace to extract frame name
const stackTraceResponse = await session.customRequest('stackTrace', {
threadId: state.threadId,
startFrame: 0,
levels: 1
});
if (stackTraceResponse?.stackFrames && stackTraceResponse.stackFrames.length > 0) {
const currentFrame = stackTraceResponse.stackFrames[0];
state.updateFrameName(currentFrame.name || null);
}
} catch (error) {
console.log('Unable to extract frame name:', error);
// Set empty frame name on error
state.updateFrameName(null);
}
}
/**
* Get variables from the current debug context
*/
public async getVariables(frameId: number, scope?: 'local' | 'global' | 'all'): Promise<any> {
try {
const activeSession = vscode.debug.activeDebugSession;
if (!activeSession) {
throw new Error('No active debug session');
}
const response = await activeSession.customRequest('scopes', { frameId });
if (!response || !response.scopes || response.scopes.length === 0) {
return { scopes: [] };
}
const filteredScopes = response.scopes.filter((scopeItem: any) => {
if (scope === 'all') {return true;}
const scopeName = scopeItem.name.toLowerCase();
if (scope === 'local') {return scopeName.includes('local');}
if (scope === 'global') {return scopeName.includes('global');}
return true;
});
// Get variables for each scope
for (const scopeItem of filteredScopes) {
try {
const variablesResponse = await activeSession.customRequest('variables', {
variablesReference: scopeItem.variablesReference
});
scopeItem.variables = variablesResponse.variables || [];
} catch (scopeError) {
scopeItem.variables = [];
scopeItem.error = scopeError;
}
}
return { scopes: filteredScopes };
} catch (error) {
throw new Error(`Failed to get variables: ${error}`);
}
}
/**
* Evaluate an expression in the current debug context
*/
public async evaluateExpression(expression: string, frameId: number): Promise<any> {
try {
const activeSession = vscode.debug.activeDebugSession;
if (!activeSession) {
throw new Error('No active debug session');
}
const response = await activeSession.customRequest('evaluate', {
expression: expression,
frameId: frameId,
context: 'repl'
});
return response;
} catch (error) {
throw new Error(`Failed to evaluate expression: ${error}`);
}
}
/**
* Get all active breakpoints
*/
public getBreakpoints(): readonly vscode.Breakpoint[] {
return vscode.debug.breakpoints;
}
/**
* Clear all breakpoints
*/
public clearAllBreakpoints(): void {
const breakpoints = vscode.debug.breakpoints;
if (breakpoints.length > 0) {
vscode.debug.removeBreakpoints(breakpoints);
}
}
/**
* Check if there's an active debug session that is ready for debugging operations
*/
public async hasActiveSession(): Promise<boolean> {
// Quick check first - no session at all
if (!vscode.debug.activeDebugSession) {
return false;
}
try {
// Get the current debug state and check if it has location information
// This is the most reliable way to determine if the debugger is truly ready
const debugState = await this.getCurrentDebugState();
// A session is ready when it has location info (file name and line number)
// This means the debugger has attached and we can see where we are in the code
return debugState.sessionActive && debugState.hasLocationInfo();
} catch (error) {
// Any error means session isn't ready (e.g., Python still initializing)
console.log('Session readiness check failed:', error);
return false;
}
}
/**
* Get the active debug session
*/
public getActiveSession(): vscode.DebugSession | undefined {
return vscode.debug.activeDebugSession;
}
}