-
Notifications
You must be signed in to change notification settings - Fork 180
/
mockRuntime.ts
618 lines (515 loc) · 15.5 KB
/
mockRuntime.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { EventEmitter } from 'events';
export interface FileAccessor {
readFile(path: string): Promise<string>;
}
export interface IRuntimeBreakpoint {
id: number;
line: number;
verified: boolean;
}
interface IRuntimeStepInTargets {
id: number;
label: string;
}
interface IRuntimeStackFrame {
index: number;
name: string;
file: string;
line: number;
column?: number;
instruction?: number;
}
interface IRuntimeStack {
count: number;
frames: IRuntimeStackFrame[];
}
interface RuntimeDisassembledInstruction {
address: number;
instruction: string;
}
export type IRuntimeVariableType = number | boolean | string | IRuntimeVariable[];
export interface IRuntimeVariable {
name: string;
value: IRuntimeVariableType;
}
interface Word {
name: string;
index: number
}
export function timeout(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* A Mock runtime with minimal debugger functionality.
*/
export class MockRuntime extends EventEmitter {
// the initial (and one and only) file we are 'debugging'
private _sourceFile: string = '';
public get sourceFile() {
return this._sourceFile;
}
private variables = new Map<string, IRuntimeVariable>();
// the contents (= lines) of the one and only file
private sourceLines: string[] = [];
private instructions: Word[] = [];
private starts: number[] = [];
private ends: number[] = [];
// This is the next line that will be 'executed'
private _currentLine = 0;
private get currentLine() {
return this._currentLine;
}
private set currentLine(x) {
this._currentLine = x;
this.instruction = this.starts[x];
}
private currentColumn: number | undefined;
// This is the next instruction that will be 'executed'
public instruction= 0;
// maps from sourceFile to array of IRuntimeBreakpoint
private breakPoints = new Map<string, IRuntimeBreakpoint[]>();
// all instruction breakpoint addresses
private instructionBreakpoints = new Set<number>();
// since we want to send breakpoint events, we will assign an id to every event
// so that the frontend can match events with breakpoints.
private breakpointId = 1;
private breakAddresses = new Map<string, string>();
private namedException: string | undefined;
private otherExceptions = false;
constructor(private fileAccessor: FileAccessor) {
super();
}
/**
* Start executing the given program.
*/
public async start(program: string, stopOnEntry: boolean, debug: boolean): Promise<void> {
await this.loadSource(program);
if (debug) {
await this.verifyBreakpoints(this._sourceFile);
if (stopOnEntry) {
this.findNextStatement(false, 'stopOnEntry');
} else {
// we just start to run until we hit a breakpoint, an exception, or the end
this.continue(false);
}
} else {
this.continue(false);
}
}
/**
* Continue execution to the end/beginning.
*/
public continue(reverse: boolean) {
while (!this.executeLine(this.currentLine, reverse)) {
if (this.updateCurrentLine(reverse)) {
break;
}
if (this.findNextStatement(reverse)) {
break;
}
}
}
/**
* Step to the next/previous non empty line.
*/
public step(instruction: boolean, reverse: boolean) {
if (instruction) {
if (reverse) {
this.instruction--;
} else {
this.instruction++;
}
this.sendEvent('stopOnStep');
} else {
if (!this.executeLine(this.currentLine, reverse)) {
if (!this.updateCurrentLine(reverse)) {
this.findNextStatement(reverse, 'stopOnStep');
}
}
}
}
private updateCurrentLine(reverse: boolean): boolean {
if (reverse) {
if (this.currentLine > 0) {
this.currentLine--;
} else {
// no more lines: stop at first line
this.currentLine = 0;
this.currentColumn = undefined;
this.sendEvent('stopOnEntry');
return true;
}
} else {
if (this.currentLine < this.sourceLines.length-1) {
this.currentLine++;
} else {
// no more lines: run to end
this.currentColumn = undefined;
this.sendEvent('end');
return true;
}
}
return false;
}
/**
* "Step into" for Mock debug means: go to next character
*/
public stepIn(targetId: number | undefined) {
if (typeof targetId === 'number') {
this.currentColumn = targetId;
this.sendEvent('stopOnStep');
} else {
if (typeof this.currentColumn === 'number') {
if (this.currentColumn <= this.sourceLines[this.currentLine].length) {
this.currentColumn += 1;
}
} else {
this.currentColumn = 1;
}
this.sendEvent('stopOnStep');
}
}
/**
* "Step out" for Mock debug means: go to previous character
*/
public stepOut() {
if (typeof this.currentColumn === 'number') {
this.currentColumn -= 1;
if (this.currentColumn === 0) {
this.currentColumn = undefined;
}
}
this.sendEvent('stopOnStep');
}
public getStepInTargets(frameId: number): IRuntimeStepInTargets[] {
const line = this.getLine();
const words = this.getWords(line);
// return nothing if frameId is out of range
if (frameId < 0 || frameId >= words.length) {
return [];
}
const { name, index } = words[frameId];
// make every character of the frame a potential "step in" target
return name.split('').map((c, ix) => {
return {
id: index + ix,
label: `target: ${c}`
};
});
}
/**
* Returns a fake 'stacktrace' where every 'stackframe' is a word from the current line.
*/
public stack(startFrame: number, endFrame: number): IRuntimeStack {
const line = this.getLine();
const words = this.getWords(line);
words.push({ name: 'BOTTOM', index: -1 }); // add a sentinel so that the stack is never empty...
// if the line contains the word 'disassembly' we support to "disassemble" the line by adding an 'instruction' property to the stackframe
const instruction = line.indexOf('disassembly') >= 0 ? this.instruction : undefined;
const column = typeof this.currentColumn === 'number' ? this.currentColumn : undefined;
const frames: IRuntimeStackFrame[] = [];
// every word of the current line becomes a stack frame.
for (let i = startFrame; i < Math.min(endFrame, words.length); i++) {
const stackFrame: IRuntimeStackFrame = {
index: i,
name: `${words[i].name}(${i})`, // use a word of the line as the stackframe name
file: this._sourceFile,
line: this.currentLine,
column: column, // words[i].index
instruction: instruction
};
frames.push(stackFrame);
}
return {
frames: frames,
count: words.length
};
}
/*
* Determine possible column breakpoint positions for the given line.
* Here we return the start location of words with more than 8 characters.
*/
public getBreakpoints(path: string, line: number): number[] {
return this.getWords(this.getLine(line)).filter(w => w.name.length > 8).map(w => w.index);
}
/*
* Set breakpoint in file with given line.
*/
public async setBreakPoint(path: string, line: number): Promise<IRuntimeBreakpoint> {
const bp: IRuntimeBreakpoint = { verified: false, line, id: this.breakpointId++ };
let bps = this.breakPoints.get(path);
if (!bps) {
bps = new Array<IRuntimeBreakpoint>();
this.breakPoints.set(path, bps);
}
bps.push(bp);
await this.verifyBreakpoints(path);
return bp;
}
/*
* Clear breakpoint in file with given line.
*/
public clearBreakPoint(path: string, line: number): IRuntimeBreakpoint | undefined {
const bps = this.breakPoints.get(path);
if (bps) {
const index = bps.findIndex(bp => bp.line === line);
if (index >= 0) {
const bp = bps[index];
bps.splice(index, 1);
return bp;
}
}
return undefined;
}
public clearBreakpoints(path: string): void {
this.breakPoints.delete(path);
}
public setDataBreakpoint(address: string, accessType: 'read' | 'write' | 'readWrite'): boolean {
const x = accessType === 'readWrite' ? 'read write' : accessType;
const t = this.breakAddresses.get(address);
if (t) {
if (t !== x) {
this.breakAddresses.set(address, 'read write');
}
} else {
this.breakAddresses.set(address, x);
}
return true;
}
public clearAllDataBreakpoints(): void {
this.breakAddresses.clear();
}
public setExceptionsFilters(namedException: string | undefined, otherExceptions: boolean): void {
this.namedException = namedException;
this.otherExceptions = otherExceptions;
}
public setInstructionBreakpoint(address: number): boolean {
this.instructionBreakpoints.add(address);
return true;
}
public clearInstructionBreakpoints(): void {
this.instructionBreakpoints.clear();
}
public async getGlobalVariables(cancellationToken?: () => boolean ): Promise<IRuntimeVariable[]> {
let a: IRuntimeVariable[] = [];
for (let i = 0; i < 10; i++) {
a.push({
name: `global_${i}`,
value: i
});
if (cancellationToken && cancellationToken()) {
break;
}
await timeout(1000);
}
return a;
}
public getLocalVariables(): IRuntimeVariable[] {
return Array.from(this.variables, ([name, value]) => value);
}
public getLocalVariable(name: string): IRuntimeVariable | undefined {
return this.variables.get(name);
}
/**
* Return words of the given address range as "instructions"
*/
public disassemble(address: number, instructionCount: number): RuntimeDisassembledInstruction[] {
const instructions: RuntimeDisassembledInstruction[] = [];
for (let a = address; a < address + instructionCount; a++) {
instructions.push({
address: a,
instruction: (a >= 0 && a < this.instructions.length) ? this.instructions[a].name : 'nop'
});
}
return instructions;
}
// private methods
private getLine(line?: number): string {
return this.sourceLines[line === undefined ? this.currentLine : line].trim();
}
private getWords(line: string): Word[] {
// break line into words
const WORD_REGEXP = /[a-z]+/ig;
const words: Word[] = [];
let match: RegExpExecArray | null;
while (match = WORD_REGEXP.exec(line)) {
words.push({ name: match[0], index: match.index });
}
return words;
}
private async loadSource(file: string): Promise<void> {
if (this._sourceFile !== file) {
this._sourceFile = file;
const contents = await this.fileAccessor.readFile(file);
this.sourceLines = contents.split(/\r?\n/);
this.instructions = [];
for (let line of this.sourceLines) {
this.starts.push(this.instructions.length);
const words = this.getWords(line);
for (let word of words) {
this.instructions.push(word);
}
this.ends.push(this.instructions.length);
}
}
}
/**
* return true on stop
*/
private findNextStatement(reverse: boolean, stepEvent?: string): boolean {
for (let ln = this.currentLine; reverse ? ln >= 0 : ln < this.sourceLines.length; reverse ? ln-- : ln++) {
// is there a source breakpoint?
const breakpoints = this.breakPoints.get(this._sourceFile);
if (breakpoints) {
const bps = breakpoints.filter(bp => bp.line === ln);
if (bps.length > 0) {
// send 'stopped' event
this.sendEvent('stopOnBreakpoint');
// the following shows the use of 'breakpoint' events to update properties of a breakpoint in the UI
// if breakpoint is not yet verified, verify it now and send a 'breakpoint' update event
if (!bps[0].verified) {
bps[0].verified = true;
this.sendEvent('breakpointValidated', bps[0]);
}
this.currentLine = ln;
return true;
}
}
const line = this.getLine(ln);
if (line.length > 0) {
this.currentLine = ln;
break;
}
}
if (stepEvent) {
this.sendEvent(stepEvent);
return true;
}
return false;
}
/**
* "execute a line" of the readme markdown.
* Returns true if execution sent out a stopped event and needs to stop.
*/
private executeLine(ln: number, reverse: boolean): boolean {
// first "execute" the instructions associated with this line and potentially hit instruction breakpoints
while (reverse ? this.instruction >= this.starts[ln] : this.instruction < this.ends[ln]) {
reverse ? this.instruction-- : this.instruction++;
if (this.instructionBreakpoints.has(this.instruction)) {
this.sendEvent('stopOnInstructionBreakpoint');
return true;
}
}
const line = this.getLine(ln);
// find variable accesses
let reg0 = /\$([a-z][a-z0-9]*)(=(false|true|[0-9]+(\.[0-9]+)?|\".*\"|\{.*\}))?/ig;
let matches0: RegExpExecArray | null;
while (matches0 = reg0.exec(line)) {
if (matches0.length === 5) {
let access: string | undefined;
const name = matches0[1];
const value = matches0[3];
let v: IRuntimeVariable = { name, value };
if (value && value.length > 0) {
if (value === 'true') {
v.value = true;
} else if (value === 'false') {
v.value = false;
} else if (value[0] === '"') {
v.value = value.substr(1, value.length-2);
} else if (value[0] === '{') {
v.value = [ {
name: 'fBool',
value: true
}, {
name: 'fInteger',
value: 123
}, {
name: 'fString',
value: 'hello'
} ];
} else {
v.value = parseFloat(value);
}
if (this.variables.has(name)) {
// the first write access to a variable is the "declaration" and not a "write access"
access = 'write';
}
this.variables.set(name, v);
} else {
if (this.variables.has(name)) {
// variable must exist in order to trigger a read access
access = 'read';
}
}
const accessType = this.breakAddresses.get(name);
if (access && accessType && accessType.indexOf(access) >= 0) {
this.sendEvent('stopOnDataBreakpoint', access);
return true;
}
}
}
// if 'log(...)' found in source -> send argument to debug console
const matches = /log\((.*)\)/.exec(line);
if (matches && matches.length === 2) {
this.sendEvent('output', matches[1], this._sourceFile, ln, matches.index);
}
// if pattern 'exception(...)' found in source -> throw named exception
const matches2 = /exception\((.*)\)/.exec(line);
if (matches2 && matches2.length === 2) {
const exception = matches2[1].trim();
if (this.namedException === exception) {
this.sendEvent('stopOnException', exception);
return true;
} else {
if (this.otherExceptions) {
this.sendEvent('stopOnException', undefined);
return true;
}
}
} else {
// if word 'exception' found in source -> throw exception
if (line.indexOf('exception') >= 0) {
if (this.otherExceptions) {
this.sendEvent('stopOnException', undefined);
return true;
}
}
}
// nothing interesting found -> continue
return false;
}
private async verifyBreakpoints(path: string): Promise<void> {
const bps = this.breakPoints.get(path);
if (bps) {
await this.loadSource(path);
bps.forEach(bp => {
if (!bp.verified && bp.line < this.sourceLines.length) {
const srcLine = this.getLine(bp.line);
// if a line is empty or starts with '+' we don't allow to set a breakpoint but move the breakpoint down
if (srcLine.length === 0 || srcLine.indexOf('+') === 0) {
bp.line++;
}
// if a line starts with '-' we don't allow to set a breakpoint but move the breakpoint up
if (srcLine.indexOf('-') === 0) {
bp.line--;
}
// don't set 'verified' to true if the line contains the word 'lazy'
// in this case the breakpoint will be verified 'lazy' after hitting it once.
if (srcLine.indexOf('lazy') < 0) {
bp.verified = true;
this.sendEvent('breakpointValidated', bp);
}
}
});
}
}
private sendEvent(event: string, ... args: any[]): void {
setImmediate(() => {
this.emit(event, ...args);
});
}
}