Enable `max-statements-per-line` lint rule (#45475)

* Enable the rule

* Fix all the violations
This commit is contained in:
Ryan Cavanaugh 2021-08-16 13:53:51 -07:00 committed by GitHub
parent 339ad92b98
commit e00b5ecd40
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 215 additions and 109 deletions

View File

@ -36,6 +36,8 @@
"@typescript-eslint/consistent-type-definitions": ["error", "interface"],
"@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "as" }],
"max-statements-per-line": ["error", { "max": 1 }],
"no-duplicate-imports": "off",
"@typescript-eslint/no-duplicate-imports": "error",

View File

@ -105,9 +105,9 @@ function createKey(name: string, code: number): string {
function convertPropertyName(origName: string): string {
let result = origName.split("").map(char => {
if (char === "*") { return "_Asterisk"; }
if (char === "/") { return "_Slash"; }
if (char === ":") { return "_Colon"; }
if (char === "*") return "_Asterisk";
if (char === "/") return "_Slash";
if (char === ":") return "_Colon";
return /\w/.test(char) ? char : "_";
}).join("");

View File

@ -102,5 +102,9 @@ async function exec(path: string, args: string[] = []) {
childProcess.execSync(cmdLine);
}
process.on("unhandledRejection", err => { throw err; });
produceLKG().then(() => console.log("Done"), err => { throw err; });
process.on("unhandledRejection", err => {
throw err;
});
produceLKG().then(() => console.log("Done"), err => {
throw err;
});

View File

@ -232,8 +232,8 @@ namespace ts {
else if (canCopySemanticDiagnostics) {
const sourceFile = newProgram.getSourceFileByPath(sourceFilePath)!;
if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; }
if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { return; }
if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) return;
if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) return;
// Unchanged file copy diagnostics
const diagnostics = oldState!.semanticDiagnosticsPerFile!.get(sourceFilePath);

View File

@ -258,9 +258,9 @@ namespace ts {
if (sourceFile.moduleAugmentations.length) {
const checker = program.getTypeChecker();
for (const moduleName of sourceFile.moduleAugmentations) {
if (!isStringLiteral(moduleName)) { continue; }
if (!isStringLiteral(moduleName)) continue;
const symbol = checker.getSymbolAtLocation(moduleName);
if (!symbol) { continue; }
if (!symbol) continue;
// Add any file other than our own as reference
addReferenceFromAmbientModule(symbol);

View File

@ -34531,7 +34531,9 @@ namespace ts {
case SyntaxKind.ImportClause:
let result = DeclarationSpaces.None;
const target = resolveAlias(getSymbolOfNode(d)!);
forEach(target.declarations, d => { result |= getDeclarationSpaces(d); });
forEach(target.declarations, d => {
result |= getDeclarationSpaces(d);
});
return result;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
@ -37943,7 +37945,9 @@ namespace ts {
return properties;
}
const seen = new Map<__String, Symbol>();
forEach(properties, p => { seen.set(p.escapedName, p); });
forEach(properties, p => {
seen.set(p.escapedName, p);
});
for (const base of baseTypes) {
const properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
@ -37966,7 +37970,9 @@ namespace ts {
interface InheritanceInfoMap { prop: Symbol; containingType: Type; }
const seen = new Map<__String, InheritanceInfoMap>();
forEach(resolveDeclaredMembers(type).declaredProperties, p => { seen.set(p.escapedName, { prop: p, containingType: type }); });
forEach(resolveDeclaredMembers(type).declaredProperties, p => {
seen.set(p.escapedName, { prop: p, containingType: type });
});
let ok = true;
for (const base of baseTypes) {

View File

@ -1568,19 +1568,29 @@ namespace ts {
export function noop(_?: {} | null | undefined): void { }
/** Do nothing and return false */
export function returnFalse(): false { return false; }
export function returnFalse(): false {
return false;
}
/** Do nothing and return true */
export function returnTrue(): true { return true; }
export function returnTrue(): true {
return true;
}
/** Do nothing and return undefined */
export function returnUndefined(): undefined { return undefined; }
export function returnUndefined(): undefined {
return undefined;
}
/** Returns its argument. */
export function identity<T>(x: T) { return x; }
export function identity<T>(x: T) {
return x;
}
/** Returns lower case string */
export function toLowerCase(x: string) { return x.toLowerCase(); }
export function toLowerCase(x: string) {
return x.toLowerCase();
}
// We convert the file names to lower case as key for file name on case insensitive file system
// While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert

View File

@ -1059,18 +1059,18 @@ namespace ts {
// @api
function createModifiersFromModifierFlags(flags: ModifierFlags) {
const result: Modifier[] = [];
if (flags & ModifierFlags.Export) { result.push(createModifier(SyntaxKind.ExportKeyword)); }
if (flags & ModifierFlags.Ambient) { result.push(createModifier(SyntaxKind.DeclareKeyword)); }
if (flags & ModifierFlags.Default) { result.push(createModifier(SyntaxKind.DefaultKeyword)); }
if (flags & ModifierFlags.Const) { result.push(createModifier(SyntaxKind.ConstKeyword)); }
if (flags & ModifierFlags.Public) { result.push(createModifier(SyntaxKind.PublicKeyword)); }
if (flags & ModifierFlags.Private) { result.push(createModifier(SyntaxKind.PrivateKeyword)); }
if (flags & ModifierFlags.Protected) { result.push(createModifier(SyntaxKind.ProtectedKeyword)); }
if (flags & ModifierFlags.Abstract) { result.push(createModifier(SyntaxKind.AbstractKeyword)); }
if (flags & ModifierFlags.Static) { result.push(createModifier(SyntaxKind.StaticKeyword)); }
if (flags & ModifierFlags.Override) { result.push(createModifier(SyntaxKind.OverrideKeyword)); }
if (flags & ModifierFlags.Readonly) { result.push(createModifier(SyntaxKind.ReadonlyKeyword)); }
if (flags & ModifierFlags.Async) { result.push(createModifier(SyntaxKind.AsyncKeyword)); }
if (flags & ModifierFlags.Export) result.push(createModifier(SyntaxKind.ExportKeyword));
if (flags & ModifierFlags.Ambient) result.push(createModifier(SyntaxKind.DeclareKeyword));
if (flags & ModifierFlags.Default) result.push(createModifier(SyntaxKind.DefaultKeyword));
if (flags & ModifierFlags.Const) result.push(createModifier(SyntaxKind.ConstKeyword));
if (flags & ModifierFlags.Public) result.push(createModifier(SyntaxKind.PublicKeyword));
if (flags & ModifierFlags.Private) result.push(createModifier(SyntaxKind.PrivateKeyword));
if (flags & ModifierFlags.Protected) result.push(createModifier(SyntaxKind.ProtectedKeyword));
if (flags & ModifierFlags.Abstract) result.push(createModifier(SyntaxKind.AbstractKeyword));
if (flags & ModifierFlags.Static) result.push(createModifier(SyntaxKind.StaticKeyword));
if (flags & ModifierFlags.Override) result.push(createModifier(SyntaxKind.OverrideKeyword));
if (flags & ModifierFlags.Readonly) result.push(createModifier(SyntaxKind.ReadonlyKeyword));
if (flags & ModifierFlags.Async) result.push(createModifier(SyntaxKind.AsyncKeyword));
return result;
}

View File

@ -556,7 +556,7 @@ namespace ts {
// Visit project references first
if (cbRef) {
const result = cbRef(projectReferences, parent);
if (result) { return result; }
if (result) return result;
}
return forEach(resolvedProjectReferences, (resolvedRef, index) => {
@ -2238,7 +2238,7 @@ namespace ts {
}
function getOptionsDiagnosticsOfConfigFile() {
if (!options.configFile) { return emptyArray; }
if (!options.configFile) return emptyArray;
let diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
forEachResolvedProjectReference(resolvedRef => {
diagnostics = concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));

View File

@ -764,14 +764,14 @@ namespace ts {
}
function removeResolutionsFromProjectReferenceRedirects(filePath: Path) {
if (!fileExtensionIs(filePath, Extension.Json)) { return; }
if (!fileExtensionIs(filePath, Extension.Json)) return;
const program = resolutionHost.getCurrentProgram();
if (!program) { return; }
if (!program) return;
// If this file is input file for the referenced project, get it
const resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
if (!resolvedProjectReference) { return; }
if (!resolvedProjectReference) return;
// filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
resolvedProjectReference.commandLine.fileNames.forEach(f => removeResolutionsOfFile(resolutionHost.toPath(f)));

View File

@ -366,7 +366,7 @@ namespace ts {
FileSystemEntryKind.Directory,
(_eventName: string, relativeFileName) => {
// When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
if (!isString(relativeFileName)) { return; }
if (!isString(relativeFileName)) return;
const fileName = getNormalizedAbsolutePath(relativeFileName, dirName);
// Some applications save a working file via rename operations
const callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));

View File

@ -601,7 +601,7 @@ namespace ts {
// Set initial build if not already built
if (!state.allProjectBuildPending) return;
state.allProjectBuildPending = false;
if (state.options.watch) { reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode); }
if (state.options.watch) reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode);
enableCache(state);
const buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
buildOrder.forEach(configFileName =>
@ -1358,7 +1358,7 @@ namespace ts {
}
if (!force) {
const inputTime = getModifiedTime(host, inputFile); host.getModifiedTime(inputFile);
const inputTime = getModifiedTime(host, inputFile);
if (inputTime > newestInputFileTime) {
newestInputFileName = inputFile;
newestInputFileTime = inputTime;

View File

@ -6702,9 +6702,9 @@ namespace ts {
}
export function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: readonly string[]): readonly string[] {
if (!options || !options.resolveJsonModule) { return supportedExtensions; }
if (supportedExtensions === allSupportedExtensions) { return allSupportedExtensionsWithJson; }
if (supportedExtensions === supportedTSExtensions) { return supportedTSExtensionsWithJson; }
if (!options || !options.resolveJsonModule) return supportedExtensions;
if (supportedExtensions === allSupportedExtensions) return allSupportedExtensionsWithJson;
if (supportedExtensions === supportedTSExtensions) return supportedTSExtensionsWithJson;
return [...supportedExtensions, Extension.Json];
}
@ -6721,7 +6721,7 @@ namespace ts {
}
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]) {
if (!fileName) { return false; }
if (!fileName) return false;
const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
for (const extension of getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions)) {

View File

@ -2100,7 +2100,7 @@ namespace FourSlash {
}
private printMembersOrCompletions(info: ts.CompletionInfo | undefined) {
if (info === undefined) { return "No completion info."; }
if (info === undefined) return "No completion info.";
const { entries } = info;
function pad(s: string, length: number) {
@ -2836,7 +2836,7 @@ namespace FourSlash {
public verifyTodoComments(descriptors: string[], spans: Range[]) {
const actual = this.languageService.getTodoComments(this.activeFile.fileName,
descriptors.map(d => { return { text: d, priority: 0 }; }));
descriptors.map(d => ({ text: d, priority: 0 })));
if (actual.length !== spans.length) {
this.raiseError(`verifyTodoComments failed - expected total spans to be ${spans.length}, but was ${actual.length}`);
@ -4498,7 +4498,7 @@ namespace FourSlash {
// put ranges in the correct order
localRanges = localRanges.sort((a, b) => a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1);
localRanges.forEach((r) => { ranges.push(r); });
localRanges.forEach(r => ranges.push(r));
return {
content: output,

View File

@ -9,7 +9,9 @@ globalThis.assert = _chai.assert;
{
// chai's builtin `assert.isFalse` is featureful but slow - we don't use those features,
// so we'll just overwrite it as an alterative to migrating a bunch of code off of chai
assert.isFalse = (expr: any, msg: string) => { if (expr !== false) throw new Error(msg); };
assert.isFalse = (expr: any, msg: string) => {
if (expr !== false) throw new Error(msg);
};
const assertDeepImpl = assert.deepEqual;
assert.deepEqual = (a, b, msg) => {

View File

@ -219,7 +219,7 @@ namespace Harness {
}
public Close() {
if (this.currentLine !== undefined) { this.lines.push(this.currentLine); }
if (this.currentLine !== undefined) this.lines.push(this.currentLine);
this.currentLine = undefined!;
}

View File

@ -113,7 +113,11 @@ namespace Utils {
});
const childNodesAndArrays: any[] = [];
ts.forEachChild(node, child => { childNodesAndArrays.push(child); }, array => { childNodesAndArrays.push(array); });
ts.forEachChild(node, child => {
childNodesAndArrays.push(child);
}, array => {
childNodesAndArrays.push(array);
});
for (const childName in node) {
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator" ||
@ -198,7 +202,9 @@ namespace Utils {
return result;
}
function getNodeFlagName(f: number) { return getFlagName((ts as any).NodeFlags, f); }
function getNodeFlagName(f: number) {
return getFlagName((ts as any).NodeFlags, f);
}
function serializeNode(n: ts.Node): any {
const o: any = { kind: getKindName(n.kind) };

View File

@ -29,7 +29,9 @@ namespace Harness {
const resChildren: ts.Node[] = [];
// push onto work queue in reverse order to maintain preorder traversal
ts.forEachChild(elem, c => { resChildren.unshift(c); });
ts.forEachChild(elem, c => {
resChildren.unshift(c);
});
work.push(...resChildren);
}
}

View File

@ -848,14 +848,18 @@ namespace vfs {
// no difference if links are empty
if (!changedLinks.size) return false;
changedLinks.forEach((node, basename) => { FileSystem.trackCreatedInode(container, basename, changed, node); });
changedLinks.forEach((node, basename) => {
FileSystem.trackCreatedInode(container, basename, changed, node);
});
return true;
}
private static trackDeletedInodes(container: FileSet, baseLinks: ReadonlyMap<string, Inode>) {
// no difference if links are empty
if (!baseLinks.size) return false;
baseLinks.forEach((node, basename) => { container[basename] = isDirectory(node) ? new Rmdir() : new Unlink(); });
baseLinks.forEach((node, basename) => {
container[basename] = isDirectory(node) ? new Rmdir() : new Unlink();
});
return true;
}

View File

@ -1581,7 +1581,9 @@ namespace ts.server {
const log = (message: string) => this.projectService.logger.info(message);
let errorLogs: string[] | undefined;
const logError = (message: string) => { (errorLogs || (errorLogs = [])).push(message); };
const logError = (message: string) => {
(errorLogs || (errorLogs = [])).push(message);
};
const resolvedModule = firstDefined(searchPaths, searchPath =>
Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError) as PluginModuleFactory | undefined);
if (resolvedModule) {

View File

@ -9,7 +9,7 @@ namespace ts.codefix {
getCodeActions(context) {
const { sourceFile } = context;
const info = getInfo(sourceFile, context.span.start, context.errorCode);
if (!info) { return undefined; }
if (!info) return undefined;
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, info));

View File

@ -53,7 +53,9 @@ namespace ts.codefix {
const token = getTokenAtPosition(sourceFile, start);
let declaration: Declaration | undefined;
const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, preferences); });
const changes = textChanges.ChangeTracker.with(context, changes => {
declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, preferences);
});
const name = declaration && getNameOfDeclaration(declaration);
return !name || changes.length === 0 ? undefined
: [createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, Diagnostics.Infer_all_types_from_usage)];

View File

@ -2197,7 +2197,7 @@ namespace ts.FindAllReferences {
}
function isStaticSymbol(symbol: Symbol): boolean {
if (!symbol.valueDeclaration) { return false; }
if (!symbol.valueDeclaration) return false;
const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration);
return !!(modifierFlags & ModifierFlags.Static);
}

View File

@ -31,7 +31,7 @@ namespace ts.OrganizeImports {
organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
if (!ambientModule.body) { continue; }
if (!ambientModule.body) continue;
const ambientModuleImportDecls = ambientModule.body.statements.filter(isImportDeclaration);
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);

View File

@ -139,7 +139,9 @@ namespace ts {
if (isJSDocCommentContainingNode(node)) {
/** Don't add trivia for "tokens" since this is in a comment. */
node.forEachChild(child => { children.push(child); });
node.forEachChild(child => {
children.push(child);
});
return children;
}

View File

@ -14,7 +14,9 @@
//
/* @internal */
let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { return this; })(); // eslint-disable-line prefer-const
let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { // eslint-disable-line prefer-const
return this;
})();
// We need to use 'null' to interface with the managed side.
/* eslint-disable no-in-operator */

View File

@ -1024,7 +1024,12 @@ namespace ts.textChanges {
delta = formatting.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? (formatOptions.indentSize || 0) : 0;
}
const file: SourceFileLike = { text, getLineAndCharacterOfPosition(pos) { return getLineAndCharacterOfPosition(this, pos); } };
const file: SourceFileLike = {
text,
getLineAndCharacterOfPosition(pos) {
return getLineAndCharacterOfPosition(this, pos);
}
};
const changes = formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions });
return applyChanges(text, changes);
}

View File

@ -2164,19 +2164,19 @@ namespace ts {
if (flags & SymbolFlags.Variable) {
return isFirstDeclarationOfSymbolParameter(symbol) ? SymbolDisplayPartKind.parameterName : SymbolDisplayPartKind.localName;
}
else if (flags & SymbolFlags.Property) { return SymbolDisplayPartKind.propertyName; }
else if (flags & SymbolFlags.GetAccessor) { return SymbolDisplayPartKind.propertyName; }
else if (flags & SymbolFlags.SetAccessor) { return SymbolDisplayPartKind.propertyName; }
else if (flags & SymbolFlags.EnumMember) { return SymbolDisplayPartKind.enumMemberName; }
else if (flags & SymbolFlags.Function) { return SymbolDisplayPartKind.functionName; }
else if (flags & SymbolFlags.Class) { return SymbolDisplayPartKind.className; }
else if (flags & SymbolFlags.Interface) { return SymbolDisplayPartKind.interfaceName; }
else if (flags & SymbolFlags.Enum) { return SymbolDisplayPartKind.enumName; }
else if (flags & SymbolFlags.Module) { return SymbolDisplayPartKind.moduleName; }
else if (flags & SymbolFlags.Method) { return SymbolDisplayPartKind.methodName; }
else if (flags & SymbolFlags.TypeParameter) { return SymbolDisplayPartKind.typeParameterName; }
else if (flags & SymbolFlags.TypeAlias) { return SymbolDisplayPartKind.aliasName; }
else if (flags & SymbolFlags.Alias) { return SymbolDisplayPartKind.aliasName; }
if (flags & SymbolFlags.Property) return SymbolDisplayPartKind.propertyName;
if (flags & SymbolFlags.GetAccessor) return SymbolDisplayPartKind.propertyName;
if (flags & SymbolFlags.SetAccessor) return SymbolDisplayPartKind.propertyName;
if (flags & SymbolFlags.EnumMember) return SymbolDisplayPartKind.enumMemberName;
if (flags & SymbolFlags.Function) return SymbolDisplayPartKind.functionName;
if (flags & SymbolFlags.Class) return SymbolDisplayPartKind.className;
if (flags & SymbolFlags.Interface) return SymbolDisplayPartKind.interfaceName;
if (flags & SymbolFlags.Enum) return SymbolDisplayPartKind.enumName;
if (flags & SymbolFlags.Module) return SymbolDisplayPartKind.moduleName;
if (flags & SymbolFlags.Method) return SymbolDisplayPartKind.methodName;
if (flags & SymbolFlags.TypeParameter) return SymbolDisplayPartKind.typeParameterName;
if (flags & SymbolFlags.TypeAlias) return SymbolDisplayPartKind.aliasName;
if (flags & SymbolFlags.Alias) return SymbolDisplayPartKind.aliasName;
return SymbolDisplayPartKind.text;
}
@ -2254,14 +2254,14 @@ namespace ts {
: "linkplain";
const parts = [linkPart(`{@${prefix} `)];
if (!link.name) {
if (link.text) {parts.push(linkTextPart(link.text));}
if (link.text) parts.push(linkTextPart(link.text));
}
else {
const symbol = checker?.getSymbolAtLocation(link.name);
const decl = symbol?.valueDeclaration || symbol?.declarations?.[0];
if (decl) {
parts.push(linkNamePart(link.name, decl));
if (link.text) {parts.push(linkTextPart(link.text));}
if (link.text) parts.push(linkTextPart(link.text));
}
else {
parts.push(linkTextPart(getTextOfNode(link.name) + " " + link.text));
@ -2638,7 +2638,7 @@ namespace ts {
export function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined {
const checker = program.getTypeChecker();
let typeIsAccessible = true;
const notAccessible = () => { typeIsAccessible = false; };
const notAccessible = () => typeIsAccessible = false;
const res = checker.typeToTypeNode(type, enclosingScope, NodeBuilderFlags.NoTruncation, {
trackSymbol: (symbol, declaration, meaning) => {
typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === SymbolAccessibility.Accessible;
@ -2798,8 +2798,12 @@ namespace ts {
}
export function tryAndIgnoreErrors<T>(cb: () => T): T | undefined {
try { return cb(); }
catch { return undefined; }
try {
return cb();
}
catch {
return undefined;
}
}
export function tryIOAndConsumeErrors<T>(host: unknown, toApply: ((...a: any[]) => T) | undefined, ...args: any[]) {

View File

@ -85,13 +85,15 @@ namespace Harness {
}
compilerTest = new CompilerTest(fileName, payload, configuration);
});
it(`Correct errors for ${fileName}`, () => { compilerTest.verifyDiagnostics(); });
it(`Correct module resolution tracing for ${fileName}`, () => { compilerTest.verifyModuleResolution(); });
it(`Correct sourcemap content for ${fileName}`, () => { compilerTest.verifySourceMapRecord(); });
it(`Correct JS output for ${fileName}`, () => { if (this.emit) compilerTest.verifyJavaScriptOutput(); });
it(`Correct Sourcemap output for ${fileName}`, () => { compilerTest.verifySourceMapOutput(); });
it(`Correct type/symbol baselines for ${fileName}`, () => { compilerTest.verifyTypesAndSymbols(); });
after(() => { compilerTest = undefined!; });
it(`Correct errors for ${fileName}`, () => compilerTest.verifyDiagnostics());
it(`Correct module resolution tracing for ${fileName}`, () => compilerTest.verifyModuleResolution());
it(`Correct sourcemap content for ${fileName}`, () => compilerTest.verifySourceMapRecord());
it(`Correct JS output for ${fileName}`, () => (this.emit && compilerTest.verifyJavaScriptOutput()));
it(`Correct Sourcemap output for ${fileName}`, () => compilerTest.verifySourceMapOutput());
it(`Correct type/symbol baselines for ${fileName}`, () => compilerTest.verifyTypesAndSymbols());
after(() => {
compilerTest = undefined!;
});
}
private parseOptions() {

View File

@ -98,10 +98,10 @@ namespace Harness.Parallel.Worker {
*/
function shimTestInterface(rootSuite: Mocha.Suite, context: Mocha.MochaGlobals) {
const suites = [rootSuite];
context.before = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].beforeAll(title as string, fn); };
context.after = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].afterAll(title as string, fn); };
context.beforeEach = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].beforeEach(title as string, fn); };
context.afterEach = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].afterEach(title as string, fn); };
context.before = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => suites[0].beforeAll(title as string, fn);
context.after = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => suites[0].afterAll(title as string, fn);
context.beforeEach = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => suites[0].beforeEach(title as string, fn);
context.afterEach = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => suites[0].afterEach(title as string, fn);
context.describe = context.context = ((title: string, fn: (this: Mocha.Suite) => void) => addSuite(title, fn)) as Mocha.SuiteFunction;
context.describe.skip = context.xdescribe = context.xcontext = (title: string) => addSuite(title, /*fn*/ undefined);
context.describe.only = (title: string, fn?: (this: Mocha.Suite) => void) => addSuite(title, fn);

View File

@ -56,14 +56,18 @@ namespace project {
for (const { name, payload } of ProjectTestCase.getConfigurations(testCaseFileName)) {
describe("Compiling project for " + payload.testCase.scenario + ": testcase " + testCaseFileName + (name ? ` (${name})` : ``), () => {
let projectTestCase: ProjectTestCase | undefined;
before(() => { projectTestCase = new ProjectTestCase(testCaseFileName, payload); });
before(() => {
projectTestCase = new ProjectTestCase(testCaseFileName, payload);
});
it(`Correct module resolution tracing for ${testCaseFileName}`, () => projectTestCase && projectTestCase.verifyResolution());
it(`Correct errors for ${testCaseFileName}`, () => projectTestCase && projectTestCase.verifyDiagnostics());
it(`Correct JS output for ${testCaseFileName}`, () => projectTestCase && projectTestCase.verifyJavaScriptOutput());
// NOTE: This check was commented out in previous code. Leaving this here to eventually be restored if needed.
// it(`Correct sourcemap content for ${testCaseFileName}`, () => projectTestCase && projectTestCase.verifySourceMapRecord());
it(`Correct declarations for ${testCaseFileName}`, () => projectTestCase && projectTestCase.verifyDeclarations());
after(() => { projectTestCase = undefined; });
after(() => {
projectTestCase = undefined;
});
});
}
}

View File

@ -319,7 +319,7 @@ namespace ts {
map.set("c", "d");
map.set("a", "b");
const actual: [string, string][] = [];
map.forEach((value, key) => { actual.push([key, value]); });
map.forEach((value, key) => actual.push([key, value]));
assert.deepEqual(actual, [["c", "d"], ["a", "b"]]);
});
});

View File

@ -302,7 +302,7 @@ namespace ts {
set.add("c");
set.add("a");
const actual: [string, string][] = [];
set.forEach((value, key) => { actual.push([key, value]); });
set.forEach((value, key) => actual.push([key, value]));
assert.deepEqual(actual, [["c", "c"], ["a", "a"]]);
});
});

View File

@ -13,7 +13,11 @@ namespace ts {
typeScriptVersion: "3.8"
});
let logWritten = false;
Debug.loggingHost = { log() { logWritten = true; } };
Debug.loggingHost = {
log() {
logWritten = true;
}
};
deprecation();
assert.isFalse(logWritten);
});
@ -23,7 +27,11 @@ namespace ts {
typeScriptVersion: "3.9"
});
let logWritten = false;
Debug.loggingHost = { log() { logWritten = true; } };
Debug.loggingHost = {
log() {
logWritten = true;
}
};
deprecation();
assert.isTrue(logWritten);
});
@ -32,7 +40,11 @@ namespace ts {
typeScriptVersion: "3.9"
});
let logWritten = false;
Debug.loggingHost = { log() { logWritten = true; } };
Debug.loggingHost = {
log() {
logWritten = true;
}
};
deprecation();
assert.isTrue(logWritten);
});
@ -41,7 +53,11 @@ namespace ts {
typeScriptVersion: "3.9"
});
let logWrites = 0;
Debug.loggingHost = { log() { logWrites++; } };
Debug.loggingHost = {
log() {
logWrites++;
}
};
deprecation();
deprecation();
assert.equal(logWrites, 1);
@ -53,7 +69,11 @@ namespace ts {
typeScriptVersion: "3.9"
});
let logWritten = false;
Debug.loggingHost = { log() { logWritten = true; } };
Debug.loggingHost = {
log() {
logWritten = true;
}
};
expect(deprecation).throws();
assert.isFalse(logWritten);
});
@ -62,7 +82,11 @@ namespace ts {
error: true,
});
let logWritten = false;
Debug.loggingHost = { log() { logWritten = true; } };
Debug.loggingHost = {
log() {
logWritten = true;
}
};
expect(deprecation).throws();
assert.isFalse(logWritten);
});

View File

@ -23,15 +23,34 @@ describe("unittests:: services:: Colorization", () => {
return undefined;
}
function punctuation(text: string, position?: number) { return createClassification(text, ts.TokenClass.Punctuation, position); }
function keyword(text: string, position?: number) { return createClassification(text, ts.TokenClass.Keyword, position); }
function operator(text: string, position?: number) { return createClassification(text, ts.TokenClass.Operator, position); }
function comment(text: string, position?: number) { return createClassification(text, ts.TokenClass.Comment, position); }
function whitespace(text: string, position?: number) { return createClassification(text, ts.TokenClass.Whitespace, position); }
function identifier(text: string, position?: number) { return createClassification(text, ts.TokenClass.Identifier, position); }
function numberLiteral(text: string, position?: number) { return createClassification(text, ts.TokenClass.NumberLiteral, position); }
function stringLiteral(text: string, position?: number) { return createClassification(text, ts.TokenClass.StringLiteral, position); }
function finalEndOfLineState(value: number): ClassificationEntry { return { value, classification: undefined!, position: 0 }; } // TODO: GH#18217
function punctuation(text: string, position?: number) {
return createClassification(text, ts.TokenClass.Punctuation, position);
}
function keyword(text: string, position?: number) {
return createClassification(text, ts.TokenClass.Keyword, position);
}
function operator(text: string, position?: number) {
return createClassification(text, ts.TokenClass.Operator, position);
}
function comment(text: string, position?: number) {
return createClassification(text, ts.TokenClass.Comment, position);
}
function whitespace(text: string, position?: number) {
return createClassification(text, ts.TokenClass.Whitespace, position);
}
function identifier(text: string, position?: number) {
return createClassification(text, ts.TokenClass.Identifier, position);
}
function numberLiteral(text: string, position?: number) {
return createClassification(text, ts.TokenClass.NumberLiteral, position);
}
function stringLiteral(text: string, position?: number) {
return createClassification(text, ts.TokenClass.StringLiteral, position);
}
function finalEndOfLineState(value: number): ClassificationEntry {
// TODO: GH#18217
return { value, classification: undefined!, position: 0 };
}
function createClassification(value: string, classification: ts.TokenClass, position?: number): ClassificationEntry {
return { value, classification, position };
}

View File

@ -2,7 +2,9 @@ namespace ts {
describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => {
let outFileFs: vfs.FileSystem;
const enum Project { lib, app }
function relName(path: string) { return path.slice(1); }
function relName(path: string) {
return path.slice(1);
}
type Sources = [string, readonly string[]];
const enum Source { config, ts }
const sources: [Sources, Sources] = [

View File

@ -4,7 +4,9 @@ namespace ts {
const enum Ext { js, jsmap, dts, dtsmap, buildinfo }
const enum Project { first, second, third }
type OutputFile = [string, string, string, string, string];
function relName(path: string) { return path.slice(1); }
function relName(path: string) {
return path.slice(1);
}
const outputFiles: [OutputFile, OutputFile, OutputFile] = [
[
"/src/first/bin/first-output.js",