Enable tslint with basic rules

Add tslint as a plugin to tsc, so that they will show up in vscode or
whatever editor people use.  I only enabled two basic rules that I think
are very useful, prefer-const and no-var-keyword.  Violations of these
rules were fixed with "tslint -p . --fix".  There was one unused
variable (in the isExpandable) function that I removed by hand.
This commit is contained in:
Simon Marchi 2018-07-17 18:19:37 -04:00
commit 1244e4133c
15 changed files with 209 additions and 196 deletions

View file

@ -117,7 +117,7 @@ export class VariableObject {
}
public toProtocolVariable(): DebugProtocol.Variable {
let res: DebugProtocol.Variable = {
const res: DebugProtocol.Variable = {
name: this.exp,
evaluateName: this.name,
value: (this.value === void 0) ? "<unknown>" : this.value,

View file

@ -12,7 +12,6 @@ const numberRegex = /^\d+(\.\d+)?/;
const pointerCombineChar = ".";
export function isExpandable(value: string): number {
let primitive: any;
let match;
value = value.trim();
if (value.length == 0) return 0;
@ -31,13 +30,13 @@ export function isExpandable(value: string): number {
}
export function expandValue(variableCreate: Function, value: string, root: string = "", extra: any = undefined): any {
let parseCString = () => {
const parseCString = () => {
value = value.trim();
if (value[0] != '"' && value[0] != '\'')
return "";
let stringEnd = 1;
let inString = true;
let charStr = value[0];
const charStr = value[0];
let remaining = value.substr(1);
let escaped = false;
while (inString) {
@ -51,16 +50,16 @@ export function expandValue(variableCreate: Function, value: string, root: strin
remaining = remaining.substr(1);
stringEnd++;
}
let str = value.substr(0, stringEnd).trim();
const str = value.substr(0, stringEnd).trim();
value = value.substr(stringEnd).trim();
return str;
};
let stack = [root];
const stack = [root];
let parseValue, parseCommaResult, parseCommaValue, parseResult, createValue;
let variable = "";
let getNamespace = (variable) => {
const getNamespace = (variable) => {
let namespace = "";
let prefix = "";
stack.push(variable);
@ -86,11 +85,11 @@ export function expandValue(variableCreate: Function, value: string, root: strin
return prefix + namespace;
};
let parseTupleOrList = () => {
const parseTupleOrList = () => {
value = value.trim();
if (value[0] != '{')
return undefined;
let oldContent = value;
const oldContent = value;
value = value.substr(1).trim();
if (value[0] == '}') {
value = value.substr(1).trim();
@ -103,19 +102,19 @@ export function expandValue(variableCreate: Function, value: string, root: strin
return <any>"<...>";
}
}
let eqPos = value.indexOf("=");
let newValPos1 = value.indexOf("{");
let newValPos2 = value.indexOf(",");
const eqPos = value.indexOf("=");
const newValPos1 = value.indexOf("{");
const newValPos2 = value.indexOf(",");
let newValPos = newValPos1;
if (newValPos2 != -1 && newValPos2 < newValPos1)
newValPos = newValPos2;
if (newValPos != -1 && eqPos > newValPos || eqPos == -1) { // is value list
let values = [];
const values = [];
stack.push("[0]");
let val = parseValue();
stack.pop();
values.push(createValue("[0]", val));
let remaining = value;
const remaining = value;
let i = 0;
while (true) {
stack.push("[" + (++i) + "]");
@ -132,7 +131,7 @@ export function expandValue(variableCreate: Function, value: string, root: strin
let result = parseResult(true);
if (result) {
let results = [];
const results = [];
results.push(result);
while (result = parseCommaResult(true))
results.push(result);
@ -143,7 +142,7 @@ export function expandValue(variableCreate: Function, value: string, root: strin
return undefined;
};
let parsePrimitive = () => {
const parsePrimitive = () => {
let primitive: any;
let match;
value = value.trim();
@ -208,14 +207,14 @@ export function expandValue(variableCreate: Function, value: string, root: strin
parseResult = (pushToStack: boolean = false) => {
value = value.trim();
let variableMatch = resultRegex.exec(value);
const variableMatch = resultRegex.exec(value);
if (!variableMatch)
return undefined;
value = value.substr(variableMatch[0].length).trim();
let name = variable = variableMatch[1];
const name = variable = variableMatch[1];
if (pushToStack)
stack.push(variable);
let val = parseValue();
const val = parseValue();
if (pushToStack)
stack.pop();
return createValue(name, val);

View file

@ -3,13 +3,13 @@ import * as fs from "fs"
export function spawnTerminalEmulator(preferedEmulator: string): Thenable<string> {
return new Promise((resolve, reject) => {
let ttyFileOutput = "/tmp/vscode-gdb-tty-0" + Math.floor(Math.random() * 100000000).toString(36);
const ttyFileOutput = "/tmp/vscode-gdb-tty-0" + Math.floor(Math.random() * 100000000).toString(36);
ChildProcess.spawn(preferedEmulator || "x-terminal-emulator", ["-e", "sh -c \"tty > " + ttyFileOutput + " && sleep 4294967294\""]);
let it = 0;
let interval = setInterval(() => {
const interval = setInterval(() => {
if (fs.existsSync(ttyFileOutput)) {
clearInterval(interval);
let tty = fs.readFileSync(ttyFileOutput).toString("utf8");
const tty = fs.readFileSync(ttyFileOutput).toString("utf8");
fs.unlink(ttyFileOutput);
return resolve(tty);
}

View file

@ -7,8 +7,8 @@ import * as net from "net"
import * as fs from "fs"
import { posix } from "path"
import * as nativePath from "path"
let path = posix;
var Client = require("ssh2").Client;
const path = posix;
const Client = require("ssh2").Client;
export function escape(str: string) {
return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
@ -31,14 +31,14 @@ export class MI2 extends EventEmitter implements IBackend {
super();
if (procEnv) {
var env = {};
const env = {};
// Duplicate process.env so we don't override it
for (var key in process.env)
for (const key in process.env)
if (process.env.hasOwnProperty(key))
env[key] = process.env[key];
// Overwrite with user specified variables
for (var key in procEnv) {
for (const key in procEnv) {
if (procEnv.hasOwnProperty(key)) {
if (procEnv === null)
delete env[key];
@ -55,13 +55,13 @@ export class MI2 extends EventEmitter implements IBackend {
target = nativePath.join(cwd, target);
return new Promise((resolve, reject) => {
this.isSSH = false;
let args = this.preargs.concat(this.extraargs || []);
const args = this.preargs.concat(this.extraargs || []);
this.process = ChildProcess.spawn(this.application, args, { cwd: cwd, env: this.procEnv });
this.process.stdout.on("data", this.stdout.bind(this));
this.process.stderr.on("data", this.stderr.bind(this));
this.process.on("exit", (() => { this.emit("quit"); }).bind(this));
this.process.on("error", ((err) => { this.emit("launcherror", err); }).bind(this));
let promises = this.initCommands(target, cwd);
const promises = this.initCommands(target, cwd);
if (procArgs && procArgs.length)
promises.push(this.sendCommand("exec-arguments " + procArgs));
if (process.platform == "win32") {
@ -103,19 +103,19 @@ export class MI2 extends EventEmitter implements IBackend {
if (args.forwardX11) {
this.sshConn.on("x11", (info, accept, reject) => {
var xserversock = new net.Socket();
const xserversock = new net.Socket();
xserversock.on("error", (err) => {
this.log("stderr", "Could not connect to local X11 server! Did you enable it in your display manager?\n" + err);
});
xserversock.on("connect", () => {
let xclientsock = accept();
const xclientsock = accept();
xclientsock.pipe(xserversock).pipe(xclientsock);
});
xserversock.connect(args.x11port, args.x11host);
});
}
let connectionArgs: any = {
const connectionArgs: any = {
host: args.host,
port: args.port,
username: args.user
@ -138,7 +138,7 @@ export class MI2 extends EventEmitter implements IBackend {
this.sshConn.on("ready", () => {
this.log("stdout", "Running " + this.application + " over ssh...");
let execArgs: any = {};
const execArgs: any = {};
if (args.forwardX11) {
execArgs.x11 = {
single: false,
@ -165,7 +165,7 @@ export class MI2 extends EventEmitter implements IBackend {
this.emit("quit");
this.sshConn.end();
}).bind(this));
let promises = this.initCommands(target, cwd, true, attach);
const promises = this.initCommands(target, cwd, true, attach);
promises.push(this.sendCommand("environment-cd \"" + escape(cwd) + "\""));
if (procArgs && procArgs.length && !attach)
promises.push(this.sendCommand("exec-arguments " + procArgs));
@ -192,7 +192,7 @@ export class MI2 extends EventEmitter implements IBackend {
if (!nativePath.isAbsolute(target))
target = nativePath.join(cwd, target);
}
var cmds = [
const cmds = [
this.sendCommand("gdb-set target-async on", true),
this.sendCommand("environment-directory \"" + escape(cwd) + "\"", true)
];
@ -211,7 +211,7 @@ export class MI2 extends EventEmitter implements IBackend {
executable = nativePath.join(cwd, executable);
if (!executable)
executable = "-p";
var isExtendedRemote = false;
let isExtendedRemote = false;
if (target.startsWith("extended-remote")) {
isExtendedRemote = true;
args = this.preargs;
@ -222,7 +222,7 @@ export class MI2 extends EventEmitter implements IBackend {
this.process.stderr.on("data", this.stderr.bind(this));
this.process.on("exit", (() => { this.emit("quit"); }).bind(this));
this.process.on("error", ((err) => { this.emit("launcherror", err); }).bind(this));
var commands = [
const commands = [
this.sendCommand("gdb-set target-async on"),
this.sendCommand("environment-directory \"" + escape(cwd) + "\"")
];
@ -269,7 +269,7 @@ export class MI2 extends EventEmitter implements IBackend {
this.buffer += data;
else
this.buffer += data.toString("utf8");
let end = this.buffer.lastIndexOf('\n');
const end = this.buffer.lastIndexOf('\n');
if (end != -1) {
this.onOutput(this.buffer.substr(0, end));
this.buffer = this.buffer.substr(end + 1);
@ -286,7 +286,7 @@ export class MI2 extends EventEmitter implements IBackend {
this.errbuf += data;
else
this.errbuf += data.toString("utf8");
let end = this.errbuf.lastIndexOf('\n');
const end = this.errbuf.lastIndexOf('\n');
if (end != -1) {
this.onOutputStderr(this.errbuf.substr(0, end));
this.errbuf = this.errbuf.substr(end + 1);
@ -320,7 +320,7 @@ export class MI2 extends EventEmitter implements IBackend {
this.log("stdout", line);
}
else {
let parsed = parseMI(line);
const parsed = parseMI(line);
if (this.debugOutput)
this.log("log", "GDB -> App: " + JSON.stringify(parsed));
let handled = false;
@ -344,7 +344,7 @@ export class MI2 extends EventEmitter implements IBackend {
if (record.asyncClass == "running")
this.emit("running", parsed);
else if (record.asyncClass == "stopped") {
let reason = parsed.record("reason");
const reason = parsed.record("reason");
if (trace)
this.log("stderr", "stop: " + reason);
if (reason == "breakpoint-hit")
@ -402,8 +402,8 @@ export class MI2 extends EventEmitter implements IBackend {
stop() {
if (this.isSSH) {
let proc = this.stream;
let to = setTimeout(() => {
const proc = this.stream;
const to = setTimeout(() => {
proc.signal("KILL");
}, 1000);
this.stream.on("exit", function (code) {
@ -412,8 +412,8 @@ export class MI2 extends EventEmitter implements IBackend {
this.sendRaw("-gdb-exit");
}
else {
let proc = this.process;
let to = setTimeout(() => {
const proc = this.process;
const to = setTimeout(() => {
process.kill(-proc.pid);
}, 1000);
this.process.on("exit", function (code) {
@ -424,8 +424,8 @@ export class MI2 extends EventEmitter implements IBackend {
}
detach() {
let proc = this.process;
let to = setTimeout(() => {
const proc = this.process;
const to = setTimeout(() => {
process.kill(-proc.pid);
}, 1000);
this.process.on("exit", function (code) {
@ -493,7 +493,7 @@ export class MI2 extends EventEmitter implements IBackend {
loadBreakPoints(breakpoints: Breakpoint[]): Thenable<[boolean, Breakpoint][]> {
if (trace)
this.log("stderr", "loadBreakPoints");
let promisses = [];
const promisses = [];
breakpoints.forEach(breakpoint => {
promisses.push(this.addBreakPoint(breakpoint));
});
@ -517,7 +517,7 @@ export class MI2 extends EventEmitter implements IBackend {
if (breakpoint.countCondition[0] == ">")
location += "-i " + numRegex.exec(breakpoint.countCondition.substr(1))[0] + " ";
else {
let match = numRegex.exec(breakpoint.countCondition)[0];
const match = numRegex.exec(breakpoint.countCondition)[0];
if (match.length != breakpoint.countCondition.length) {
this.log("stderr", "Unsupported break count expression: '" + breakpoint.countCondition + "'. Only supports 'X' for breaking once after X times or '>X' for ignoring the first X breaks");
location += "-t ";
@ -532,8 +532,8 @@ export class MI2 extends EventEmitter implements IBackend {
location += '"' + escape(breakpoint.file) + ":" + breakpoint.line + '"';
this.sendCommand("break-insert -f " + location).then((result) => {
if (result.resultRecords.resultClass == "done") {
let bkptNum = parseInt(result.result("bkpt.number"));
let newBrk = {
const bkptNum = parseInt(result.result("bkpt.number"));
const newBrk = {
file: result.result("bkpt.file"),
line: parseInt(result.result("bkpt.line")),
condition: breakpoint.condition
@ -595,17 +595,17 @@ export class MI2 extends EventEmitter implements IBackend {
async getThreads(): Promise<Thread[]> {
if (trace) this.log("stderr", "getThreads");
let command = "thread-info";
let result = await this.sendCommand(command);
let threads = result.result("threads");
let ret: Thread[] = [];
const command = "thread-info";
const result = await this.sendCommand(command);
const threads = result.result("threads");
const ret: Thread[] = [];
return threads.map(element => {
let ret : Thread = {
const ret : Thread = {
id: parseInt(MINode.valueOf(element, "id")),
targetId: MINode.valueOf(element, "target-id")
};
let name = MINode.valueOf(element, "name");
const name = MINode.valueOf(element, "name");
if (name) {
ret.name = name;
}
@ -624,20 +624,20 @@ export class MI2 extends EventEmitter implements IBackend {
if (maxLevels) {
command += " 0 " + maxLevels;
}
let result = await this.sendCommand(command);
let stack = result.result("stack");
let ret: Stack[] = [];
const result = await this.sendCommand(command);
const stack = result.result("stack");
const ret: Stack[] = [];
return stack.map(element => {
let level = MINode.valueOf(element, "@frame.level");
let addr = MINode.valueOf(element, "@frame.addr");
let func = MINode.valueOf(element, "@frame.func");
let filename = MINode.valueOf(element, "@frame.file");
let file = MINode.valueOf(element, "@frame.fullname");
const level = MINode.valueOf(element, "@frame.level");
const addr = MINode.valueOf(element, "@frame.addr");
const func = MINode.valueOf(element, "@frame.func");
const filename = MINode.valueOf(element, "@frame.file");
const file = MINode.valueOf(element, "@frame.fullname");
let line = 0;
let lnstr = MINode.valueOf(element, "@frame.line");
const lnstr = MINode.valueOf(element, "@frame.line");
if (lnstr)
line = parseInt(lnstr);
let from = parseInt(MINode.valueOf(element, "@frame.from"));
const from = parseInt(MINode.valueOf(element, "@frame.from"));
return {
address: addr,
fileName: filename,
@ -655,7 +655,7 @@ export class MI2 extends EventEmitter implements IBackend {
const result = await this.sendCommand(`stack-list-variables --thread ${thread} --frame ${frame} --simple-values`);
const variables = result.result("variables");
let ret: Variable[] = [];
const ret: Variable[] = [];
for (const element of variables) {
const key = MINode.valueOf(element, "name");
const value = MINode.valueOf(element, "value");
@ -712,7 +712,7 @@ export class MI2 extends EventEmitter implements IBackend {
//TODO: add `from` and `to` arguments
const res = await this.sendCommand(`var-list-children --all-values ${name}`);
const children = res.result("children") || [];
let omg: VariableObject[] = children.map(child => new VariableObject(child[1]));
const omg: VariableObject[] = children.map(child => new VariableObject(child[1]));
return omg;
}
@ -764,7 +764,7 @@ export class MI2 extends EventEmitter implements IBackend {
}
sendCommand(command: string, suppressFailure: boolean = false): Thenable<MINode> {
let sel = this.currentToken++;
const sel = this.currentToken++;
return new Promise((resolve, reject) => {
this.handlers[sel] = (node: MINode) => {
if (node && node.resultRecords && node.resultRecords.resultClass === "error") {

View file

@ -3,7 +3,7 @@ import { Breakpoint } from "../backend"
import * as ChildProcess from "child_process"
import { posix } from "path"
import * as nativePath from "path"
let path = posix;
const path = posix;
export class MI2_LLDB extends MI2 {
protected initCommands(target: string, cwd: string, ssh: boolean = false, attach: boolean = false) {
@ -15,7 +15,7 @@ export class MI2_LLDB extends MI2 {
if (!nativePath.isAbsolute(target))
target = nativePath.join(cwd, target);
}
var cmds = [
const cmds = [
this.sendCommand("gdb-set target-async on")
];
if (!attach)
@ -43,7 +43,7 @@ export class MI2_LLDB extends MI2 {
clearBreakPoints(): Thenable<any> {
return new Promise((resolve, reject) => {
let promises = [];
const promises = [];
this.breakpoints.forEach((k, index) => {
promises.push(this.sendCommand("break-delete " + k).then((result) => {
if (result.resultRecords.resultClass == "done") resolve(true);

View file

@ -5,22 +5,22 @@ import { MINode } from "../mi_parse"
export class MI2_Mago extends MI2_LLDB {
getStack(maxLevels: number, thread: number): Promise<Stack[]> {
return new Promise((resolve, reject) => {
let command = "stack-list-frames";
const command = "stack-list-frames";
this.sendCommand(command).then((result) => {
let stack = result.resultRecords.results;
let ret: Stack[] = [];
let remaining = [];
let addToStack = (element) => {
let level = MINode.valueOf(element, "frame.level");
let addr = MINode.valueOf(element, "frame.addr");
let func = MINode.valueOf(element, "frame.func");
let filename = MINode.valueOf(element, "file");
let file = MINode.valueOf(element, "fullname");
const stack = result.resultRecords.results;
const ret: Stack[] = [];
const remaining = [];
const addToStack = (element) => {
const level = MINode.valueOf(element, "frame.level");
const addr = MINode.valueOf(element, "frame.addr");
const func = MINode.valueOf(element, "frame.func");
const filename = MINode.valueOf(element, "file");
const file = MINode.valueOf(element, "fullname");
let line = 0;
let lnstr = MINode.valueOf(element, "line");
const lnstr = MINode.valueOf(element, "line");
if (lnstr)
line = parseInt(lnstr);
let from = parseInt(MINode.valueOf(element, "from"));
const from = parseInt(MINode.valueOf(element, "from"));
ret.push({
address: addr,
fileName: filename || "",

View file

@ -4,18 +4,18 @@ export interface MIInfo {
resultRecords: { resultClass: string, results: [string, any][] };
}
var octalMatch = /^[0-7]{3}/;
const octalMatch = /^[0-7]{3}/;
function parseString(str: string): string {
var ret = new Buffer(str.length * 4);
var bufIndex = 0;
const ret = new Buffer(str.length * 4);
let bufIndex = 0;
if (str[0] != '"' || str[str.length - 1] != '"')
throw new Error("Not a valid string");
str = str.slice(1, -1);
var escaped = false;
for (var i = 0; i < str.length; i++) {
let escaped = false;
for (let i = 0; i < str.length; i++) {
if (escaped) {
var m;
let m;
if (str[i] == '\\')
bufIndex += ret.write('\\', bufIndex);
else if (str[i] == '"')
@ -81,8 +81,8 @@ export class MINode implements MIInfo {
static valueOf(start: any, path: string): any {
if (!start)
return undefined;
let pathRegex = /^\.?([a-zA-Z_\-][a-zA-Z0-9_\-]*)/;
let indexRegex = /^\[(\d+)\](?:$|\.)/;
const pathRegex = /^\.?([a-zA-Z_\-][a-zA-Z0-9_\-]*)/;
const indexRegex = /^\[(\d+)\](?:$|\.)/;
path = path.trim();
if (!path)
return start;
@ -92,9 +92,9 @@ export class MINode implements MIInfo {
if (target) {
path = path.substr(target[0].length);
if (current.length && typeof current != "string") {
let found = [];
const found = [];
for (let i = 0; i < current.length; i++) {
let element = current[i];
const element = current[i];
if (element[0] == target[1]) {
found.push(element[1]);
}
@ -114,7 +114,7 @@ export class MINode implements MIInfo {
target = indexRegex.exec(path);
if (target) {
path = path.substr(target[0].length);
let i = parseInt(target[1]);
const i = parseInt(target[1]);
if (current.length && typeof current != "string" && i >= 0 && i < current.length) {
current = current[i];
} else if (i == 0) {
@ -154,21 +154,21 @@ export function parseMI(output: string): MINode {
*/
let token = undefined;
let outOfBandRecord = [];
const outOfBandRecord = [];
let resultRecords = undefined;
let asyncRecordType = {
const asyncRecordType = {
"*": "exec",
"+": "status",
"=": "notify"
};
let streamRecordType = {
const streamRecordType = {
"~": "console",
"@": "target",
"&": "log"
};
let parseCString = () => {
const parseCString = () => {
if (output[0] != '"')
return "";
let stringEnd = 1;
@ -199,11 +199,11 @@ export function parseMI(output: string): MINode {
let parseValue, parseCommaResult, parseCommaValue, parseResult;
let parseTupleOrList = () => {
const parseTupleOrList = () => {
if (output[0] != '{' && output[0] != '[')
return undefined;
let oldContent = output;
let canBeValueList = output[0] == '[';
const oldContent = output;
const canBeValueList = output[0] == '[';
output = output.substr(1);
if (output[0] == '}' || output[0] == ']') {
output = output.substr(1); // ] or }
@ -212,9 +212,9 @@ export function parseMI(output: string): MINode {
if (canBeValueList) {
let value = parseValue();
if (value) { // is value list
let values = [];
const values = [];
values.push(value);
let remaining = output;
const remaining = output;
while ((value = parseCommaValue()) !== undefined)
values.push(value);
output = output.substr(1); // ]
@ -223,7 +223,7 @@ export function parseMI(output: string): MINode {
}
let result = parseResult();
if (result) {
let results = [];
const results = [];
results.push(result);
while (result = parseCommaResult())
results.push(result);
@ -244,11 +244,11 @@ export function parseMI(output: string): MINode {
};
parseResult = () => {
let variableMatch = variableRegex.exec(output);
const variableMatch = variableRegex.exec(output);
if (!variableMatch)
return undefined;
output = output.substr(variableMatch[0].length + 1);
let variable = variableMatch[1];
const variable = variableMatch[1];
return [variable, parseValue()];
};
@ -275,9 +275,9 @@ export function parseMI(output: string): MINode {
}
if (match[2]) {
let classMatch = asyncClassRegex.exec(output);
const classMatch = asyncClassRegex.exec(output);
output = output.substr(classMatch[1].length);
let asyncRecord = {
const asyncRecord = {
isStream: false,
type: asyncRecordType[match[2]],
asyncClass: classMatch[1],
@ -289,7 +289,7 @@ export function parseMI(output: string): MINode {
outOfBandRecord.push(asyncRecord);
}
else if (match[3]) {
let streamRecord = {
const streamRecord = {
isStream: true,
type: streamRecordType[match[3]],
content: parseCString()

View file

@ -12,8 +12,8 @@ export function activate(context: vscode.ExtensionContext) {
vscode.window.showErrorMessage("No editor with valid file name active");
return;
}
var fileName = vscode.window.activeTextEditor.document.fileName;
var ext = path.extname(fileName);
const fileName = vscode.window.activeTextEditor.document.fileName;
const ext = path.extname(fileName);
return fileName.substr(0, fileName.length - ext.length);
}));
context.subscriptions.push(vscode.commands.registerCommand("code-debug.getFileBasenameNoExt", () => {
@ -21,22 +21,22 @@ export function activate(context: vscode.ExtensionContext) {
vscode.window.showErrorMessage("No editor with valid file name active");
return;
}
var fileName = path.basename(vscode.window.activeTextEditor.document.fileName);
var ext = path.extname(fileName);
const fileName = path.basename(vscode.window.activeTextEditor.document.fileName);
const ext = path.extname(fileName);
return fileName.substr(0, fileName.length - ext.length);
}));
}
var memoryLocationRegex = /^0x[0-9a-f]+$/;
const memoryLocationRegex = /^0x[0-9a-f]+$/;
function getMemoryRange(range: string) {
if (!range)
return undefined;
range = range.replace(/\s+/g, "").toLowerCase();
var index;
let index;
if ((index = range.indexOf("+")) != -1) {
var from = range.substr(0, index);
var length = range.substr(index + 1);
const from = range.substr(0, index);
let length = range.substr(index + 1);
if (!memoryLocationRegex.exec(from))
return undefined;
if (memoryLocationRegex.exec(length))
@ -44,8 +44,8 @@ function getMemoryRange(range: string) {
return "from=" + encodeURIComponent(from) + "&length=" + encodeURIComponent(length);
}
else if ((index = range.indexOf("-")) != -1) {
var from = range.substr(0, index);
var to = range.substr(index + 1);
const from = range.substr(0, index);
const to = range.substr(index + 1);
if (!memoryLocationRegex.exec(from))
return undefined;
if (!memoryLocationRegex.exec(to))
@ -58,7 +58,7 @@ function getMemoryRange(range: string) {
}
function examineMemory() {
let socketlists = path.join(os.tmpdir(), "code-debug-sockets");
const socketlists = path.join(os.tmpdir(), "code-debug-sockets");
if (!fs.existsSync(socketlists)) {
if (process.platform == "win32")
return vscode.window.showErrorMessage("This command is not available on windows");
@ -72,7 +72,7 @@ function examineMemory() {
else
return vscode.window.showErrorMessage("No debugging sessions available");
}
var pickedFile = (file) => {
const pickedFile = (file) => {
vscode.window.showInputBox({ placeHolder: "Memory Location or Range", validateInput: range => getMemoryRange(range) === undefined ? "Range must either be in format 0xF00-0xF01, 0xF100+32 or 0xABC154" : "" }).then(range => {
vscode.commands.executeCommand("vscode.previewHtml", vscode.Uri.parse("debugmemory://" + file + "#" + getMemoryRange(range)));
});
@ -91,12 +91,12 @@ function examineMemory() {
class MemoryContentProvider implements vscode.TextDocumentContentProvider {
provideTextDocumentContent(uri: vscode.Uri, token: vscode.CancellationToken): Thenable<string> {
return new Promise((resolve, reject) => {
var conn = net.connect(path.join(os.tmpdir(), "code-debug-sockets", uri.authority));
var from, to;
var highlightAt = -1;
var splits = uri.fragment.split("&");
const conn = net.connect(path.join(os.tmpdir(), "code-debug-sockets", uri.authority));
let from, to;
let highlightAt = -1;
const splits = uri.fragment.split("&");
if (splits[0].split("=")[0] == "at") {
var loc = parseInt(splits[0].split("=")[1].substr(2), 16);
const loc = parseInt(splits[0].split("=")[1].substr(2), 16);
highlightAt = 64;
from = Math.max(loc - 64, 0);
to = Math.max(loc + 768, 0);
@ -116,14 +116,14 @@ class MemoryContentProvider implements vscode.TextDocumentContentProvider {
return reject("Negative Range");
conn.write("examineMemory " + JSON.stringify([from, to - from + 1]));
conn.once("data", data => {
var formattedCode = "";
var hexString = data.toString();
var x = 0;
var asciiLine = "";
var byteNo = 0;
for (var i = 0; i < hexString.length; i += 2) {
var digit = hexString.substr(i, 2);
var digitNum = parseInt(digit, 16);
let formattedCode = "";
const hexString = data.toString();
let x = 0;
let asciiLine = "";
let byteNo = 0;
for (let i = 0; i < hexString.length; i += 2) {
const digit = hexString.substr(i, 2);
const digitNum = parseInt(digit, 16);
if (digitNum >= 32 && digitNum <= 126)
asciiLine += String.fromCharCode(digitNum);
else
@ -140,7 +140,7 @@ class MemoryContentProvider implements vscode.TextDocumentContentProvider {
byteNo++;
}
if (x > 0) {
for (var i = 0; i <= 16 - x; i++) {
for (let i = 0; i <= 16 - x; i++) {
formattedCode += " ";
}
formattedCode += asciiLine;

View file

@ -11,8 +11,8 @@ import * as net from "net";
import * as os from "os";
import * as fs from "fs";
let resolve = posix.resolve;
let relative = posix.relative;
const resolve = posix.resolve;
const relative = posix.relative;
class ExtendedVariable {
constructor(public name, public options) {
@ -58,10 +58,10 @@ export class MI2DebugSession extends DebugSession {
try {
this.commandServer = net.createServer(c => {
c.on("data", data => {
var rawCmd = data.toString();
var spaceIndex = rawCmd.indexOf(" ");
var func = rawCmd;
var args = [];
const rawCmd = data.toString();
const spaceIndex = rawCmd.indexOf(" ");
let func = rawCmd;
let args = [];
if (spaceIndex != -1) {
func = rawCmd.substr(0, spaceIndex);
args = JSON.parse(rawCmd.substr(spaceIndex + 1));
@ -110,19 +110,19 @@ export class MI2DebugSession extends DebugSession {
}
protected handleBreakpoint(info: MINode) {
let event = new StoppedEvent("breakpoint", parseInt(info.record("thread-id")));
const event = new StoppedEvent("breakpoint", parseInt(info.record("thread-id")));
(event as DebugProtocol.StoppedEvent).body.allThreadsStopped = info.record("stopped-threads") == "all";
this.sendEvent(event);
}
protected handleBreak(info: MINode) {
let event = new StoppedEvent("step", parseInt(info.record("thread-id")));
const event = new StoppedEvent("step", parseInt(info.record("thread-id")));
(event as DebugProtocol.StoppedEvent).body.allThreadsStopped = info.record("stopped-threads") == "all";
this.sendEvent(event);
}
protected handlePause(info: MINode) {
let event = new StoppedEvent("user request", parseInt(info.record("thread-id")));
const event = new StoppedEvent("user request", parseInt(info.record("thread-id")));
(event as DebugProtocol.StoppedEvent).body.allThreadsStopped = info.record("stopped-threads") == "all";
this.sendEvent(event);
}
@ -131,7 +131,7 @@ export class MI2DebugSession extends DebugSession {
if (!this.started)
this.crashed = true;
if (!this.quit) {
let event = new StoppedEvent("exception", parseInt(info.record("thread-id")));
const event = new StoppedEvent("exception", parseInt(info.record("thread-id")));
(event as DebugProtocol.StoppedEvent).body.allThreadsStopped = info.record("stopped-threads") == "all";
this.sendEvent(event);
}
@ -175,7 +175,7 @@ export class MI2DebugSession extends DebugSession {
name = `${parent.name}.${name}`;
}
let res = await this.miDebugger.varAssign(name, args.value);
const res = await this.miDebugger.varAssign(name, args.value);
response.body = {
value: res.result("value")
};
@ -194,14 +194,14 @@ export class MI2DebugSession extends DebugSession {
}
protected setFunctionBreakPointsRequest(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments): void {
let cb = (() => {
const cb = (() => {
this.debugReady = true;
let all = [];
const all = [];
args.breakpoints.forEach(brk => {
all.push(this.miDebugger.addBreakPoint({ raw: brk.name, condition: brk.condition, countCondition: brk.hitCondition }));
});
Promise.all(all).then(brkpoints => {
let finalBrks = [];
const finalBrks = [];
brkpoints.forEach(brkp => {
if (brkp[0])
finalBrks.push({ line: brkp[1].line });
@ -221,7 +221,7 @@ export class MI2DebugSession extends DebugSession {
}
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
let cb = (() => {
const cb = (() => {
this.debugReady = true;
this.miDebugger.clearBreakPoints().then(() => {
let path = args.source.path;
@ -229,11 +229,11 @@ export class MI2DebugSession extends DebugSession {
path = relative(this.trimCWD.replace(/\\/g, "/"), path.replace(/\\/g, "/"));
path = resolve(this.switchCWD.replace(/\\/g, "/"), path.replace(/\\/g, "/"));
}
let all = args.breakpoints.map(brk => {
const all = args.breakpoints.map(brk => {
return this.miDebugger.addBreakPoint({ file: path, line: brk.line, condition: brk.condition, countCondition: brk.hitCondition });
});
Promise.all(all).then(brkpoints => {
let finalBrks = [];
const finalBrks = [];
brkpoints.forEach(brkp => {
// TODO: Currently all breakpoints returned are marked as verified,
// which leads to verified breakpoints on a broken lldb.
@ -292,7 +292,7 @@ export class MI2DebugSession extends DebugSession {
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
this.miDebugger.getStack(args.levels, args.threadId).then(stack => {
let ret: StackFrame[] = [];
const ret: StackFrame[] = [];
stack.forEach(element => {
let source = null;
let file = element.file;
@ -358,14 +358,14 @@ export class MI2DebugSession extends DebugSession {
id = this.variableHandles.get(args.variablesReference);
}
let createVariable = (arg, options?) => {
const createVariable = (arg, options?) => {
if (options)
return this.variableHandles.create(new ExtendedVariable(arg, options));
else
return this.variableHandles.create(arg);
};
let findOrCreateVariable = (varObj: VariableObject): number => {
const findOrCreateVariable = (varObj: VariableObject): number => {
let id: number;
if (this.variableHandlesReverse.hasOwnProperty(varObj.name)) {
id = this.variableHandlesReverse[varObj.name];
@ -380,12 +380,12 @@ export class MI2DebugSession extends DebugSession {
if (typeof id == "number") {
let stack: Variable[];
try {
let [threadId, level] = this.frameIdToThreadAndLevel(id);
const [threadId, level] = this.frameIdToThreadAndLevel(id);
stack = await this.miDebugger.getStackVariables(threadId, level);
for (const variable of stack) {
if (this.useVarObjects) {
try {
let varObjName = `var_${id}_${variable.name}`;
const varObjName = `var_${id}_${variable.name}`;
let varObj: VariableObject;
try {
const changes = await this.miDebugger.varUpdate(varObjName);
@ -508,22 +508,22 @@ export class MI2DebugSession extends DebugSession {
}
}
else if (id instanceof ExtendedVariable) {
let varReq = id;
const varReq = id;
if (varReq.options.arg) {
let strArr = [];
const strArr = [];
let argsPart = true;
let arrIndex = 0;
let submit = () => {
const submit = () => {
response.body = {
variables: strArr
};
this.sendResponse(response);
};
let addOne = async () => {
const addOne = async () => {
// TODO: this evals on an (effectively) unknown thread for multithreaded programs.
const variable = await this.miDebugger.evalExpression(JSON.stringify(`${varReq.name}+${arrIndex})`), 0, 0);
try {
let expanded = expandValue(createVariable, variable.result("value"), varReq.name, variable);
const expanded = expandValue(createVariable, variable.result("value"), varReq.name, variable);
if (!expanded) {
this.sendErrorResponse(response, 15, `Could not expand variable`);
}
@ -641,7 +641,7 @@ export class MI2DebugSession extends DebugSession {
}
protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void {
let [threadId, level] = this.frameIdToThreadAndLevel(args.frameId);
const [threadId, level] = this.frameIdToThreadAndLevel(args.frameId);
if (args.context == "watch" || args.context == "hover") {
this.miDebugger.evalExpression(args.expression, threadId, level).then((res) => {
response.body = {