From 1244e4133c125fa4136d43d456bf5200ccb146d5 Mon Sep 17 00:00:00 2001 From: Simon Marchi Date: Tue, 17 Jul 2018 18:19:37 -0400 Subject: [PATCH 1/3] 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. --- package.json | 10 ++-- src/backend/backend.ts | 2 +- src/backend/gdb_expansion.ts | 35 +++++++------ src/backend/linux/console.ts | 6 +-- src/backend/mi2/mi2.ts | 96 ++++++++++++++++++------------------ src/backend/mi2/mi2lldb.ts | 6 +-- src/backend/mi2/mi2mago.ts | 24 ++++----- src/backend/mi_parse.ts | 52 +++++++++---------- src/frontend/extension.ts | 52 +++++++++---------- src/mibase.ts | 56 ++++++++++----------- test/gdb_expansion.test.ts | 20 ++++---- test/index.ts | 2 +- test/mi_parse.test.ts | 28 +++++------ tsconfig.json | 9 +++- tslint.json | 7 +++ 15 files changed, 209 insertions(+), 196 deletions(-) create mode 100644 tslint.json diff --git a/package.json b/package.json index 3a6db75b..cf85125f 100644 --- a/package.json +++ b/package.json @@ -926,10 +926,12 @@ "ssh2": "^0.5.4" }, "devDependencies": { - "typescript": "^2.1.6", - "vscode": "^1.0.3", - "mocha": "^3.2.0", + "@types/mocha": "^2.2.39", "@types/node": "^7.0.5", - "@types/mocha": "^2.2.39" + "mocha": "^3.2.0", + "tslint": "^5.11.0", + "tslint-language-service": "^0.9.9", + "typescript": "^2.1.6", + "vscode": "^1.0.3" } } diff --git a/src/backend/backend.ts b/src/backend/backend.ts index 13028085..54d47cda 100644 --- a/src/backend/backend.ts +++ b/src/backend/backend.ts @@ -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) ? "" : this.value, diff --git a/src/backend/gdb_expansion.ts b/src/backend/gdb_expansion.ts index a5288a4d..ae48de49 100644 --- a/src/backend/gdb_expansion.ts +++ b/src/backend/gdb_expansion.ts @@ -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 "<...>"; } } - 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); diff --git a/src/backend/linux/console.ts b/src/backend/linux/console.ts index 6ab593c7..c3cbea02 100644 --- a/src/backend/linux/console.ts +++ b/src/backend/linux/console.ts @@ -3,13 +3,13 @@ import * as fs from "fs" export function spawnTerminalEmulator(preferedEmulator: string): Thenable { 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); } diff --git a/src/backend/mi2/mi2.ts b/src/backend/mi2/mi2.ts index f6bec8df..d1feca6a 100644 --- a/src/backend/mi2/mi2.ts +++ b/src/backend/mi2/mi2.ts @@ -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 { 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 { - 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") { diff --git a/src/backend/mi2/mi2lldb.ts b/src/backend/mi2/mi2lldb.ts index 83d2023a..5cdf7885 100644 --- a/src/backend/mi2/mi2lldb.ts +++ b/src/backend/mi2/mi2lldb.ts @@ -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 { 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); diff --git a/src/backend/mi2/mi2mago.ts b/src/backend/mi2/mi2mago.ts index c9aad349..43af6617 100644 --- a/src/backend/mi2/mi2mago.ts +++ b/src/backend/mi2/mi2mago.ts @@ -5,22 +5,22 @@ import { MINode } from "../mi_parse" export class MI2_Mago extends MI2_LLDB { getStack(maxLevels: number, thread: number): Promise { 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 || "", diff --git a/src/backend/mi_parse.ts b/src/backend/mi_parse.ts index 91163156..f8556f91 100644 --- a/src/backend/mi_parse.ts +++ b/src/backend/mi_parse.ts @@ -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() diff --git a/src/frontend/extension.ts b/src/frontend/extension.ts index 4c6fe0e3..f8a251f2 100644 --- a/src/frontend/extension.ts +++ b/src/frontend/extension.ts @@ -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 { 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; diff --git a/src/mibase.ts b/src/mibase.ts index cc728fae..ec083bd8 100644 --- a/src/mibase.ts +++ b/src/mibase.ts @@ -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 = { diff --git a/test/gdb_expansion.test.ts b/test/gdb_expansion.test.ts index 8d7e3b7d..c91b62aa 100644 --- a/test/gdb_expansion.test.ts +++ b/test/gdb_expansion.test.ts @@ -2,7 +2,7 @@ import * as assert from 'assert'; import { expandValue, isExpandable } from '../src/backend/gdb_expansion'; suite("GDB Value Expansion", () => { - let variableCreate = (variable) => { return { expanded: variable }; }; + const variableCreate = (variable) => { return { expanded: variable }; }; test("Various values", () => { assert.strictEqual(isExpandable(`false`), 0); assert.equal(expandValue(variableCreate, `false`), "false"); @@ -104,7 +104,7 @@ suite("GDB Value Expansion", () => { }); test("Simple node", () => { assert.strictEqual(isExpandable(`{a = false, b = 5, c = 0x0, d = "foobar"}`), 1); - let variables = expandValue(variableCreate, `{a = false, b = 5, c = 0x0, d = "foobar"}`); + const variables = expandValue(variableCreate, `{a = false, b = 5, c = 0x0, d = "foobar"}`); assert.equal(variables.length, 4); assert.equal(variables[0].name, "a"); assert.equal(variables[0].value, "false"); @@ -116,9 +116,9 @@ suite("GDB Value Expansion", () => { assert.equal(variables[3].value, `"foobar"`); }); test("Complex node", () => { - let node = `{quit = false, _views = {{view = 0x7ffff7ece1e8, renderer = 0x7ffff7eccc50, world = 0x7ffff7ece480}}, deltaTimer = {_flagStarted = false, _timeStart = {length = 0}, _timeMeasured = {length = 0}}, _start = {callbacks = 0x0}, _stop = {callbacks = 0x0}}`; + const node = `{quit = false, _views = {{view = 0x7ffff7ece1e8, renderer = 0x7ffff7eccc50, world = 0x7ffff7ece480}}, deltaTimer = {_flagStarted = false, _timeStart = {length = 0}, _timeMeasured = {length = 0}}, _start = {callbacks = 0x0}, _stop = {callbacks = 0x0}}`; assert.strictEqual(isExpandable(node), 1); - let variables = expandValue(variableCreate, node); + const variables = expandValue(variableCreate, node); assert.deepEqual(variables, [ { name: "quit", @@ -224,9 +224,9 @@ suite("GDB Value Expansion", () => { ]); }); test("Simple node with errors", () => { - let node = `{_enableMipMaps = false, _minFilter = , _magFilter = , _wrapX = , _wrapY = , _inMode = 6408, _mode = 6408, _id = 1, _width = 1024, _height = 1024}`; + const node = `{_enableMipMaps = false, _minFilter = , _magFilter = , _wrapX = , _wrapY = , _inMode = 6408, _mode = 6408, _id = 1, _width = 1024, _height = 1024}`; assert.strictEqual(isExpandable(node), 1); - let variables = expandValue(variableCreate, node); + const variables = expandValue(variableCreate, node); assert.deepEqual(variables, [ { name: "_enableMipMaps", @@ -281,9 +281,9 @@ suite("GDB Value Expansion", () => { ]); }); test("lldb strings", () => { - let node = `{ name = {...} }`; + const node = `{ name = {...} }`; assert.strictEqual(isExpandable(node), 1); - let variables = expandValue(variableCreate, node); + const variables = expandValue(variableCreate, node); assert.deepEqual(variables, [ { name: "name", @@ -293,8 +293,8 @@ suite("GDB Value Expansion", () => { ]); }); test("float values", () => { - let node = `{ intval1 = 123, floatval1 = 123.456, intval2 = 3, floatval2 = 234.45 }`; - let variables = expandValue(variableCreate, node); + const node = `{ intval1 = 123, floatval1 = 123.456, intval2 = 3, floatval2 = 234.45 }`; + const variables = expandValue(variableCreate, node); assert.deepEqual(variables, [ { name: "intval1", value: "123", variablesReference: 0 }, diff --git a/test/index.ts b/test/index.ts index e3cebd0d..93023b9a 100644 --- a/test/index.ts +++ b/test/index.ts @@ -10,7 +10,7 @@ // to report the results back to the caller. When the tests are finished, return // a possible error to the callback or null if none. -var testRunner = require('vscode/lib/testrunner'); +const testRunner = require('vscode/lib/testrunner'); // You can directly control Mocha options by uncommenting the following lines // See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info diff --git a/test/mi_parse.test.ts b/test/mi_parse.test.ts index e7587db0..9360d790 100644 --- a/test/mi_parse.test.ts +++ b/test/mi_parse.test.ts @@ -3,7 +3,7 @@ import { parseMI, MINode } from '../src/backend/mi_parse'; suite("MI Parse", () => { test("Simple out of band record", () => { - let parsed = parseMI(`4=thread-exited,id="3",group-id="i1"`); + const parsed = parseMI(`4=thread-exited,id="3",group-id="i1"`); assert.ok(parsed); assert.equal(parsed.token, 4); assert.equal(parsed.outOfBandRecord.length, 1); @@ -15,7 +15,7 @@ suite("MI Parse", () => { assert.equal(parsed.resultRecords, undefined); }); test("Console stream output with new line", () => { - let parsed = parseMI(`~"[Thread 0x7fffe993a700 (LWP 11002) exited]\\n"`); + const parsed = parseMI(`~"[Thread 0x7fffe993a700 (LWP 11002) exited]\\n"`); assert.ok(parsed); assert.equal(parsed.token, undefined); assert.equal(parsed.outOfBandRecord.length, 1); @@ -40,21 +40,21 @@ suite("MI Parse", () => { assert.equal(parsed.resultRecords, undefined); }); test("Empty line", () => { - let parsed = parseMI(``); + const parsed = parseMI(``); assert.ok(parsed); assert.equal(parsed.token, undefined); assert.equal(parsed.outOfBandRecord.length, 0); assert.equal(parsed.resultRecords, undefined); }); test("'(gdb)' line", () => { - let parsed = parseMI(`(gdb)`); + const parsed = parseMI(`(gdb)`); assert.ok(parsed); assert.equal(parsed.token, undefined); assert.equal(parsed.outOfBandRecord.length, 0); assert.equal(parsed.resultRecords, undefined); }); test("Simple result record", () => { - let parsed = parseMI(`1^running`); + const parsed = parseMI(`1^running`); assert.ok(parsed); assert.equal(parsed.token, 1); assert.equal(parsed.outOfBandRecord.length, 0); @@ -63,7 +63,7 @@ suite("MI Parse", () => { assert.equal(parsed.resultRecords.results.length, 0); }); test("Advanced out of band record (Breakpoint hit)", () => { - let parsed = parseMI(`*stopped,reason="breakpoint-hit",disp="keep",bkptno="1",frame={addr="0x00000000004e807f",func="D main",args=[{name="args",value="..."}],file="source/app.d",fullname="/path/to/source/app.d",line="157"},thread-id="1",stopped-threads="all",core="0"`); + const parsed = parseMI(`*stopped,reason="breakpoint-hit",disp="keep",bkptno="1",frame={addr="0x00000000004e807f",func="D main",args=[{name="args",value="..."}],file="source/app.d",fullname="/path/to/source/app.d",line="157"},thread-id="1",stopped-threads="all",core="0"`); assert.ok(parsed); assert.equal(parsed.token, undefined); assert.equal(parsed.outOfBandRecord.length, 1); @@ -73,7 +73,7 @@ suite("MI Parse", () => { assert.deepEqual(parsed.outOfBandRecord[0].output[0], ["reason", "breakpoint-hit"]); assert.deepEqual(parsed.outOfBandRecord[0].output[1], ["disp", "keep"]); assert.deepEqual(parsed.outOfBandRecord[0].output[2], ["bkptno", "1"]); - let frame = [ + const frame = [ ["addr", "0x00000000004e807f"], ["func", "D main"], ["args", [[["name", "args"], ["value", "..."]]]], @@ -88,14 +88,14 @@ suite("MI Parse", () => { assert.equal(parsed.resultRecords, undefined); }); test("Advanced result record", () => { - let parsed = parseMI(`2^done,asm_insns=[src_and_asm_line={line="134",file="source/app.d",fullname="/path/to/source/app.d",line_asm_insn=[{address="0x00000000004e7da4",func-name="_Dmain",offset="0",inst="push %rbp"},{address="0x00000000004e7da5",func-name="_Dmain",offset="1",inst="mov %rsp,%rbp"}]}]`); + const parsed = parseMI(`2^done,asm_insns=[src_and_asm_line={line="134",file="source/app.d",fullname="/path/to/source/app.d",line_asm_insn=[{address="0x00000000004e7da4",func-name="_Dmain",offset="0",inst="push %rbp"},{address="0x00000000004e7da5",func-name="_Dmain",offset="1",inst="mov %rsp,%rbp"}]}]`); assert.ok(parsed); assert.equal(parsed.token, 2); assert.equal(parsed.outOfBandRecord.length, 0); assert.notEqual(parsed.resultRecords, undefined); assert.equal(parsed.resultRecords.resultClass, "done"); assert.equal(parsed.resultRecords.results.length, 1); - let asm_insns = [ + const asm_insns = [ "asm_insns", [ [ @@ -129,7 +129,7 @@ suite("MI Parse", () => { assert.equal(parsed.result("asm_insns.src_and_asm_line.line_asm_insn[1].address"), "0x00000000004e7da5"); }); test("valueof children", () => { - let obj = [ + const obj = [ [ "frame", [ @@ -174,17 +174,17 @@ suite("MI Parse", () => { assert.equal(MINode.valueOf(obj[1], "@frame.line"), undefined); }); test("empty string values", () => { - let parsed = parseMI(`15^done,register-names=["r0","pc","","xpsr","","control"]`); - let result = parsed.result('register-names'); + const parsed = parseMI(`15^done,register-names=["r0","pc","","xpsr","","control"]`); + const result = parsed.result('register-names'); assert.deepEqual(result, ["r0", "pc", "", "xpsr", "", "control"]); }); test("empty array values", () => { - let parsed = parseMI(`15^done,foo={x=[],y="y"}`); + const parsed = parseMI(`15^done,foo={x=[],y="y"}`); assert.deepEqual(parsed.result('foo.x'), []); assert.equal(parsed.result('foo.y'), "y"); }); test("empty object values", () => { - let parsed = parseMI(`15^done,foo={x={},y="y"}`); + const parsed = parseMI(`15^done,foo={x={},y="y"}`); assert.deepEqual(parsed.result('foo.x'), {}); assert.equal(parsed.result('foo.y'), "y"); }); diff --git a/tsconfig.json b/tsconfig.json index fbda0cd6..915ff8fc 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,10 +7,15 @@ "es6" ], "sourceMap": true, - "rootDir": "." + "rootDir": ".", + "plugins": [ + { + "name": "tslint-language-service" + } + ] }, "exclude": [ "node_modules", ".vscode-test" ] -} \ No newline at end of file +} diff --git a/tslint.json b/tslint.json new file mode 100644 index 00000000..c6d41360 --- /dev/null +++ b/tslint.json @@ -0,0 +1,7 @@ +{ + "defaultSeverity": "error", + "rules": { + "no-var-keyword": true, + "prefer-const": true + } +} From d0dc094f4e4f222ab34e3c3a7314f581d293fecb Mon Sep 17 00:00:00 2001 From: Simon Marchi Date: Tue, 17 Jul 2018 18:34:44 -0400 Subject: [PATCH 2/3] tslint: Enable no-null-keyword I find this rule quite useful so that we use undefined all the time. The rationale on the rule's documentation page is quite clear: https://palantir.github.io/tslint/rules/no-null-keyword/ --- src/backend/mi2/mi2.ts | 2 +- src/mibase.ts | 2 +- tslint.json | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/backend/mi2/mi2.ts b/src/backend/mi2/mi2.ts index d1feca6a..d8d2879c 100644 --- a/src/backend/mi2/mi2.ts +++ b/src/backend/mi2/mi2.ts @@ -544,7 +544,7 @@ export class MI2 extends EventEmitter implements IBackend { this.breakpoints.set(newBrk, bkptNum); resolve([true, newBrk]); } else { - resolve([false, null]); + resolve([false, undefined]); } }, reject); } diff --git a/src/mibase.ts b/src/mibase.ts index ec083bd8..9c10fe72 100644 --- a/src/mibase.ts +++ b/src/mibase.ts @@ -294,7 +294,7 @@ export class MI2DebugSession extends DebugSession { this.miDebugger.getStack(args.levels, args.threadId).then(stack => { const ret: StackFrame[] = []; stack.forEach(element => { - let source = null; + let source = undefined; let file = element.file; if (file) { if (this.isSSH) { diff --git a/tslint.json b/tslint.json index c6d41360..24ffabe2 100644 --- a/tslint.json +++ b/tslint.json @@ -2,6 +2,7 @@ "defaultSeverity": "error", "rules": { "no-var-keyword": true, - "prefer-const": true + "prefer-const": true, + "no-null-keyword": true } } From b4d539258ec96540e33a8a2a037f6c1a95174163 Mon Sep 17 00:00:00 2001 From: Simon Marchi Date: Tue, 17 Jul 2018 18:45:43 -0400 Subject: [PATCH 3/3] tslint: Extend tslint:recommended Rather than take a whitelist approach to the rules, I think it would be better to start with some goal (for example, the tslint:recommended set of rules) and disable those that we don't follow. This way, it's easy to see which ones we could potentially enable. This doesn't mean that we have to follow all of them. If there are rules that we don't want, we can move them to a "Rules from tslint:recommended that we don't want" section. --- tslint.json | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/tslint.json b/tslint.json index 24ffabe2..92c34425 100644 --- a/tslint.json +++ b/tslint.json @@ -1,8 +1,47 @@ { "defaultSeverity": "error", + "extends": "tslint:recommended", "rules": { - "no-var-keyword": true, - "prefer-const": true, - "no-null-keyword": true + "no-null-keyword": true, + /* Rules in tslint:recommended that we don't follow yet. */ + "array-type": false, + "arrow-parens": false, + "arrow-return-shorthand": false, + "ban-types": false, + "class-name": false, + "comment-format": false, + "curly": false, + "eofline": false, + "indent": false, + "interface-name": false, + "max-classes-per-file": false, + "max-line-length": false, + "member-access": false, + "member-ordering": false, + "no-angle-bracket-type-assertion": false, + "no-bitwise": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-empty": false, + "no-shadowed-variable": false, + "no-trailing-whitespace": false, + "no-unnecessary-initializer": false, + "no-var-requires": false, + "object-literal-shorthand": false, + "object-literal-sort-keys": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "ordered-imports": false, + "prefer-for-of": false, + "quotemark": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "trailing-comma": false, + "triple-equals": false, + "typedef-whitespace": false, + "variable-name": false, + "whitespace": false } }