-
Notifications
You must be signed in to change notification settings - Fork 188
/
mockDebug.ts
911 lines (763 loc) · 30.2 KB
/
mockDebug.ts
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
/*
* mockDebug.ts implements the Debug Adapter that "adapts" or translates the Debug Adapter Protocol (DAP) used by the client (e.g. VS Code)
* into requests and events of the real "execution engine" or "debugger" (here: class MockRuntime).
* When implementing your own debugger extension for VS Code, most of the work will go into the Debug Adapter.
* Since the Debug Adapter is independent from VS Code, it can be used in any client (IDE) supporting the Debug Adapter Protocol.
*
* The most important class of the Debug Adapter is the MockDebugSession which implements many DAP requests by talking to the MockRuntime.
*/
import {
Logger, logger,
LoggingDebugSession,
InitializedEvent, TerminatedEvent, StoppedEvent, BreakpointEvent, OutputEvent,
ProgressStartEvent, ProgressUpdateEvent, ProgressEndEvent, InvalidatedEvent,
Thread, StackFrame, Scope, Source, Handles, Breakpoint, MemoryEvent
} from '@vscode/debugadapter';
import { DebugProtocol } from '@vscode/debugprotocol';
import { basename } from 'path-browserify';
import { MockRuntime, IRuntimeBreakpoint, FileAccessor, RuntimeVariable, timeout, IRuntimeVariableType } from './mockRuntime';
import { Subject } from 'await-notify';
import * as base64 from 'base64-js';
/**
* This interface describes the mock-debug specific launch attributes
* (which are not part of the Debug Adapter Protocol).
* The schema for these attributes lives in the package.json of the mock-debug extension.
* The interface should always match this schema.
*/
interface ILaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
/** An absolute path to the "program" to debug. */
program: string;
/** Automatically stop target after launch. If not specified, target does not stop. */
stopOnEntry?: boolean;
/** enable logging the Debug Adapter Protocol */
trace?: boolean;
/** run without debugging */
noDebug?: boolean;
/** if specified, results in a simulated compile error in launch. */
compileError?: 'default' | 'show' | 'hide';
}
interface IAttachRequestArguments extends ILaunchRequestArguments { }
export class MockDebugSession extends LoggingDebugSession {
// we don't support multiple threads, so we can use a hardcoded ID for the default thread
private static threadID = 1;
// a Mock runtime (or debugger)
private _runtime: MockRuntime;
private _variableHandles = new Handles<'locals' | 'globals' | RuntimeVariable>();
private _configurationDone = new Subject();
private _cancellationTokens = new Map<number, boolean>();
private _reportProgress = false;
private _progressId = 10000;
private _cancelledProgressId: string | undefined = undefined;
private _isProgressCancellable = true;
private _valuesInHex = false;
private _useInvalidatedEvent = false;
private _addressesInHex = true;
/**
* Creates a new debug adapter that is used for one debug session.
* We configure the default implementation of a debug adapter here.
*/
public constructor(fileAccessor: FileAccessor) {
super("mock-debug.txt");
// this debugger uses zero-based lines and columns
this.setDebuggerLinesStartAt1(false);
this.setDebuggerColumnsStartAt1(false);
this._runtime = new MockRuntime(fileAccessor);
// setup event handlers
this._runtime.on('stopOnEntry', () => {
this.sendEvent(new StoppedEvent('entry', MockDebugSession.threadID));
});
this._runtime.on('stopOnStep', () => {
this.sendEvent(new StoppedEvent('step', MockDebugSession.threadID));
});
this._runtime.on('stopOnBreakpoint', () => {
this.sendEvent(new StoppedEvent('breakpoint', MockDebugSession.threadID));
});
this._runtime.on('stopOnDataBreakpoint', () => {
this.sendEvent(new StoppedEvent('data breakpoint', MockDebugSession.threadID));
});
this._runtime.on('stopOnInstructionBreakpoint', () => {
this.sendEvent(new StoppedEvent('instruction breakpoint', MockDebugSession.threadID));
});
this._runtime.on('stopOnException', (exception) => {
if (exception) {
this.sendEvent(new StoppedEvent(`exception(${exception})`, MockDebugSession.threadID));
} else {
this.sendEvent(new StoppedEvent('exception', MockDebugSession.threadID));
}
});
this._runtime.on('breakpointValidated', (bp: IRuntimeBreakpoint) => {
this.sendEvent(new BreakpointEvent('changed', { verified: bp.verified, id: bp.id } as DebugProtocol.Breakpoint));
});
this._runtime.on('output', (type, text, filePath, line, column) => {
let category: string;
switch(type) {
case 'prio': category = 'important'; break;
case 'out': category = 'stdout'; break;
case 'err': category = 'stderr'; break;
default: category = 'console'; break;
}
const e: DebugProtocol.OutputEvent = new OutputEvent(`${text}\n`, category);
if (text === 'start' || text === 'startCollapsed' || text === 'end') {
e.body.group = text;
e.body.output = `group-${text}\n`;
}
e.body.source = this.createSource(filePath);
e.body.line = this.convertDebuggerLineToClient(line);
e.body.column = this.convertDebuggerColumnToClient(column);
this.sendEvent(e);
});
this._runtime.on('end', () => {
this.sendEvent(new TerminatedEvent());
});
}
/**
* The 'initialize' request is the first request called by the frontend
* to interrogate the features the debug adapter provides.
*/
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
if (args.supportsProgressReporting) {
this._reportProgress = true;
}
if (args.supportsInvalidatedEvent) {
this._useInvalidatedEvent = true;
}
// build and return the capabilities of this debug adapter:
response.body = response.body || {};
// the adapter implements the configurationDone request.
response.body.supportsConfigurationDoneRequest = true;
// make VS Code use 'evaluate' when hovering over source
response.body.supportsEvaluateForHovers = true;
// make VS Code show a 'step back' button
response.body.supportsStepBack = true;
// make VS Code support data breakpoints
response.body.supportsDataBreakpoints = true;
// make VS Code support completion in REPL
response.body.supportsCompletionsRequest = true;
response.body.completionTriggerCharacters = [ ".", "[" ];
// make VS Code send cancel request
response.body.supportsCancelRequest = true;
// make VS Code send the breakpointLocations request
response.body.supportsBreakpointLocationsRequest = true;
// make VS Code provide "Step in Target" functionality
response.body.supportsStepInTargetsRequest = true;
// the adapter defines two exceptions filters, one with support for conditions.
response.body.supportsExceptionFilterOptions = true;
response.body.exceptionBreakpointFilters = [
{
filter: 'namedException',
label: "Named Exception",
description: `Break on named exceptions. Enter the exception's name as the Condition.`,
default: false,
supportsCondition: true,
conditionDescription: `Enter the exception's name`
},
{
filter: 'otherExceptions',
label: "Other Exceptions",
description: 'This is a other exception',
default: true,
supportsCondition: false
}
];
// make VS Code send exceptionInfo request
response.body.supportsExceptionInfoRequest = true;
// make VS Code send setVariable request
response.body.supportsSetVariable = true;
// make VS Code send setExpression request
response.body.supportsSetExpression = true;
// make VS Code send disassemble request
response.body.supportsDisassembleRequest = true;
response.body.supportsSteppingGranularity = true;
response.body.supportsInstructionBreakpoints = true;
// make VS Code able to read and write variable memory
response.body.supportsReadMemoryRequest = true;
response.body.supportsWriteMemoryRequest = true;
response.body.supportSuspendDebuggee = true;
response.body.supportTerminateDebuggee = true;
response.body.supportsFunctionBreakpoints = true;
response.body.supportsDelayedStackTraceLoading = true;
this.sendResponse(response);
// since this debug adapter can accept configuration requests like 'setBreakpoint' at any time,
// we request them early by sending an 'initializeRequest' to the frontend.
// The frontend will end the configuration sequence by calling 'configurationDone' request.
this.sendEvent(new InitializedEvent());
}
/**
* Called at the end of the configuration sequence.
* Indicates that all breakpoints etc. have been sent to the DA and that the 'launch' can start.
*/
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
super.configurationDoneRequest(response, args);
// notify the launchRequest that configuration has finished
this._configurationDone.notify();
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): void {
console.log(`disconnectRequest suspend: ${args.suspendDebuggee}, terminate: ${args.terminateDebuggee}`);
}
protected async attachRequest(response: DebugProtocol.AttachResponse, args: IAttachRequestArguments) {
return this.launchRequest(response, args);
}
protected async launchRequest(response: DebugProtocol.LaunchResponse, args: ILaunchRequestArguments) {
// make sure to 'Stop' the buffered logging if 'trace' is not set
logger.setup(args.trace ? Logger.LogLevel.Verbose : Logger.LogLevel.Stop, false);
// wait 1 second until configuration has finished (and configurationDoneRequest has been called)
await this._configurationDone.wait(1000);
// start the program in the runtime
await this._runtime.start(args.program, !!args.stopOnEntry, !args.noDebug);
if (args.compileError) {
// simulate a compile/build error in "launch" request:
// the error should not result in a modal dialog since 'showUser' is set to false.
// A missing 'showUser' should result in a modal dialog.
this.sendErrorResponse(response, {
id: 1001,
format: `compile error: some fake error.`,
showUser: args.compileError === 'show' ? true : (args.compileError === 'hide' ? false : undefined)
});
} else {
this.sendResponse(response);
}
}
protected setFunctionBreakPointsRequest(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments, request?: DebugProtocol.Request): void {
this.sendResponse(response);
}
protected async setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): Promise<void> {
const path = args.source.path as string;
const clientLines = args.lines || [];
// clear all breakpoints for this file
this._runtime.clearBreakpoints(path);
// set and verify breakpoint locations
const actualBreakpoints0 = clientLines.map(async l => {
const { verified, line, id } = await this._runtime.setBreakPoint(path, this.convertClientLineToDebugger(l));
const bp = new Breakpoint(verified, this.convertDebuggerLineToClient(line)) as DebugProtocol.Breakpoint;
bp.id = id;
return bp;
});
const actualBreakpoints = await Promise.all<DebugProtocol.Breakpoint>(actualBreakpoints0);
// send back the actual breakpoint positions
response.body = {
breakpoints: actualBreakpoints
};
this.sendResponse(response);
}
protected breakpointLocationsRequest(response: DebugProtocol.BreakpointLocationsResponse, args: DebugProtocol.BreakpointLocationsArguments, request?: DebugProtocol.Request): void {
if (args.source.path) {
const bps = this._runtime.getBreakpoints(args.source.path, this.convertClientLineToDebugger(args.line));
response.body = {
breakpoints: bps.map(col => {
return {
line: args.line,
column: this.convertDebuggerColumnToClient(col)
};
})
};
} else {
response.body = {
breakpoints: []
};
}
this.sendResponse(response);
}
protected async setExceptionBreakPointsRequest(response: DebugProtocol.SetExceptionBreakpointsResponse, args: DebugProtocol.SetExceptionBreakpointsArguments): Promise<void> {
let namedException: string | undefined = undefined;
let otherExceptions = false;
if (args.filterOptions) {
for (const filterOption of args.filterOptions) {
switch (filterOption.filterId) {
case 'namedException':
namedException = args.filterOptions[0].condition;
break;
case 'otherExceptions':
otherExceptions = true;
break;
}
}
}
if (args.filters) {
if (args.filters.indexOf('otherExceptions') >= 0) {
otherExceptions = true;
}
}
this._runtime.setExceptionsFilters(namedException, otherExceptions);
this.sendResponse(response);
}
protected exceptionInfoRequest(response: DebugProtocol.ExceptionInfoResponse, args: DebugProtocol.ExceptionInfoArguments) {
response.body = {
exceptionId: 'Exception ID',
description: 'This is a descriptive description of the exception.',
breakMode: 'always',
details: {
message: 'Message contained in the exception.',
typeName: 'Short type name of the exception object',
stackTrace: 'stack frame 1\nstack frame 2',
}
};
this.sendResponse(response);
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
// runtime supports no threads so just return a default thread.
response.body = {
threads: [
new Thread(MockDebugSession.threadID, "thread 1"),
new Thread(MockDebugSession.threadID + 1, "thread 2"),
]
};
this.sendResponse(response);
}
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
const startFrame = typeof args.startFrame === 'number' ? args.startFrame : 0;
const maxLevels = typeof args.levels === 'number' ? args.levels : 1000;
const endFrame = startFrame + maxLevels;
const stk = this._runtime.stack(startFrame, endFrame);
response.body = {
stackFrames: stk.frames.map((f, ix) => {
const sf: DebugProtocol.StackFrame = new StackFrame(f.index, f.name, this.createSource(f.file), this.convertDebuggerLineToClient(f.line));
if (typeof f.column === 'number') {
sf.column = this.convertDebuggerColumnToClient(f.column);
}
if (typeof f.instruction === 'number') {
const address = this.formatAddress(f.instruction);
sf.name = `${f.name} ${address}`;
sf.instructionPointerReference = address;
}
return sf;
}),
// 4 options for 'totalFrames':
//omit totalFrames property: // VS Code has to probe/guess. Should result in a max. of two requests
totalFrames: stk.count // stk.count is the correct size, should result in a max. of two requests
//totalFrames: 1000000 // not the correct size, should result in a max. of two requests
//totalFrames: endFrame + 20 // dynamically increases the size with every requested chunk, results in paging
};
this.sendResponse(response);
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
response.body = {
scopes: [
new Scope("Locals", this._variableHandles.create('locals'), false),
new Scope("Globals", this._variableHandles.create('globals'), true)
]
};
this.sendResponse(response);
}
protected async writeMemoryRequest(response: DebugProtocol.WriteMemoryResponse, { data, memoryReference, offset = 0 }: DebugProtocol.WriteMemoryArguments) {
const variable = this._variableHandles.get(Number(memoryReference));
if (typeof variable === 'object') {
const decoded = base64.toByteArray(data);
variable.setMemory(decoded, offset);
response.body = { bytesWritten: decoded.length };
} else {
response.body = { bytesWritten: 0 };
}
this.sendResponse(response);
this.sendEvent(new InvalidatedEvent(['variables']));
}
protected async readMemoryRequest(response: DebugProtocol.ReadMemoryResponse, { offset = 0, count, memoryReference }: DebugProtocol.ReadMemoryArguments) {
const variable = this._variableHandles.get(Number(memoryReference));
if (typeof variable === 'object' && variable.memory) {
const memory = variable.memory.subarray(
Math.min(offset, variable.memory.length),
Math.min(offset + count, variable.memory.length),
);
response.body = {
address: offset.toString(),
data: base64.fromByteArray(memory),
unreadableBytes: count - memory.length
};
} else {
response.body = {
address: offset.toString(),
data: '',
unreadableBytes: count
};
}
this.sendResponse(response);
}
protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments, request?: DebugProtocol.Request): Promise<void> {
let vs: RuntimeVariable[] = [];
const v = this._variableHandles.get(args.variablesReference);
if (v === 'locals') {
vs = this._runtime.getLocalVariables();
} else if (v === 'globals') {
if (request) {
this._cancellationTokens.set(request.seq, false);
vs = await this._runtime.getGlobalVariables(() => !!this._cancellationTokens.get(request.seq));
this._cancellationTokens.delete(request.seq);
} else {
vs = await this._runtime.getGlobalVariables();
}
} else if (v && Array.isArray(v.value)) {
vs = v.value;
}
response.body = {
variables: vs.map(v => this.convertFromRuntime(v))
};
this.sendResponse(response);
}
protected setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments): void {
const container = this._variableHandles.get(args.variablesReference);
const rv = container === 'locals'
? this._runtime.getLocalVariable(args.name)
: container instanceof RuntimeVariable && container.value instanceof Array
? container.value.find(v => v.name === args.name)
: undefined;
if (rv) {
rv.value = this.convertToRuntime(args.value);
response.body = this.convertFromRuntime(rv);
if (rv.memory && rv.reference) {
this.sendEvent(new MemoryEvent(String(rv.reference), 0, rv.memory.length));
}
}
this.sendResponse(response);
}
protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
this._runtime.continue(false);
this.sendResponse(response);
}
protected reverseContinueRequest(response: DebugProtocol.ReverseContinueResponse, args: DebugProtocol.ReverseContinueArguments): void {
this._runtime.continue(true);
this.sendResponse(response);
}
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this._runtime.step(args.granularity === 'instruction', false);
this.sendResponse(response);
}
protected stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void {
this._runtime.step(args.granularity === 'instruction', true);
this.sendResponse(response);
}
protected stepInTargetsRequest(response: DebugProtocol.StepInTargetsResponse, args: DebugProtocol.StepInTargetsArguments) {
const targets = this._runtime.getStepInTargets(args.frameId);
response.body = {
targets: targets.map(t => {
return { id: t.id, label: t.label };
})
};
this.sendResponse(response);
}
protected stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): void {
this._runtime.stepIn(args.targetId);
this.sendResponse(response);
}
protected stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): void {
this._runtime.stepOut();
this.sendResponse(response);
}
protected async evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): Promise<void> {
let reply: string | undefined;
let rv: RuntimeVariable | undefined;
switch (args.context) {
case 'repl':
// handle some REPL commands:
// 'evaluate' supports to create and delete breakpoints from the 'repl':
const matches = /new +([0-9]+)/.exec(args.expression);
if (matches && matches.length === 2) {
const mbp = await this._runtime.setBreakPoint(this._runtime.sourceFile, this.convertClientLineToDebugger(parseInt(matches[1])));
const bp = new Breakpoint(mbp.verified, this.convertDebuggerLineToClient(mbp.line), undefined, this.createSource(this._runtime.sourceFile)) as DebugProtocol.Breakpoint;
bp.id= mbp.id;
this.sendEvent(new BreakpointEvent('new', bp));
reply = `breakpoint created`;
} else {
const matches = /del +([0-9]+)/.exec(args.expression);
if (matches && matches.length === 2) {
const mbp = this._runtime.clearBreakPoint(this._runtime.sourceFile, this.convertClientLineToDebugger(parseInt(matches[1])));
if (mbp) {
const bp = new Breakpoint(false) as DebugProtocol.Breakpoint;
bp.id= mbp.id;
this.sendEvent(new BreakpointEvent('removed', bp));
reply = `breakpoint deleted`;
}
} else {
const matches = /progress/.exec(args.expression);
if (matches && matches.length === 1) {
if (this._reportProgress) {
reply = `progress started`;
this.progressSequence();
} else {
reply = `frontend doesn't support progress (capability 'supportsProgressReporting' not set)`;
}
}
}
}
// fall through
default:
if (args.expression.startsWith('$')) {
rv = this._runtime.getLocalVariable(args.expression.substr(1));
} else {
rv = new RuntimeVariable('eval', this.convertToRuntime(args.expression));
}
break;
}
if (rv) {
const v = this.convertFromRuntime(rv);
response.body = {
result: v.value,
type: v.type,
variablesReference: v.variablesReference,
presentationHint: v.presentationHint
};
} else {
response.body = {
result: reply ? reply : `evaluate(context: '${args.context}', '${args.expression}')`,
variablesReference: 0
};
}
this.sendResponse(response);
}
protected setExpressionRequest(response: DebugProtocol.SetExpressionResponse, args: DebugProtocol.SetExpressionArguments): void {
if (args.expression.startsWith('$')) {
const rv = this._runtime.getLocalVariable(args.expression.substr(1));
if (rv) {
rv.value = this.convertToRuntime(args.value);
response.body = this.convertFromRuntime(rv);
this.sendResponse(response);
} else {
this.sendErrorResponse(response, {
id: 1002,
format: `variable '{lexpr}' not found`,
variables: { lexpr: args.expression },
showUser: true
});
}
} else {
this.sendErrorResponse(response, {
id: 1003,
format: `'{lexpr}' not an assignable expression`,
variables: { lexpr: args.expression },
showUser: true
});
}
}
private async progressSequence() {
const ID = '' + this._progressId++;
await timeout(100);
const title = this._isProgressCancellable ? 'Cancellable operation' : 'Long running operation';
const startEvent: DebugProtocol.ProgressStartEvent = new ProgressStartEvent(ID, title);
startEvent.body.cancellable = this._isProgressCancellable;
this._isProgressCancellable = !this._isProgressCancellable;
this.sendEvent(startEvent);
this.sendEvent(new OutputEvent(`start progress: ${ID}\n`));
let endMessage = 'progress ended';
for (let i = 0; i < 100; i++) {
await timeout(500);
this.sendEvent(new ProgressUpdateEvent(ID, `progress: ${i}`));
if (this._cancelledProgressId === ID) {
endMessage = 'progress cancelled';
this._cancelledProgressId = undefined;
this.sendEvent(new OutputEvent(`cancel progress: ${ID}\n`));
break;
}
}
this.sendEvent(new ProgressEndEvent(ID, endMessage));
this.sendEvent(new OutputEvent(`end progress: ${ID}\n`));
this._cancelledProgressId = undefined;
}
protected dataBreakpointInfoRequest(response: DebugProtocol.DataBreakpointInfoResponse, args: DebugProtocol.DataBreakpointInfoArguments): void {
response.body = {
dataId: null,
description: "cannot break on data access",
accessTypes: undefined,
canPersist: false
};
if (args.variablesReference && args.name) {
const v = this._variableHandles.get(args.variablesReference);
if (v === 'globals') {
response.body.dataId = args.name;
response.body.description = args.name;
response.body.accessTypes = [ "write" ];
response.body.canPersist = true;
} else {
response.body.dataId = args.name;
response.body.description = args.name;
response.body.accessTypes = ["read", "write", "readWrite"];
response.body.canPersist = true;
}
}
this.sendResponse(response);
}
protected setDataBreakpointsRequest(response: DebugProtocol.SetDataBreakpointsResponse, args: DebugProtocol.SetDataBreakpointsArguments): void {
// clear all data breakpoints
this._runtime.clearAllDataBreakpoints();
response.body = {
breakpoints: []
};
for (const dbp of args.breakpoints) {
const ok = this._runtime.setDataBreakpoint(dbp.dataId, dbp.accessType || 'write');
response.body.breakpoints.push({
verified: ok
});
}
this.sendResponse(response);
}
protected completionsRequest(response: DebugProtocol.CompletionsResponse, args: DebugProtocol.CompletionsArguments): void {
response.body = {
targets: [
{
label: "item 10",
sortText: "10"
},
{
label: "item 1",
sortText: "01",
detail: "detail 1"
},
{
label: "item 2",
sortText: "02",
detail: "detail 2"
},
{
label: "array[]",
selectionStart: 6,
sortText: "03"
},
{
label: "func(arg)",
selectionStart: 5,
selectionLength: 3,
sortText: "04"
}
]
};
this.sendResponse(response);
}
protected cancelRequest(response: DebugProtocol.CancelResponse, args: DebugProtocol.CancelArguments) {
if (args.requestId) {
this._cancellationTokens.set(args.requestId, true);
}
if (args.progressId) {
this._cancelledProgressId= args.progressId;
}
}
protected disassembleRequest(response: DebugProtocol.DisassembleResponse, args: DebugProtocol.DisassembleArguments) {
const baseAddress = parseInt(args.memoryReference);
const offset = args.instructionOffset || 0;
const count = args.instructionCount;
const isHex = args.memoryReference.startsWith('0x');
const pad = isHex ? args.memoryReference.length-2 : args.memoryReference.length;
const loc = this.createSource(this._runtime.sourceFile);
let lastLine = -1;
const instructions = this._runtime.disassemble(baseAddress+offset, count).map(instruction => {
const address = instruction.address.toString(isHex ? 16 : 10).padStart(pad, '0');
const instr : DebugProtocol.DisassembledInstruction = {
address: isHex ? `0x${address}` : `${address}`,
instruction: instruction.instruction
};
// if instruction's source starts on a new line add the source to instruction
if (instruction.line !== undefined && lastLine !== instruction.line) {
lastLine = instruction.line;
instr.location = loc;
instr.line = this.convertDebuggerLineToClient(instruction.line);
}
return instr;
});
response.body = {
instructions: instructions
};
this.sendResponse(response);
}
protected setInstructionBreakpointsRequest(response: DebugProtocol.SetInstructionBreakpointsResponse, args: DebugProtocol.SetInstructionBreakpointsArguments) {
// clear all instruction breakpoints
this._runtime.clearInstructionBreakpoints();
// set instruction breakpoints
const breakpoints = args.breakpoints.map(ibp => {
const address = parseInt(ibp.instructionReference);
const offset = ibp.offset || 0;
return <DebugProtocol.Breakpoint>{
verified: this._runtime.setInstructionBreakpoint(address + offset)
};
});
response.body = {
breakpoints: breakpoints
};
this.sendResponse(response);
}
protected customRequest(command: string, response: DebugProtocol.Response, args: any) {
if (command === 'toggleFormatting') {
this._valuesInHex = ! this._valuesInHex;
if (this._useInvalidatedEvent) {
this.sendEvent(new InvalidatedEvent( ['variables'] ));
}
this.sendResponse(response);
} else {
super.customRequest(command, response, args);
}
}
//---- helpers
private convertToRuntime(value: string): IRuntimeVariableType {
value= value.trim();
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
if (value[0] === '\'' || value[0] === '"') {
return value.substr(1, value.length-2);
}
const n = parseFloat(value);
if (!isNaN(n)) {
return n;
}
return value;
}
private convertFromRuntime(v: RuntimeVariable): DebugProtocol.Variable {
let dapVariable: DebugProtocol.Variable = {
name: v.name,
value: '???',
type: typeof v.value,
variablesReference: 0,
evaluateName: '$' + v.name
};
if (v.name.indexOf('lazy') >= 0) {
// a "lazy" variable needs an additional click to retrieve its value
dapVariable.value = 'lazy var'; // placeholder value
v.reference ??= this._variableHandles.create(new RuntimeVariable('', [ new RuntimeVariable('', v.value) ]));
dapVariable.variablesReference = v.reference;
dapVariable.presentationHint = { lazy: true };
} else {
if (Array.isArray(v.value)) {
dapVariable.value = 'Object';
v.reference ??= this._variableHandles.create(v);
dapVariable.variablesReference = v.reference;
} else {
switch (typeof v.value) {
case 'number':
if (Math.round(v.value) === v.value) {
dapVariable.value = this.formatNumber(v.value);
(<any>dapVariable).__vscodeVariableMenuContext = 'simple'; // enable context menu contribution
dapVariable.type = 'integer';
} else {
dapVariable.value = v.value.toString();
dapVariable.type = 'float';
}
break;
case 'string':
dapVariable.value = `"${v.value}"`;
break;
case 'boolean':
dapVariable.value = v.value ? 'true' : 'false';
break;
default:
dapVariable.value = typeof v.value;
break;
}
}
}
if (v.memory) {
v.reference ??= this._variableHandles.create(v);
dapVariable.memoryReference = String(v.reference);
}
return dapVariable;
}
private formatAddress(x: number, pad = 8) {
return this._addressesInHex ? '0x' + x.toString(16).padStart(8, '0') : x.toString(10);
}
private formatNumber(x: number) {
return this._valuesInHex ? '0x' + x.toString(16) : x.toString(10);
}
private createSource(filePath: string): Source {
return new Source(basename(filePath), this.convertDebuggerPathToClient(filePath), undefined, undefined, 'mock-adapter-data');
}
}