forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathdebuggerVariables.ts
More file actions
309 lines (278 loc) · 12.2 KB
/
debuggerVariables.ts
File metadata and controls
309 lines (278 loc) · 12.2 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { inject, injectable, named } from 'inversify';
import { DebugAdapterTracker, Disposable, Event, EventEmitter } from 'vscode';
import { DebugProtocol } from 'vscode-debugprotocol';
import { IDebugService } from '../../common/application/types';
import { traceError } from '../../common/logger';
import { IConfigurationService, Resource } from '../../common/types';
import { sendTelemetryEvent } from '../../telemetry';
import { DataFrameLoading, Identifiers, Telemetry } from '../constants';
import { DebugLocationTracker } from '../debugLocationTracker';
import {
IConditionalJupyterVariables,
IJupyterDebugService,
IJupyterVariable,
IJupyterVariablesRequest,
IJupyterVariablesResponse,
INotebook
} from '../types';
const DataViewableTypes: Set<string> = new Set<string>(['DataFrame', 'list', 'dict', 'ndarray', 'Series']);
const KnownExcludedVariables = new Set<string>(['In', 'Out', 'exit', 'quit']);
@injectable()
export class DebuggerVariables extends DebugLocationTracker
implements IConditionalJupyterVariables, DebugAdapterTracker {
private refreshEventEmitter = new EventEmitter<void>();
private lastKnownVariables: IJupyterVariable[] = [];
private importedIntoKernel = new Set<string>();
private watchedNotebooks = new Map<string, Disposable[]>();
private debuggingStarted = false;
constructor(
@inject(IJupyterDebugService) @named(Identifiers.MULTIPLEXING_DEBUGSERVICE) private debugService: IDebugService,
@inject(IConfigurationService) private configService: IConfigurationService
) {
super(undefined);
}
public get refreshRequired(): Event<void> {
return this.refreshEventEmitter.event;
}
public get active(): boolean {
return this.debugService.activeDebugSession !== undefined && this.debuggingStarted;
}
// IJupyterVariables implementation
public async getVariables(
notebook: INotebook,
request: IJupyterVariablesRequest
): Promise<IJupyterVariablesResponse> {
// Listen to notebook events if we haven't already
this.watchNotebook(notebook);
const result: IJupyterVariablesResponse = {
executionCount: request.executionCount,
pageStartIndex: 0,
pageResponse: [],
totalCount: 0,
refreshCount: request.refreshCount
};
if (this.active) {
const startPos = request.startIndex ? request.startIndex : 0;
const chunkSize = request.pageSize ? request.pageSize : 100;
result.pageStartIndex = startPos;
// Do one at a time. All at once doesn't work as they all have to wait for each other anyway
for (let i = startPos; i < startPos + chunkSize && i < this.lastKnownVariables.length; i += 1) {
const fullVariable = !this.lastKnownVariables[i].truncated
? this.lastKnownVariables[i]
: await this.getFullVariable(this.lastKnownVariables[i], notebook);
this.lastKnownVariables[i] = fullVariable;
result.pageResponse.push(fullVariable);
}
result.totalCount = this.lastKnownVariables.length;
}
return result;
}
public async getMatchingVariable(notebook: INotebook, name: string): Promise<IJupyterVariable | undefined> {
if (this.active) {
// Note, full variable results isn't necessary for this call. It only really needs the variable value.
const result = this.lastKnownVariables.find((v) => v.name === name);
if (result) {
if (notebook.identity.fsPath.endsWith('.ipynb')) {
sendTelemetryEvent(Telemetry.RunByLineVariableHover);
}
}
return result;
}
}
public async getDataFrameInfo(targetVariable: IJupyterVariable, notebook: INotebook): Promise<IJupyterVariable> {
if (!this.active) {
// No active server just return the unchanged target variable
return targetVariable;
}
// Listen to notebook events if we haven't already
this.watchNotebook(notebook);
// See if we imported or not into the kernel our special function
await this.importDataFrameScripts(notebook);
// Then eval calling the main function with our target variable
const results = await this.evaluate(
`${DataFrameLoading.DataFrameInfoFunc}(${targetVariable.name})`,
// tslint:disable-next-line: no-any
(targetVariable as any).frameId
);
// Results should be the updated variable.
return results
? {
...targetVariable,
...JSON.parse(results.result.slice(1, -1))
}
: targetVariable;
}
public async getDataFrameRows(
targetVariable: IJupyterVariable,
notebook: INotebook,
start: number,
end: number
): Promise<{}> {
// Run the get dataframe rows script
if (!this.debugService.activeDebugSession || targetVariable.columns === undefined) {
// No active server just return no rows
return {};
}
// Listen to notebook events if we haven't already
this.watchNotebook(notebook);
// See if we imported or not into the kernel our special function
await this.importDataFrameScripts(notebook);
// Since the debugger splits up long requests, split this based on the number of items.
// Maximum 100 cells at a time or one row
// tslint:disable-next-line: no-any
let output: any;
const minnedEnd = Math.min(targetVariable.rowCount || 0, end);
const totalRowCount = end - start;
const cellsPerRow = targetVariable.columns!.length;
const chunkSize = Math.floor(Math.max(1, Math.min(100 / cellsPerRow, totalRowCount / cellsPerRow)));
for (let pos = start; pos < end; pos += chunkSize) {
const chunkEnd = Math.min(pos + chunkSize, minnedEnd);
const results = await this.evaluate(
`${DataFrameLoading.DataFrameRowFunc}(${targetVariable.name}, ${pos}, ${chunkEnd})`,
// tslint:disable-next-line: no-any
(targetVariable as any).frameId
);
const chunkResults = JSON.parse(results.result.slice(1, -1));
if (output && output.data) {
output = {
...output,
data: output.data.concat(chunkResults.data)
};
} else {
output = chunkResults;
}
}
// Results should be the rows.
return output;
}
// tslint:disable-next-line: no-any
public onDidSendMessage(message: any) {
super.onDidSendMessage(message);
// When the initialize response comes back, indicate we have started.
if (message.type === 'response' && message.command === 'initialize') {
this.debuggingStarted = true;
} else if (message.type === 'response' && message.command === 'variables' && message.body) {
// If using the interactive debugger, update our variables.
// tslint:disable-next-line: no-suspicious-comment
// TODO: Figure out what resource to use
this.updateVariables(undefined, message as DebugProtocol.VariablesResponse);
} else if (message.type === 'event' && message.event === 'terminated') {
// When the debugger exits, make sure the variables are cleared
this.lastKnownVariables = [];
this.topMostFrameId = 0;
this.debuggingStarted = false;
this.refreshEventEmitter.fire();
}
}
private watchNotebook(notebook: INotebook) {
const key = notebook.identity.toString();
if (!this.watchedNotebooks.has(key)) {
const disposables: Disposable[] = [];
disposables.push(notebook.onKernelChanged(this.resetImport.bind(this, key)));
disposables.push(notebook.onKernelRestarted(this.resetImport.bind(this, key)));
disposables.push(
notebook.onDisposed(() => {
this.resetImport(key);
disposables.forEach((d) => d.dispose());
this.watchedNotebooks.delete(key);
})
);
this.watchedNotebooks.set(key, disposables);
}
}
private resetImport(key: string) {
this.importedIntoKernel.delete(key);
}
// tslint:disable-next-line: no-any
private async evaluate(code: string, frameId?: number): Promise<any> {
if (this.debugService.activeDebugSession) {
const results = await this.debugService.activeDebugSession.customRequest('evaluate', {
expression: code,
frameId: this.topMostFrameId || frameId,
context: 'repl'
});
if (results && results.result !== 'None') {
return results;
} else {
traceError(`Cannot evaluate ${code}`);
return undefined;
}
}
throw Error('Debugger is not active, cannot evaluate.');
}
private async importDataFrameScripts(notebook: INotebook): Promise<void> {
try {
const key = notebook.identity.toString();
if (!this.importedIntoKernel.has(key)) {
await this.evaluate(DataFrameLoading.DataFrameSysImport);
await this.evaluate(DataFrameLoading.DataFrameInfoImport);
await this.evaluate(DataFrameLoading.DataFrameRowImport);
await this.evaluate(DataFrameLoading.VariableInfoImport);
this.importedIntoKernel.add(key);
}
} catch (exc) {
traceError('Error attempting to import in debugger', exc);
}
}
private async getFullVariable(variable: IJupyterVariable, notebook: INotebook): Promise<IJupyterVariable> {
// See if we imported or not into the kernel our special function
await this.importDataFrameScripts(notebook);
// Then eval calling the variable info function with our target variable
const results = await this.evaluate(
`${DataFrameLoading.VariableInfoFunc}(${variable.name})`,
// tslint:disable-next-line: no-any
(variable as any).frameId
);
if (results && results.result) {
// Results should be the updated variable.
return {
...variable,
truncated: false,
...JSON.parse(results.result.slice(1, -1))
};
} else {
// If no results, just return current value. Better than nothing.
return variable;
}
}
private updateVariables(resource: Resource, variablesResponse: DebugProtocol.VariablesResponse) {
const exclusionList = this.configService.getSettings(resource).datascience.variableExplorerExclude
? this.configService.getSettings().datascience.variableExplorerExclude?.split(';')
: [];
const allowedVariables = variablesResponse.body.variables.filter((v) => {
if (!v.name || !v.type || !v.value) {
return false;
}
if (exclusionList && exclusionList.includes(v.type)) {
return false;
}
if (v.name.startsWith('_')) {
return false;
}
if (KnownExcludedVariables.has(v.name)) {
return false;
}
if (v.type === 'NoneType') {
return false;
}
return true;
});
this.lastKnownVariables = allowedVariables.map((v) => {
return {
name: v.name,
type: v.type!,
count: 0,
shape: '',
size: 0,
supportsDataExplorer: DataViewableTypes.has(v.type || ''),
value: v.value,
truncated: true,
frameId: v.variablesReference
};
});
this.refreshEventEmitter.fire();
}
}