debugSession.ts 35.3 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

I
isidor 已提交
6
import { URI } from 'vs/base/common/uri';
7
import * as resources from 'vs/base/common/resources';
I
isidor 已提交
8 9 10
import * as platform from 'vs/base/common/platform';
import severity from 'vs/base/common/severity';
import { Event, Emitter } from 'vs/base/common/event';
I
isidor 已提交
11
import { Position, IPosition } from 'vs/editor/common/core/position';
I
isidor 已提交
12
import * as aria from 'vs/base/browser/ui/aria/aria';
13
import { IDebugSession, IConfig, IThread, IRawModelUpdate, IDebugService, IRawStoppedDetails, State, LoadedSourceEvent, IFunctionBreakpoint, IExceptionBreakpoint, IBreakpoint, IExceptionInfo, AdapterEndEvent, IDebugger, VIEWLET_ID, IDebugConfiguration, IReplElement, IStackFrame, IExpression, IReplElementSource, IDataBreakpoint, IDebugSessionOptions } from 'vs/workbench/contrib/debug/common/debug';
14
import { Source } from 'vs/workbench/contrib/debug/common/debugSource';
15
import { mixin } from 'vs/base/common/objects';
16
import { Thread, ExpressionContainer, DebugModel } from 'vs/workbench/contrib/debug/common/debugModel';
A
Andre Weinand 已提交
17
import { RawDebugSession } from 'vs/workbench/contrib/debug/browser/rawDebugSession';
18
import { IProductService } from 'vs/platform/product/common/productService';
I
isidor 已提交
19
import { IWorkspaceFolder, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
I
isidor 已提交
20
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
21
import { RunOnceScheduler, Queue } from 'vs/base/common/async';
I
isidor 已提交
22
import { generateUuid } from 'vs/base/common/uuid';
23
import { IHostService } from 'vs/workbench/services/host/browser/host';
24
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
I
isidor 已提交
25
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
A
Andre Weinand 已提交
26
import { normalizeDriveLetter } from 'vs/base/common/labels';
I
isidor 已提交
27 28
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
29
import { ReplModel } from 'vs/workbench/contrib/debug/common/replModel';
30
import { IOpenerService } from 'vs/platform/opener/common/opener';
31
import { variableSetEmitter } from 'vs/workbench/contrib/debug/browser/variablesView';
I
isidor 已提交
32
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
I
isidor 已提交
33
import { distinct } from 'vs/base/common/arrays';
I
isidor 已提交
34
import { INotificationService } from 'vs/platform/notification/common/notification';
I
isidor 已提交
35
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
I
isidor 已提交
36
import { localize } from 'vs/nls';
I
isidor 已提交
37

38
export class DebugSession implements IDebugSession {
39 40

	private _subId: string | undefined;
I
isidor 已提交
41
	private raw: RawDebugSession | undefined;
I
isidor 已提交
42
	private initialized = false;
43
	private _options: IDebugSessionOptions;
A
Andre Weinand 已提交
44

I
isidor 已提交
45 46
	private sources = new Map<string, Source>();
	private threads = new Map<number, Thread>();
I
isidor 已提交
47
	private cancellationMap = new Map<number, CancellationTokenSource[]>();
I
isidor 已提交
48
	private rawListeners: IDisposable[] = [];
I
isidor 已提交
49
	private fetchThreadsScheduler: RunOnceScheduler | undefined;
50
	private repl: ReplModel;
A
Andre Weinand 已提交
51

52
	private readonly _onDidChangeState = new Emitter<void>();
A
Andre Weinand 已提交
53 54
	private readonly _onDidEndAdapter = new Emitter<AdapterEndEvent>();

I
isidor 已提交
55
	private readonly _onDidLoadedSource = new Emitter<LoadedSourceEvent>();
A
Andre Weinand 已提交
56
	private readonly _onDidCustomEvent = new Emitter<DebugProtocol.Event>();
57
	private readonly _onDidProgressStart = new Emitter<DebugProtocol.ProgressStartEvent>();
I
isidor 已提交
58
	private readonly _onDidProgressUpdate = new Emitter<DebugProtocol.ProgressUpdateEvent>();
59
	private readonly _onDidProgressEnd = new Emitter<DebugProtocol.ProgressEndEvent>();
A
Andre Weinand 已提交
60

I
isidor 已提交
61
	private readonly _onDidChangeREPLElements = new Emitter<void>();
62

63 64 65
	private name: string | undefined;
	private readonly _onDidChangeName = new Emitter<string>();

I
isidor 已提交
66
	constructor(
67
		private id: string,
I
isidor 已提交
68
		private _configuration: { resolved: IConfig, unresolved: IConfig | undefined },
I
isidor 已提交
69
		public root: IWorkspaceFolder | undefined,
70
		private model: DebugModel,
71
		options: IDebugSessionOptions | undefined,
72 73
		@IDebugService private readonly debugService: IDebugService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
74
		@IHostService private readonly hostService: IHostService,
75 76
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IViewletService private readonly viewletService: IViewletService,
A
Andre Weinand 已提交
77
		@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
A
Andre Weinand 已提交
78
		@IProductService private readonly productService: IProductService,
79
		@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService,
I
isidor 已提交
80
		@IOpenerService private readonly openerService: IOpenerService,
I
isidor 已提交
81 82
		@INotificationService private readonly notificationService: INotificationService,
		@ILifecycleService lifecycleService: ILifecycleService
I
isidor 已提交
83
	) {
84 85 86 87 88 89
		this._options = options || {};
		if (this.hasSeparateRepl()) {
			this.repl = new ReplModel();
		} else {
			this.repl = (this.parentSession as DebugSession).repl;
		}
I
isidor 已提交
90 91 92

		const toDispose: IDisposable[] = [];
		toDispose.push(this.repl.onDidChangeElements(() => this._onDidChangeREPLElements.fire()));
A
Alex Dima 已提交
93 94 95 96 97 98
		if (lifecycleService) {
			toDispose.push(lifecycleService.onShutdown(() => {
				this.shutdown();
				dispose(toDispose);
			}));
		}
99 100
	}

A
Andre Weinand 已提交
101 102 103 104
	getId(): string {
		return this.id;
	}

105 106 107 108 109 110 111 112
	setSubId(subId: string | undefined) {
		this._subId = subId;
	}

	get subId(): string | undefined {
		return this._subId;
	}

I
isidor 已提交
113
	get configuration(): IConfig {
114 115 116
		return this._configuration.resolved;
	}

I
isidor 已提交
117
	get unresolvedConfiguration(): IConfig | undefined {
118 119 120
		return this._configuration.unresolved;
	}

I
isidor 已提交
121
	get parentSession(): IDebugSession | undefined {
122
		return this._options.parentSession;
I
isidor 已提交
123 124
	}

I
isidor 已提交
125
	setConfiguration(configuration: { resolved: IConfig, unresolved: IConfig | undefined }) {
I
isidor 已提交
126 127 128
		this._configuration = configuration;
	}

I
isidor 已提交
129 130
	getLabel(): string {
		const includeRoot = this.workspaceContextService.getWorkspace().folders.length > 1;
131 132 133 134 135 136 137
		const name = this.name || this.configuration.name;
		return includeRoot && this.root ? `${name} (${resources.basenameOrAuthority(this.root.uri)})` : name;
	}

	setName(name: string): void {
		this.name = name;
		this._onDidChangeName.fire(name);
I
isidor 已提交
138 139 140
	}

	get state(): State {
I
isidor 已提交
141 142 143
		if (!this.initialized) {
			return State.Initializing;
		}
144 145 146 147
		if (!this.raw) {
			return State.Inactive;
		}

148
		const focusedThread = this.debugService.getViewModel().focusedThread;
I
isidor 已提交
149
		if (focusedThread && focusedThread.session === this) {
150 151 152 153
			return focusedThread.stopped ? State.Stopped : State.Running;
		}
		if (this.getAllThreads().some(t => t.stopped)) {
			return State.Stopped;
A
Andre Weinand 已提交
154
		}
155

156
		return State.Running;
A
Andre Weinand 已提交
157 158 159
	}

	get capabilities(): DebugProtocol.Capabilities {
160
		return this.raw ? this.raw.capabilities : Object.create(null);
161 162
	}

A
Andre Weinand 已提交
163
	//---- events
164
	get onDidChangeState(): Event<void> {
I
isidor 已提交
165
		return this._onDidChangeState.event;
166 167
	}

A
Andre Weinand 已提交
168 169 170 171
	get onDidEndAdapter(): Event<AdapterEndEvent> {
		return this._onDidEndAdapter.event;
	}

I
isidor 已提交
172 173 174 175
	get onDidChangeReplElements(): Event<void> {
		return this._onDidChangeREPLElements.event;
	}

176 177 178 179
	get onDidChangeName(): Event<string> {
		return this._onDidChangeName.event;
	}

A
Andre Weinand 已提交
180 181
	//---- DAP events

A
Andre Weinand 已提交
182
	get onDidCustomEvent(): Event<DebugProtocol.Event> {
I
isidor 已提交
183 184 185
		return this._onDidCustomEvent.event;
	}

A
Andre Weinand 已提交
186 187
	get onDidLoadedSource(): Event<LoadedSourceEvent> {
		return this._onDidLoadedSource.event;
188 189
	}

190 191 192 193
	get onDidProgressStart(): Event<DebugProtocol.ProgressStartEvent> {
		return this._onDidProgressStart.event;
	}

I
isidor 已提交
194 195 196 197
	get onDidProgressUpdate(): Event<DebugProtocol.ProgressUpdateEvent> {
		return this._onDidProgressUpdate.event;
	}

198 199 200 201
	get onDidProgressEnd(): Event<DebugProtocol.ProgressEndEvent> {
		return this._onDidProgressEnd.event;
	}

A
Andre Weinand 已提交
202 203 204 205 206
	//---- DAP requests

	/**
	 * create and initialize a new debug adapter for this session
	 */
I
isidor 已提交
207
	async initialize(dbgr: IDebugger): Promise<void> {
208

209
		if (this.raw) {
210
			// if there was already a connection make sure to remove old listeners
211
			this.shutdown();
I
isidor 已提交
212
		}
213

I
isidor 已提交
214 215 216
		try {
			const customTelemetryService = await dbgr.getCustomTelemetryService();
			const debugAdapter = await dbgr.createDebugAdapter(this);
I
isidor 已提交
217
			this.raw = new RawDebugSession(debugAdapter, dbgr, this.telemetryService, customTelemetryService, this.extensionHostDebugService, this.openerService, this.notificationService);
I
isidor 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230

			await this.raw.start();
			this.registerListeners();
			await this.raw!.initialize({
				clientID: 'vscode',
				clientName: this.productService.nameLong,
				adapterID: this.configuration.type,
				pathFormat: 'path',
				linesStartAt1: true,
				columnsStartAt1: true,
				supportsVariableType: true, // #8858
				supportsVariablePaging: true, // #9537
				supportsRunInTerminalRequest: true, // #10574
231 232
				locale: platform.locale,
				supportsProgressReporting: true // #92253
I
isidor 已提交
233
			});
I
isidor 已提交
234

I
isidor 已提交
235 236
			this.initialized = true;
			this._onDidChangeState.fire();
I
isidor 已提交
237
			this.model.setExceptionBreakpoints((this.raw && this.raw.capabilities.exceptionBreakpointFilters) || []);
I
isidor 已提交
238 239 240
		} catch (err) {
			this.initialized = true;
			this._onDidChangeState.fire();
I
isidor 已提交
241
			this.shutdown();
I
isidor 已提交
242 243
			throw err;
		}
I
isidor 已提交
244 245
	}

A
Andre Weinand 已提交
246 247 248
	/**
	 * launch or attach to the debuggee
	 */
I
isidor 已提交
249 250
	async launchOrAttach(config: IConfig): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
251
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'launch or attach'));
I
isidor 已提交
252
		}
A
Andre Weinand 已提交
253

I
isidor 已提交
254 255
		// __sessionID only used for EH debugging (but we add it always for now...)
		config.__sessionId = this.getId();
I
isidor 已提交
256 257 258 259 260 261
		try {
			await this.raw.launchOrAttach(config);
		} catch (err) {
			this.shutdown();
			throw err;
		}
A
Andre Weinand 已提交
262 263 264 265 266
	}

	/**
	 * end the current debug adapter session
	 */
I
isidor 已提交
267 268
	async terminate(restart = false): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
269
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'terminate'));
I
isidor 已提交
270 271 272 273 274 275 276
		}

		this.cancelAllRequests();
		if (this.raw.capabilities.supportsTerminateRequest && this._configuration.resolved.request === 'launch') {
			await this.raw.terminate(restart);
		} else {
			await this.raw.disconnect(restart);
A
Andre Weinand 已提交
277 278 279 280 281 282
		}
	}

	/**
	 * end the current debug adapter session
	 */
I
isidor 已提交
283 284
	async disconnect(restart = false): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
285
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'disconnect'));
A
Andre Weinand 已提交
286
		}
I
isidor 已提交
287 288 289

		this.cancelAllRequests();
		await this.raw.disconnect(restart);
A
Andre Weinand 已提交
290 291 292 293 294
	}

	/**
	 * restart debug adapter session
	 */
I
isidor 已提交
295 296
	async restart(): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
297
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'restart'));
A
Andre Weinand 已提交
298 299
		}

I
isidor 已提交
300 301 302
		this.cancelAllRequests();
		await this.raw.restart();
	}
A
Andre Weinand 已提交
303

I
isidor 已提交
304
	async sendBreakpoints(modelUri: URI, breakpointsToSend: IBreakpoint[], sourceModified: boolean): Promise<void> {
305
		if (!this.raw) {
I
isidor 已提交
306
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'breakpoints'));
A
Andre Weinand 已提交
307 308
		}

309
		if (!this.raw.readyForBreakpoints) {
I
isidor 已提交
310
			return Promise.resolve(undefined);
A
Andre Weinand 已提交
311 312
		}

I
isidor 已提交
313
		const rawSource = this.getRawSource(modelUri);
A
Andre Weinand 已提交
314 315 316 317
		if (breakpointsToSend.length && !rawSource.adapterData) {
			rawSource.adapterData = breakpointsToSend[0].adapterData;
		}
		// Normalize all drive letters going out from vscode to debug adapters so we are consistent with our resolving #43959
I
isidor 已提交
318 319 320
		if (rawSource.path) {
			rawSource.path = normalizeDriveLetter(rawSource.path);
		}
A
Andre Weinand 已提交
321

I
isidor 已提交
322
		const response = await this.raw.setBreakpoints({
A
Andre Weinand 已提交
323
			source: rawSource,
324 325
			lines: breakpointsToSend.map(bp => bp.sessionAgnosticData.lineNumber),
			breakpoints: breakpointsToSend.map(bp => ({ line: bp.sessionAgnosticData.lineNumber, column: bp.sessionAgnosticData.column, condition: bp.condition, hitCondition: bp.hitCondition, logMessage: bp.logMessage })),
A
Andre Weinand 已提交
326
			sourceModified
I
isidor 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339
		});
		if (response && response.body) {
			const data = new Map<string, DebugProtocol.Breakpoint>();
			for (let i = 0; i < breakpointsToSend.length; i++) {
				data.set(breakpointsToSend[i].getId(), response.body.breakpoints[i]);
			}

			this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
		}
	}

	async sendFunctionBreakpoints(fbpts: IFunctionBreakpoint[]): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
340
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'function breakpoints'));
I
isidor 已提交
341 342 343 344
		}

		if (this.raw.readyForBreakpoints) {
			const response = await this.raw.setFunctionBreakpoints({ breakpoints: fbpts });
A
Andre Weinand 已提交
345
			if (response && response.body) {
I
isidor 已提交
346
				const data = new Map<string, DebugProtocol.Breakpoint>();
I
isidor 已提交
347 348
				for (let i = 0; i < fbpts.length; i++) {
					data.set(fbpts[i].getId(), response.body.breakpoints[i]);
A
Andre Weinand 已提交
349
				}
350
				this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
A
Andre Weinand 已提交
351
			}
I
isidor 已提交
352
		}
A
Andre Weinand 已提交
353 354
	}

I
isidor 已提交
355 356
	async sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
357
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'exception breakpoints'));
A
Andre Weinand 已提交
358
		}
359

I
isidor 已提交
360 361 362
		if (this.raw.readyForBreakpoints) {
			await this.raw.setExceptionBreakpoints({ filters: exbpts.map(exb => exb.filter) });
		}
A
Andre Weinand 已提交
363 364
	}

I
isidor 已提交
365 366
	async dataBreakpointInfo(name: string, variablesReference?: number): Promise<{ dataId: string | null, description: string, canPersist?: boolean }> {
		if (!this.raw) {
I
isidor 已提交
367
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'data breakpoints info'));
A
Andre Weinand 已提交
368
		}
I
isidor 已提交
369
		if (!this.raw.readyForBreakpoints) {
I
isidor 已提交
370
			throw new Error(localize('sessionNotReadyForBreakpoints', "Session is not ready for breakpoints"));
I
isidor 已提交
371 372 373 374
		}

		const response = await this.raw.dataBreakpointInfo({ name, variablesReference });
		return response.body;
A
Andre Weinand 已提交
375 376
	}

I
isidor 已提交
377 378
	async sendDataBreakpoints(dataBreakpoints: IDataBreakpoint[]): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
379
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'data breakpoints'));
I
isidor 已提交
380 381
		}

I
isidor 已提交
382 383 384 385 386 387 388 389
		if (this.raw.readyForBreakpoints) {
			const response = await this.raw.setDataBreakpoints({ breakpoints: dataBreakpoints });
			if (response && response.body) {
				const data = new Map<string, DebugProtocol.Breakpoint>();
				for (let i = 0; i < dataBreakpoints.length; i++) {
					data.set(dataBreakpoints[i].getId(), response.body.breakpoints[i]);
				}
				this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
390 391 392 393
			}
		}
	}

I
isidor 已提交
394
	async breakpointsLocations(uri: URI, lineNumber: number): Promise<IPosition[]> {
I
isidor 已提交
395
		if (!this.raw) {
I
isidor 已提交
396
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'breakpoints locations'));
I
isidor 已提交
397
		}
I
isidor 已提交
398

I
isidor 已提交
399 400 401 402
		const source = this.getRawSource(uri);
		const response = await this.raw.breakpointLocations({ source, line: lineNumber });
		if (!response.body || !response.body.breakpoints) {
			return [];
I
isidor 已提交
403
		}
I
isidor 已提交
404 405 406 407

		const positions = response.body.breakpoints.map(bp => ({ lineNumber: bp.line, column: bp.column || 1 }));

		return distinct(positions, p => `${p.lineNumber}:${p.column}`);
I
isidor 已提交
408 409
	}

410
	customRequest(request: string, args: any): Promise<DebugProtocol.Response> {
I
isidor 已提交
411
		if (!this.raw) {
I
isidor 已提交
412
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", request));
A
Andre Weinand 已提交
413
		}
I
isidor 已提交
414 415

		return this.raw.custom(request, args);
A
Andre Weinand 已提交
416 417
	}

418
	stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse> {
I
isidor 已提交
419
		if (!this.raw) {
I
isidor 已提交
420
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'stackTrace'));
A
Andre Weinand 已提交
421
		}
I
isidor 已提交
422 423 424

		const token = this.getNewCancellationToken(threadId);
		return this.raw.stackTrace({ threadId, startFrame, levels }, token);
A
Andre Weinand 已提交
425 426
	}

I
isidor 已提交
427 428
	async exceptionInfo(threadId: number): Promise<IExceptionInfo | undefined> {
		if (!this.raw) {
I
isidor 已提交
429
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'exceptionInfo'));
I
isidor 已提交
430 431 432 433 434 435 436 437 438 439
		}

		const response = await this.raw.exceptionInfo({ threadId });
		if (response) {
			return {
				id: response.body.exceptionId,
				description: response.body.description,
				breakMode: response.body.breakMode,
				details: response.body.details
			};
A
Andre Weinand 已提交
440
		}
I
isidor 已提交
441 442

		return undefined;
A
Andre Weinand 已提交
443 444
	}

I
isidor 已提交
445
	scopes(frameId: number, threadId: number): Promise<DebugProtocol.ScopesResponse> {
I
isidor 已提交
446
		if (!this.raw) {
I
isidor 已提交
447
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'scopes'));
A
Andre Weinand 已提交
448
		}
I
isidor 已提交
449 450 451

		const token = this.getNewCancellationToken(threadId);
		return this.raw.scopes({ frameId }, token);
A
Andre Weinand 已提交
452 453
	}

I
isidor 已提交
454
	variables(variablesReference: number, threadId: number | undefined, filter: 'indexed' | 'named' | undefined, start: number | undefined, count: number | undefined): Promise<DebugProtocol.VariablesResponse> {
I
isidor 已提交
455
		if (!this.raw) {
I
isidor 已提交
456
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'variables'));
A
Andre Weinand 已提交
457
		}
I
isidor 已提交
458 459 460

		const token = threadId ? this.getNewCancellationToken(threadId) : undefined;
		return this.raw.variables({ variablesReference, filter, start, count }, token);
A
Andre Weinand 已提交
461 462
	}

463
	evaluate(expression: string, frameId: number, context?: string): Promise<DebugProtocol.EvaluateResponse> {
I
isidor 已提交
464
		if (!this.raw) {
I
isidor 已提交
465
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'evaluate'));
A
Andre Weinand 已提交
466
		}
I
isidor 已提交
467 468

		return this.raw.evaluate({ expression, frameId, context });
A
Andre Weinand 已提交
469 470
	}

I
isidor 已提交
471 472
	async restartFrame(frameId: number, threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
473
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'restartFrame'));
A
Andre Weinand 已提交
474
		}
I
isidor 已提交
475 476

		await this.raw.restartFrame({ frameId }, threadId);
A
Andre Weinand 已提交
477 478
	}

I
isidor 已提交
479 480
	async next(threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
481
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'next'));
A
Andre Weinand 已提交
482
		}
I
isidor 已提交
483 484

		await this.raw.next({ threadId });
A
Andre Weinand 已提交
485 486
	}

I
isidor 已提交
487 488
	async stepIn(threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
489
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'stepIn'));
A
Andre Weinand 已提交
490
		}
I
isidor 已提交
491 492

		await this.raw.stepIn({ threadId });
A
Andre Weinand 已提交
493 494
	}

I
isidor 已提交
495 496
	async stepOut(threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
497
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'stepOut'));
A
Andre Weinand 已提交
498
		}
I
isidor 已提交
499 500

		await this.raw.stepOut({ threadId });
A
Andre Weinand 已提交
501 502
	}

I
isidor 已提交
503 504
	async stepBack(threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
505
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'stepBack'));
A
Andre Weinand 已提交
506
		}
I
isidor 已提交
507 508

		await this.raw.stepBack({ threadId });
A
Andre Weinand 已提交
509 510
	}

I
isidor 已提交
511 512
	async continue(threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
513
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'continue'));
A
Andre Weinand 已提交
514
		}
I
isidor 已提交
515 516

		await this.raw.continue({ threadId });
A
Andre Weinand 已提交
517 518
	}

I
isidor 已提交
519 520
	async reverseContinue(threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
521
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'reverse continue'));
A
Andre Weinand 已提交
522
		}
I
isidor 已提交
523 524

		await this.raw.reverseContinue({ threadId });
A
Andre Weinand 已提交
525 526
	}

I
isidor 已提交
527 528
	async pause(threadId: number): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
529
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'pause'));
A
Andre Weinand 已提交
530
		}
I
isidor 已提交
531 532

		await this.raw.pause({ threadId });
A
Andre Weinand 已提交
533 534
	}

I
isidor 已提交
535 536
	async terminateThreads(threadIds?: number[]): Promise<void> {
		if (!this.raw) {
I
isidor 已提交
537
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'terminateThreads'));
A
Andre Weinand 已提交
538
		}
I
isidor 已提交
539 540

		await this.raw.terminateThreads({ threadIds });
A
Andre Weinand 已提交
541 542
	}

543
	setVariable(variablesReference: number, name: string, value: string): Promise<DebugProtocol.SetVariableResponse> {
I
isidor 已提交
544
		if (!this.raw) {
I
isidor 已提交
545
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'setVariable'));
A
Andre Weinand 已提交
546
		}
I
isidor 已提交
547 548

		return this.raw.setVariable({ variablesReference, name, value });
A
Andre Weinand 已提交
549 550
	}

I
isidor 已提交
551
	gotoTargets(source: DebugProtocol.Source, line: number, column?: number): Promise<DebugProtocol.GotoTargetsResponse> {
I
isidor 已提交
552
		if (!this.raw) {
I
isidor 已提交
553
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'gotoTargets'));
I
isidor 已提交
554
		}
I
isidor 已提交
555 556

		return this.raw.gotoTargets({ source, line, column });
I
isidor 已提交
557 558 559
	}

	goto(threadId: number, targetId: number): Promise<DebugProtocol.GotoResponse> {
I
isidor 已提交
560
		if (!this.raw) {
I
isidor 已提交
561
			throw new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'goto'));
I
isidor 已提交
562
		}
I
isidor 已提交
563 564

		return this.raw.goto({ threadId, targetId });
I
isidor 已提交
565 566
	}

567
	loadSource(resource: URI): Promise<DebugProtocol.SourceResponse> {
568
		if (!this.raw) {
I
isidor 已提交
569
			return Promise.reject(new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'loadSource')));
A
Andre Weinand 已提交
570 571 572 573 574 575 576 577
		}

		const source = this.getSourceForUri(resource);
		let rawSource: DebugProtocol.Source;
		if (source) {
			rawSource = source.raw;
		} else {
			// create a Source
578 579
			const data = Source.getEncodedDebugData(resource);
			rawSource = { path: data.path, sourceReference: data.sourceReference };
A
Andre Weinand 已提交
580 581
		}

I
isidor 已提交
582
		return this.raw.source({ sourceReference: rawSource.sourceReference || 0, source: rawSource });
A
Andre Weinand 已提交
583 584
	}

I
isidor 已提交
585 586
	async getLoadedSources(): Promise<Source[]> {
		if (!this.raw) {
I
isidor 已提交
587
			return Promise.reject(new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'getLoadedSources')));
I
isidor 已提交
588 589 590 591 592 593 594
		}

		const response = await this.raw.loadedSources({});
		if (response.body && response.body.sources) {
			return response.body.sources.map(src => this.getSource(src));
		} else {
			return [];
A
Andre Weinand 已提交
595 596 597
		}
	}

598
	async completions(frameId: number | undefined, text: string, position: Position, overwriteBefore: number, token: CancellationToken): Promise<DebugProtocol.CompletionsResponse> {
I
isidor 已提交
599
		if (!this.raw) {
I
isidor 已提交
600
			return Promise.reject(new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'completions')));
I
isidor 已提交
601 602
		}

603
		return this.raw.completions({
I
isidor 已提交
604 605 606 607 608
			frameId,
			text,
			column: position.column,
			line: position.lineNumber,
		}, token);
A
Andre Weinand 已提交
609 610
	}

I
isidor 已提交
611 612 613 614 615 616 617 618
	async cancel(progressId: string): Promise<DebugProtocol.CancelResponse> {
		if (!this.raw) {
			return Promise.reject(new Error(localize('noDebugAdapter', "No debug adapter, can not send '{0}'", 'cancel')));
		}

		return this.raw.cancel({ progressId });
	}

A
Andre Weinand 已提交
619 620
	//---- threads

I
isidor 已提交
621
	getThread(threadId: number): Thread | undefined {
A
Andre Weinand 已提交
622 623 624 625 626 627 628 629 630
		return this.threads.get(threadId);
	}

	getAllThreads(): IThread[] {
		const result: IThread[] = [];
		this.threads.forEach(t => result.push(t));
		return result;
	}

631
	clearThreads(removeThreads: boolean, reference: number | undefined = undefined): void {
A
Andre Weinand 已提交
632
		if (reference !== undefined && reference !== null) {
633 634
			const thread = this.threads.get(reference);
			if (thread) {
A
Andre Weinand 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
				thread.clearCallStack();
				thread.stoppedDetails = undefined;
				thread.stopped = false;

				if (removeThreads) {
					this.threads.delete(reference);
				}
			}
		} else {
			this.threads.forEach(thread => {
				thread.clearCallStack();
				thread.stoppedDetails = undefined;
				thread.stopped = false;
			});

			if (removeThreads) {
				this.threads.clear();
				ExpressionContainer.allValues.clear();
			}
		}
	}

	rawUpdate(data: IRawModelUpdate): void {
658
		const threadIds: number[] = [];
I
isidor 已提交
659
		data.threads.forEach(thread => {
660
			threadIds.push(thread.id);
I
isidor 已提交
661 662 663 664 665 666 667 668 669
			if (!this.threads.has(thread.id)) {
				// A new thread came in, initialize it.
				this.threads.set(thread.id, new Thread(this, thread.name, thread.id));
			} else if (thread.name) {
				// Just the thread name got updated #18244
				const oldThread = this.threads.get(thread.id);
				if (oldThread) {
					oldThread.name = thread.name;
				}
I
isidor 已提交
670
			}
I
isidor 已提交
671
		});
672 673 674 675 676 677
		this.threads.forEach(t => {
			// Remove all old threads which are no longer part of the update #75980
			if (threadIds.indexOf(t.threadId) === -1) {
				this.threads.delete(t.threadId);
			}
		});
A
Andre Weinand 已提交
678

I
isidor 已提交
679 680
		const stoppedDetails = data.stoppedDetails;
		if (stoppedDetails) {
A
Andre Weinand 已提交
681 682
			// Set the availability of the threads' callstacks depending on
			// whether the thread is stopped or not
I
isidor 已提交
683
			if (stoppedDetails.allThreadsStopped) {
A
Andre Weinand 已提交
684
				this.threads.forEach(thread => {
I
isidor 已提交
685
					thread.stoppedDetails = thread.threadId === stoppedDetails.threadId ? stoppedDetails : { reason: undefined };
A
Andre Weinand 已提交
686 687 688
					thread.stopped = true;
					thread.clearCallStack();
				});
I
isidor 已提交
689
			} else {
I
isidor 已提交
690
				const thread = typeof stoppedDetails.threadId === 'number' ? this.threads.get(stoppedDetails.threadId) : undefined;
I
isidor 已提交
691 692
				if (thread) {
					// One thread is stopped, only update that thread.
I
isidor 已提交
693
					thread.stoppedDetails = stoppedDetails;
I
isidor 已提交
694 695 696
					thread.clearCallStack();
					thread.stopped = true;
				}
A
Andre Weinand 已提交
697 698 699 700
			}
		}
	}

I
isidor 已提交
701 702 703
	private async fetchThreads(stoppedDetails?: IRawStoppedDetails): Promise<void> {
		if (this.raw) {
			const response = await this.raw.threads();
A
Andre Weinand 已提交
704
			if (response && response.body && response.body.threads) {
I
isidor 已提交
705 706 707 708
				this.model.rawUpdate({
					sessionId: this.getId(),
					threads: response.body.threads,
					stoppedDetails
A
Andre Weinand 已提交
709 710
				});
			}
I
isidor 已提交
711
		}
A
Andre Weinand 已提交
712 713
	}

714 715 716 717 718
	initializeForTest(raw: RawDebugSession): void {
		this.raw = raw;
		this.registerListeners();
	}

A
Andre Weinand 已提交
719 720
	//---- private

I
isidor 已提交
721
	private registerListeners(): void {
I
isidor 已提交
722 723 724 725
		if (!this.raw) {
			return;
		}

I
isidor 已提交
726
		this.rawListeners.push(this.raw.onDidInitialize(async () => {
I
isidor 已提交
727
			aria.status(localize('debuggingStarted', "Debugging started."));
I
isidor 已提交
728
			const sendConfigurationDone = async () => {
729
				if (this.raw && this.raw.capabilities.supportsConfigurationDoneRequest) {
I
isidor 已提交
730 731 732
					try {
						await this.raw.configurationDone();
					} catch (e) {
I
isidor 已提交
733
						// Disconnect the debug session on configuration done error #10596
734 735
						if (this.raw) {
							this.raw.disconnect();
I
isidor 已提交
736
						}
I
isidor 已提交
737
					}
I
isidor 已提交
738
				}
739 740

				return undefined;
I
isidor 已提交
741 742 743
			};

			// Send all breakpoints
I
isidor 已提交
744 745
			try {
				await this.debugService.sendAllBreakpoints(this);
I
isidor 已提交
746
			} finally {
I
isidor 已提交
747
				await sendConfigurationDone();
I
isidor 已提交
748
				await this.fetchThreads();
I
isidor 已提交
749
			}
I
isidor 已提交
750 751
		}));

I
isidor 已提交
752 753 754 755 756 757 758 759 760 761 762 763 764
		this.rawListeners.push(this.raw.onDidStop(async event => {
			await this.fetchThreads(event.body);
			const thread = typeof event.body.threadId === 'number' ? this.getThread(event.body.threadId) : undefined;
			if (thread) {
				// Call fetch call stack twice, the first only return the top stack frame.
				// Second retrieves the rest of the call stack. For performance reasons #25605
				const promises = this.model.fetchCallStack(<Thread>thread);
				const focus = async () => {
					if (!event.body.preserveFocusHint && thread.getCallStack().length) {
						await this.debugService.focusStackFrame(undefined, thread);
						if (thread.stoppedDetails) {
							if (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {
								this.viewletService.openViewlet(VIEWLET_ID);
I
isidor 已提交
765
							}
766

I
isidor 已提交
767 768 769
							if (this.configurationService.getValue<IDebugConfiguration>('debug').focusWindowOnBreak) {
								this.hostService.focus();
							}
770
						}
I
isidor 已提交
771 772 773 774 775 776 777 778 779
					}
				};

				await promises.topCallStack;
				focus();
				await promises.wholeCallStack;
				if (!this.debugService.getViewModel().focusedStackFrame) {
					// The top stack frame can be deemphesized so try to focus again #68616
					focus();
I
isidor 已提交
780
				}
I
isidor 已提交
781 782
			}
			this._onDidChangeState.fire();
I
isidor 已提交
783 784
		}));

785
		this.rawListeners.push(this.raw.onDidThread(event => {
I
isidor 已提交
786 787 788 789
			if (event.body.reason === 'started') {
				// debounce to reduce threadsRequest frequency and improve performance
				if (!this.fetchThreadsScheduler) {
					this.fetchThreadsScheduler = new RunOnceScheduler(() => {
790
						this.fetchThreads();
I
isidor 已提交
791 792 793 794 795 796 797 798
					}, 100);
					this.rawListeners.push(this.fetchThreadsScheduler);
				}
				if (!this.fetchThreadsScheduler.isScheduled()) {
					this.fetchThreadsScheduler.schedule();
				}
			} else if (event.body.reason === 'exited') {
				this.model.clearThreads(this.getId(), true, event.body.threadId);
I
isidor 已提交
799 800 801 802 803 804
				const viewModel = this.debugService.getViewModel();
				const focusedThread = viewModel.focusedThread;
				if (focusedThread && event.body.threadId === focusedThread.threadId) {
					// De-focus the thread in case it was focused
					this.debugService.focusStackFrame(undefined, undefined, viewModel.focusedSession, false);
				}
I
isidor 已提交
805 806 807
			}
		}));

I
isidor 已提交
808
		this.rawListeners.push(this.raw.onDidTerminateDebugee(async event => {
I
isidor 已提交
809
			aria.status(localize('debuggingStopped', "Debugging stopped."));
I
isidor 已提交
810
			if (event.body && event.body.restart) {
I
isidor 已提交
811
				await this.debugService.restartSession(this, event.body.restart);
I
isidor 已提交
812
			} else if (this.raw) {
I
isidor 已提交
813
				await this.raw.disconnect();
I
isidor 已提交
814 815 816
			}
		}));

817
		this.rawListeners.push(this.raw.onDidContinued(event => {
I
isidor 已提交
818
			const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
I
isidor 已提交
819 820 821 822 823 824 825 826 827 828
			if (threadId) {
				const tokens = this.cancellationMap.get(threadId);
				this.cancellationMap.delete(threadId);
				if (tokens) {
					tokens.forEach(t => t.cancel());
				}
			} else {
				this.cancelAllRequests();
			}

I
isidor 已提交
829
			this.model.clearThreads(this.getId(), false, threadId);
830
			this._onDidChangeState.fire();
I
isidor 已提交
831 832
		}));

833
		const outputQueue = new Queue<void>();
I
isidor 已提交
834
		this.rawListeners.push(this.raw.onDidOutput(async event => {
835 836 837 838 839 840 841 842 843 844 845 846 847
			outputQueue.queue(async () => {
				if (!event.body || !this.raw) {
					return;
				}

				const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
				if (event.body.category === 'telemetry') {
					// only log telemetry events from debug adapter if the debug extension provided the telemetry key
					// and the user opted in telemetry
					if (this.raw.customTelemetryService && this.telemetryService.isOptedIn) {
						// __GDPR__TODO__ We're sending events in the name of the debug extension and we can not ensure that those are declared correctly.
						this.raw.customTelemetryService.publicLog(event.body.output, event.body.data);
					}
I
isidor 已提交
848

849
					return;
I
isidor 已提交
850 851
				}

852 853 854 855 856 857
				// Make sure to append output in the correct order by properly waiting on preivous promises #33822
				const source = event.body.source && event.body.line ? {
					lineNumber: event.body.line,
					column: event.body.column ? event.body.column : 1,
					source: this.getSource(event.body.source)
				} : undefined;
I
isidor 已提交
858

859 860 861
				if (event.body.group === 'start' || event.body.group === 'startCollapsed') {
					const expanded = event.body.group === 'start';
					this.repl.startGroup(event.body.output || '', expanded, source);
862 863
					return;
				}
864 865 866 867 868 869 870
				if (event.body.group === 'end') {
					this.repl.endGroup();
					if (!event.body.output) {
						// Only return if the end event does not have additional output in it
						return;
					}
				}
I
isidor 已提交
871

872 873 874 875 876 877 878 879
				if (event.body.variablesReference) {
					const container = new ExpressionContainer(this, undefined, event.body.variablesReference, generateUuid());
					await container.getChildren().then(children => {
						children.forEach(child => {
							// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
							(<any>child).name = null;
							this.appendToRepl(child, outputSeverity, source);
						});
I
isidor 已提交
880
					});
881 882 883 884
				} else if (typeof event.body.output === 'string') {
					this.appendToRepl(event.body.output, outputSeverity, source);
				}
			});
I
isidor 已提交
885 886
		}));

887
		this.rawListeners.push(this.raw.onDidBreakpoint(event => {
I
isidor 已提交
888
			const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
D
Dmitry Gozman 已提交
889 890
			const breakpoint = this.model.getBreakpoints().filter(bp => bp.getIdFromAdapter(this.getId()) === id).pop();
			const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.getIdFromAdapter(this.getId()) === id).pop();
I
isidor 已提交
891

I
isidor 已提交
892
			if (event.body.reason === 'new' && event.body.breakpoint.source && event.body.breakpoint.line) {
I
isidor 已提交
893 894 895 896 897 898 899
				const source = this.getSource(event.body.breakpoint.source);
				const bps = this.model.addBreakpoints(source.uri, [{
					column: event.body.breakpoint.column,
					enabled: true,
					lineNumber: event.body.breakpoint.line,
				}], false);
				if (bps.length === 1) {
I
isidor 已提交
900
					const data = new Map<string, DebugProtocol.Breakpoint>([[bps[0].getId(), event.body.breakpoint]]);
901
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
				}
			}

			if (event.body.reason === 'removed') {
				if (breakpoint) {
					this.model.removeBreakpoints([breakpoint]);
				}
				if (functionBreakpoint) {
					this.model.removeFunctionBreakpoints(functionBreakpoint.getId());
				}
			}

			if (event.body.reason === 'changed') {
				if (breakpoint) {
					if (!breakpoint.column) {
						event.body.breakpoint.column = undefined;
					}
I
isidor 已提交
919
					const data = new Map<string, DebugProtocol.Breakpoint>([[breakpoint.getId(), event.body.breakpoint]]);
920
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
921 922
				}
				if (functionBreakpoint) {
I
isidor 已提交
923
					const data = new Map<string, DebugProtocol.Breakpoint>([[functionBreakpoint.getId(), event.body.breakpoint]]);
924
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
925 926 927 928
				}
			}
		}));

929
		this.rawListeners.push(this.raw.onDidLoadedSource(event => {
I
isidor 已提交
930 931 932 933 934 935
			this._onDidLoadedSource.fire({
				reason: event.body.reason,
				source: this.getSource(event.body.source)
			});
		}));

936
		this.rawListeners.push(this.raw.onDidCustomEvent(event => {
I
isidor 已提交
937 938 939
			this._onDidCustomEvent.fire(event);
		}));

940 941 942
		this.rawListeners.push(this.raw.onDidProgressStart(event => {
			this._onDidProgressStart.fire(event);
		}));
I
isidor 已提交
943 944 945
		this.rawListeners.push(this.raw.onDidProgressUpdate(event => {
			this._onDidProgressUpdate.fire(event);
		}));
946 947 948 949
		this.rawListeners.push(this.raw.onDidProgressEnd(event => {
			this._onDidProgressEnd.fire(event);
		}));

950
		this.rawListeners.push(this.raw.onDidExitAdapter(event => {
I
isidor 已提交
951
			this.initialized = true;
952
			this.model.setBreakpointSessionData(this.getId(), this.capabilities, undefined);
I
isidor 已提交
953
			this.shutdown();
A
Andre Weinand 已提交
954
			this._onDidEndAdapter.fire(event);
955 956 957
		}));
	}

I
isidor 已提交
958 959
	// Disconnects and clears state. Session can be initialized again for a new connection.
	private shutdown(): void {
960
		dispose(this.rawListeners);
I
isidor 已提交
961
		if (this.raw) {
I
isidor 已提交
962 963
			this.raw.disconnect();
			this.raw.dispose();
I
isidor 已提交
964 965
			this.raw = undefined;
		}
I
isidor 已提交
966 967
		this.fetchThreadsScheduler = undefined;
		this.model.clearThreads(this.getId(), true);
968
		this._onDidChangeState.fire();
969 970 971 972
	}

	//---- sources

I
isidor 已提交
973
	getSourceForUri(uri: URI): Source | undefined {
I
isidor 已提交
974
		return this.sources.get(this.getUriKey(uri));
975 976
	}

I
isidor 已提交
977
	getSource(raw?: DebugProtocol.Source): Source {
978
		let source = new Source(raw, this.getId());
I
isidor 已提交
979
		const uriKey = this.getUriKey(source.uri);
A
Andre Weinand 已提交
980 981 982 983
		const found = this.sources.get(uriKey);
		if (found) {
			source = found;
			// merge attributes of new into existing
984 985 986 987 988 989
			source.raw = mixin(source.raw, raw);
			if (source.raw && raw) {
				// Always take the latest presentation hint from adapter #42139
				source.raw.presentationHint = raw.presentationHint;
			}
		} else {
I
isidor 已提交
990
			this.sources.set(uriKey, source);
991 992 993 994
		}

		return source;
	}
I
isidor 已提交
995

I
isidor 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005
	private getRawSource(uri: URI): DebugProtocol.Source {
		const source = this.getSourceForUri(uri);
		if (source) {
			return source.raw;
		} else {
			const data = Source.getEncodedDebugData(uri);
			return { name: data.name, path: data.path, sourceReference: data.sourceReference };
		}
	}

I
isidor 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	private getNewCancellationToken(threadId: number): CancellationToken {
		const tokenSource = new CancellationTokenSource();
		const tokens = this.cancellationMap.get(threadId) || [];
		tokens.push(tokenSource);
		this.cancellationMap.set(threadId, tokens);

		return tokenSource.token;
	}

	private cancelAllRequests(): void {
		this.cancellationMap.forEach(tokens => tokens.forEach(t => t.cancel()));
		this.cancellationMap.clear();
	}

I
isidor 已提交
1020
	private getUriKey(uri: URI): string {
A
Andre Weinand 已提交
1021
		// TODO: the following code does not make sense if uri originates from a different platform
I
isidor 已提交
1022 1023
		return platform.isLinux ? uri.toString() : uri.toString().toLowerCase();
	}
I
isidor 已提交
1024 1025 1026

	// REPL

I
isidor 已提交
1027
	getReplElements(): IReplElement[] {
1028 1029 1030
		return this.repl.getReplElements();
	}

1031 1032 1033 1034
	hasSeparateRepl(): boolean {
		return !this.parentSession || this._options.repl !== 'mergeWithParent';
	}

1035 1036
	removeReplExpressions(): void {
		this.repl.removeReplExpressions();
I
isidor 已提交
1037 1038
	}

1039
	async addReplExpression(stackFrame: IStackFrame | undefined, name: string): Promise<void> {
1040
		await this.repl.addReplExpression(this, stackFrame, name);
1041 1042
		// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
		variableSetEmitter.fire();
I
isidor 已提交
1043 1044
	}

1045
	appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void {
D
Dmitry Gozman 已提交
1046
		this.repl.appendToRepl(this, data, severity, source);
I
isidor 已提交
1047 1048
	}

1049
	logToRepl(sev: severity, args: any[], frame?: { uri: URI, line: number, column: number }) {
1050
		this.repl.logToRepl(this, sev, args, frame);
I
isidor 已提交
1051
	}
1052
}