From 5ce8c831b44ddab60908a6ef0e81b4e18ffbb744 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Wed, 19 Jun 2019 17:58:49 +0300 Subject: [PATCH] prefer-const --- .eslintrc | 2 +- scripts/authors.ts | 2 +- scripts/buildProtocol.ts | 4 +-- scripts/errorCheck.ts | 34 +++++++++---------- .../importDefinitelyTypedTests.ts | 14 ++++---- src/compiler/debug.ts | 4 ++- src/compiler/program.ts | 3 +- src/compiler/sys.ts | 1 + src/compiler/transformers/generators.ts | 3 +- src/compiler/utilities.ts | 3 +- src/harness/harness.ts | 2 ++ src/harness/harnessLanguageService.ts | 8 ++--- src/services/services.ts | 2 +- src/services/shims.ts | 2 +- src/testRunner/runner.ts | 6 ++-- .../unittests/services/transpile.ts | 13 +++---- 16 files changed, 50 insertions(+), 53 deletions(-) diff --git a/.eslintrc b/.eslintrc index 6fd1a872d7b..622bf38c08a 100644 --- a/.eslintrc +++ b/.eslintrc @@ -112,7 +112,7 @@ "no-var": "off", "object-shorthand": "error", "one-var": "off", - "prefer-const": "off", + "prefer-const": "error", "prefer-object-spread": "error", "quote-props": ["error", "consistent-as-needed"], "quotes": ["error", "double", { "avoidEscape": true, "allowTemplateLiterals": true }], diff --git a/scripts/authors.ts b/scripts/authors.ts index 7e15e266222..9c62da393f7 100644 --- a/scripts/authors.ts +++ b/scripts/authors.ts @@ -73,7 +73,7 @@ function getKnownAuthorMaps() { } function deduplicate(array: T[]): T[] { - let result: T[] = []; + const result: T[] = []; if (array) { for (const item of array) { if (result.indexOf(item) < 0) { diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts index 123fef78b5b..b352acba12f 100644 --- a/scripts/buildProtocol.ts +++ b/scripts/buildProtocol.ts @@ -42,7 +42,7 @@ class DeclarationsWalker { return; } this.visitedTypes.push(type); - let s = type.aliasSymbol || type.getSymbol(); + const s = type.aliasSymbol || type.getSymbol(); if (!s) { return; } @@ -64,7 +64,7 @@ class DeclarationsWalker { } else { // splice declaration in final d.ts file - let text = decl.getFullText(); + const text = decl.getFullText(); this.text += `${text}\n`; // recursively pull all dependencies into result dts file diff --git a/scripts/errorCheck.ts b/scripts/errorCheck.ts index 902f001d2cd..430c5f6483f 100644 --- a/scripts/errorCheck.ts +++ b/scripts/errorCheck.ts @@ -1,35 +1,35 @@ declare var require: any; -let fs = require("fs"); -let async = require("async"); -let glob = require("glob"); +const fs = require("fs"); +const async = require("async"); +const glob = require("glob"); fs.readFile("src/compiler/diagnosticMessages.json", "utf-8", (err, data) => { if (err) { throw err; } - let messages = JSON.parse(data); - let keys = Object.keys(messages); + const messages = JSON.parse(data); + const keys = Object.keys(messages); console.log("Loaded " + keys.length + " errors"); - for (let k of keys) { + for (const k of keys) { messages[k].seen = false; } - let errRegex = /\(\d+,\d+\): error TS([^:]+):/g; + const errRegex = /\(\d+,\d+\): error TS([^:]+):/g; + const baseDir = "tests/baselines/reference/"; - let baseDir = "tests/baselines/reference/"; fs.readdir(baseDir, (err, files) => { files = files.filter(f => f.indexOf(".errors.txt") > 0); - let tasks: Array<(callback: () => void) => void> = []; + const tasks: Array<(callback: () => void) => void> = []; files.forEach(f => tasks.push(done => { fs.readFile(baseDir + f, "utf-8", (err, baseline) => { if (err) throw err; let g: string[]; while (g = errRegex.exec(baseline)) { - var errCode = +g[1]; - let msg = keys.filter(k => messages[k].code === errCode)[0]; + const errCode = +g[1]; + const msg = keys.filter(k => messages[k].code === errCode)[0]; messages[msg].seen = true; } @@ -40,7 +40,7 @@ fs.readFile("src/compiler/diagnosticMessages.json", "utf-8", (err, data) => { async.parallelLimit(tasks, 25, done => { console.log("== List of errors not present in baselines =="); let count = 0; - for (let k of keys) { + for (const k of keys) { if (messages[k].seen !== true) { console.log(k); count++; @@ -52,8 +52,8 @@ fs.readFile("src/compiler/diagnosticMessages.json", "utf-8", (err, data) => { }); fs.readFile("src/compiler/diagnosticInformationMap.generated.ts", "utf-8", (err, data) => { - let errorRegexp = /\s(\w+): \{ code/g; - let errorNames: string[] = []; + const errorRegexp = /\s(\w+): \{ code/g; + const errorNames: string[] = []; let errMatch: string[]; while (errMatch = errorRegexp.exec(data)) { errorNames.push(errMatch[1]); @@ -62,12 +62,12 @@ fs.readFile("src/compiler/diagnosticInformationMap.generated.ts", "utf-8", (err, let allSrc = ""; glob("./src/**/*.ts", {}, (err, files) => { console.log("Reading " + files.length + " source files"); - for (let file of files) { + for (const file of files) { if (file.indexOf("diagnosticInformationMap.generated.ts") > 0) { continue; } - let src = fs.readFileSync(file, "utf-8"); + const src = fs.readFileSync(file, "utf-8"); allSrc = allSrc + src; } @@ -75,7 +75,7 @@ fs.readFile("src/compiler/diagnosticInformationMap.generated.ts", "utf-8", (err, let count = 0; console.log("== List of errors not used in source =="); - for (let errName of errorNames) { + for (const errName of errorNames) { if (allSrc.indexOf(errName) < 0) { console.log(errName); count++; diff --git a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts index 270e78c128a..f58215c2612 100644 --- a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts +++ b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts @@ -42,7 +42,7 @@ function filePathEndsWith(path: string, endingString: string): boolean { } function copyFileSync(source: string, destination: string) { - let text = fs.readFileSync(source); + const text = fs.readFileSync(source); fs.writeFileSync(destination, text); } @@ -52,8 +52,8 @@ function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCas cmd += " @" + responseFile; } - let testDirectoryName = testCaseName + "_" + Math.floor((Math.random() * 10000) + 1); - let testDirectoryPath = path.join(process.env.temp, testDirectoryName); + const testDirectoryName = testCaseName + "_" + Math.floor((Math.random() * 10000) + 1); + const testDirectoryPath = path.join(process.env.temp, testDirectoryName); if (fs.existsSync(testDirectoryPath)) { throw new Error("Could not create test directory"); } @@ -77,8 +77,8 @@ function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCas } // copy generated file to output location - let outputFilePath = path.join(testDirectoryPath, "iocapture0.json"); - let testCasePath = path.join(rwcTestPath, "DefinitelyTyped_" + testCaseName + ".json"); + const outputFilePath = path.join(testDirectoryPath, "iocapture0.json"); + const testCasePath = path.join(rwcTestPath, "DefinitelyTyped_" + testCaseName + ".json"); copyFileSync(outputFilePath, testCasePath); //console.log("output generated at: " + outputFilePath); @@ -121,8 +121,8 @@ function importDefinitelyTypedTests(tscPath: string, rwcTestPath: string, defini throw err; } - let tsFiles: string[] = []; - let testFiles: string[] = []; + const tsFiles: string[] = []; + const testFiles: string[] = []; let paramFile: string; for (const filePath of files.map(f => path.join(directoryPath, f))) { diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index ee6847133c1..c8c693399e9 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -1,8 +1,10 @@ /* @internal */ namespace ts { export namespace Debug { + /* eslint-disable prefer-const */ export let currentAssertionLevel = AssertionLevel.None; export let isDebugging = false; + /* eslint-enable prefer-const */ export function shouldAssert(level: AssertionLevel): boolean { return currentAssertionLevel >= level; @@ -258,4 +260,4 @@ namespace ts { isDebugInfoEnabled = true; } } -} \ No newline at end of file +} diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 2b62da72d24..421f9c03249 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -709,7 +709,6 @@ namespace ts { const { rootNames, options, configFileParsingDiagnostics, projectReferences } = createProgramOptions; let { oldProgram } = createProgramOptions; - let program: Program; let processingDefaultLibFiles: SourceFile[] | undefined; let processingOtherFiles: SourceFile[] | undefined; let files: SourceFile[]; @@ -905,7 +904,7 @@ namespace ts { // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; - program = { + const program: Program = { getRootFileNames: () => rootNames, getSourceFile, getSourceFileByPath, diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index b1923a73a27..2fd3f5af3c7 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -635,6 +635,7 @@ namespace ts { }; // TODO: GH#18217 this is used as if it's certainly defined in many places. + // eslint-disable-next-line prefer-const export let sys: System = (() => { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 154b09dc93d..aa397ee662d 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -1975,12 +1975,11 @@ namespace ts { } function cacheExpression(node: Expression): Identifier { - let temp: Identifier; if (isGeneratedIdentifier(node) || getEmitFlags(node) & EmitFlags.HelperName) { return node; } - temp = createTempVariable(hoistVariableDeclaration); + const temp = createTempVariable(hoistVariableDeclaration); emitAssignment(temp, node, /*location*/ node); return temp; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 2a51b3caefe..3a195277e0d 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4724,7 +4724,7 @@ namespace ts { return { span, newLength }; } - export let unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + export let unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const /** * Called to merge all the changes that occurred across several versions of a script snapshot @@ -7025,6 +7025,7 @@ namespace ts { this.skipTrivia = skipTrivia || (pos => pos); } + // eslint-disable-next-line prefer-const export let objectAllocator: ObjectAllocator = { getNodeConstructor: () => Node, getTokenConstructor: () => Node, diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 029ff5c593d..065117db3dd 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -623,8 +623,10 @@ namespace Harness { ) => void; // Settings + /* eslint-disable prefer-const */ export let userSpecifiedRoot = ""; export let lightMode = false; + /* eslint-enable prefer-const */ /** Functionality for compiling TypeScript code */ export namespace Compiler { diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 897cbddbf3e..d29674b4d72 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -594,15 +594,13 @@ namespace Harness.LanguageService { getLanguageService(): ts.LanguageService { return new LanguageServiceShimProxy(this.factory.createLanguageServiceShim(this.host)); } getClassifier(): ts.Classifier { return new ClassifierShimProxy(this.factory.createClassifierShim(this.host)); } getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { - let shimResult: { + const coreServicesShim = this.factory.createCoreServicesShim(this.host); + const shimResult: { referencedFiles: ts.ShimsFileReference[]; typeReferenceDirectives: ts.ShimsFileReference[]; importedFiles: ts.ShimsFileReference[]; isLibFile: boolean; - }; - - const coreServicesShim = this.factory.createCoreServicesShim(this.host); - shimResult = unwrapJSONCallResult(coreServicesShim.getPreProcessedFileInfo(fileName, ts.ScriptSnapshot.fromString(fileContents))); + } = unwrapJSONCallResult(coreServicesShim.getPreProcessedFileInfo(fileName, ts.ScriptSnapshot.fromString(fileContents))); const convertResult: ts.PreProcessedFileInfo = { referencedFiles: [], diff --git a/src/services/services.ts b/src/services/services.ts index f5808731791..c1bf0a2de7c 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1012,7 +1012,7 @@ namespace ts { return sourceFile; } - export let disableIncrementalParsing = false; + export let disableIncrementalParsing = false; // eslint-disable-line prefer-const export function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile { // If we were given a text change range, and our version or open-ness changed, then diff --git a/src/services/shims.ts b/src/services/shims.ts index e914a4acd42..17de5f12e3e 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -14,7 +14,7 @@ // /* @internal */ -let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { return this; })(); +let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { return this; })(); // eslint-disable-line prefer-const // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ diff --git a/src/testRunner/runner.ts b/src/testRunner/runner.ts index be46d935297..455a749e207 100644 --- a/src/testRunner/runner.ts +++ b/src/testRunner/runner.ts @@ -1,5 +1,5 @@ -let runners: RunnerBase[] = []; -let iterations = 1; +const runners: RunnerBase[] = []; +const iterations = 1; function runTests(runners: RunnerBase[]) { for (let i = iterations; i > 0; i--) { @@ -50,7 +50,7 @@ const mytestconfigFileName = "mytest.config"; const testconfigFileName = "test.config"; const customConfig = tryGetConfig(Harness.IO.args()); -let testConfigContent = +const testConfigContent = customConfig && Harness.IO.fileExists(customConfig) ? Harness.IO.readFile(customConfig)! : Harness.IO.fileExists(mytestconfigFileName) diff --git a/src/testRunner/unittests/services/transpile.ts b/src/testRunner/unittests/services/transpile.ts index 8429179ffa3..2ce29f5329b 100644 --- a/src/testRunner/unittests/services/transpile.ts +++ b/src/testRunner/unittests/services/transpile.ts @@ -7,15 +7,11 @@ namespace ts { function transpilesCorrectly(name: string, input: string, testSettings: TranspileTestSettings) { describe(name, () => { - let justName: string; - let transpileOptions: TranspileOptions; - let canUseOldTranspile: boolean; - let toBeCompiled: Harness.Compiler.TestFile[]; let transpileResult: TranspileOutput; let oldTranspileResult: string; let oldTranspileDiagnostics: Diagnostic[]; - transpileOptions = testSettings.options || {}; + const transpileOptions: TranspileOptions = testSettings.options || {}; if (!transpileOptions.compilerOptions) { transpileOptions.compilerOptions = {}; } @@ -33,13 +29,12 @@ namespace ts { transpileOptions.reportDiagnostics = true; - justName = "transpile/" + name.replace(/[^a-z0-9\-. ]/ig, "") + (transpileOptions.compilerOptions.jsx ? Extension.Tsx : Extension.Ts); - toBeCompiled = [{ + const justName = "transpile/" + name.replace(/[^a-z0-9\-. ]/ig, "") + (transpileOptions.compilerOptions.jsx ? Extension.Tsx : Extension.Ts); + const toBeCompiled: Harness.Compiler.TestFile[] = [{ unitName: transpileOptions.fileName, content: input }]; - - canUseOldTranspile = !transpileOptions.renamedDependencies; + const canUseOldTranspile = !transpileOptions.renamedDependencies; before(() => { transpileResult = transpileModule(input, transpileOptions);