From 1f3a98123e63454efd4a7ca9bed2f57f2276631b Mon Sep 17 00:00:00 2001 From: ark120202 Date: Sun, 10 May 2020 00:32:03 +0000 Subject: [PATCH 1/3] Set "arrowParens" option to "always" --- .prettierrc.json | 3 +- src/LuaPrinter.ts | 27 ++++++------- src/cli/information.ts | 2 +- src/cli/parse.ts | 12 +++--- src/cli/report.ts | 2 +- src/cli/tsconfig.ts | 2 +- src/lualib/StringReplace.ts | 2 +- src/transformation/context/context.ts | 6 +-- src/transformation/utils/annotations.ts | 6 +-- src/transformation/utils/export.ts | 6 +-- src/transformation/utils/function-context.ts | 10 ++--- src/transformation/utils/lua-ast.ts | 4 +- src/transformation/utils/safe-names.ts | 4 +- src/transformation/utils/scope.ts | 6 +-- src/transformation/utils/typescript/index.ts | 4 +- src/transformation/utils/typescript/types.ts | 14 +++---- .../visitors/binary-expression/assignments.ts | 6 +-- src/transformation/visitors/call.ts | 4 +- .../visitors/class/decorators.ts | 4 +- src/transformation/visitors/class/index.ts | 10 ++--- .../visitors/class/members/accessors.ts | 4 +- .../visitors/class/members/constructor.ts | 2 +- src/transformation/visitors/class/utils.ts | 4 +- src/transformation/visitors/conditional.ts | 2 +- src/transformation/visitors/function.ts | 4 +- src/transformation/visitors/literal.ts | 16 ++++---- src/transformation/visitors/loops/for-of.ts | 6 +-- src/transformation/visitors/loops/for.ts | 2 +- src/transformation/visitors/modules/export.ts | 6 +-- src/transformation/visitors/modules/import.ts | 4 +- src/transformation/visitors/namespace.ts | 4 +- src/transformation/visitors/return.ts | 2 +- src/transformation/visitors/template.ts | 10 ++--- .../visitors/variable-declaration.ts | 10 +++-- src/transpilation/bundle.ts | 6 +-- src/transpilation/emit.ts | 2 +- src/transpilation/index.ts | 2 +- src/transpilation/transformers.ts | 6 +-- src/transpilation/transpile.ts | 6 +-- src/tstl.ts | 6 +-- test/cli/parse.spec.ts | 4 +- test/cli/run.ts | 4 +- test/cli/watch.spec.ts | 4 +- test/legacy-utils.ts | 10 ++--- test/setup.ts | 6 ++- test/translation/transformation.spec.ts | 4 +- test/transpile/plugins/plugins.spec.ts | 2 +- test/transpile/run.ts | 2 +- test/transpile/transformers/fixtures.ts | 25 ++++++------ .../transformers/transformers.spec.ts | 2 +- test/transpile/transformers/utils.ts | 2 +- .../annotations/compileMembersOnly.spec.ts | 4 +- test/unit/annotations/extension.spec.ts | 6 +-- test/unit/annotations/forRange.spec.ts | 4 +- test/unit/annotations/luaTable.spec.ts | 38 +++++++++---------- test/unit/annotations/tupleReturn.spec.ts | 2 +- test/unit/annotations/vararg.spec.ts | 8 ++-- test/unit/assignments.spec.ts | 30 +++++++-------- test/unit/builtins/array.spec.ts | 12 +++--- test/unit/builtins/console.spec.ts | 12 +++--- test/unit/builtins/loading.spec.ts | 12 +++--- test/unit/builtins/map.spec.ts | 6 +-- test/unit/builtins/math.spec.ts | 18 ++++----- test/unit/builtins/numbers.spec.ts | 18 ++++----- test/unit/builtins/object.spec.ts | 8 ++-- test/unit/builtins/set.spec.ts | 4 +- test/unit/builtins/string.spec.ts | 14 +++---- test/unit/builtins/symbol.spec.ts | 4 +- test/unit/builtins/weakMap.spec.ts | 2 +- test/unit/builtins/weakSet.spec.ts | 2 +- test/unit/classes/classes.spec.ts | 2 +- test/unit/conditionals.spec.ts | 28 +++++++------- test/unit/destructuring.spec.ts | 10 ++--- test/unit/enum.spec.ts | 4 +- test/unit/error.spec.ts | 8 ++-- test/unit/expressions.spec.ts | 35 +++++++++-------- test/unit/functions/functions.spec.ts | 10 ++--- .../functions/noImplicitSelfOption.spec.ts | 2 +- test/unit/functions/noSelfAnnotation.spec.ts | 4 +- .../functionExpressionTypeInference.spec.ts | 6 +-- .../invalidFunctionAssignments.spec.ts | 2 +- .../validFunctionAssignments.spec.ts | 2 +- test/unit/hoisting.spec.ts | 6 +-- test/unit/identifiers.spec.ts | 36 +++++++++--------- test/unit/json.spec.ts | 2 +- test/unit/loops.spec.ts | 4 +- test/unit/modules/modules.spec.ts | 10 ++--- test/unit/modules/resolution.spec.ts | 2 +- test/unit/nullishCoalescing.spec.ts | 8 ++-- test/unit/objectLiteral.spec.ts | 6 +-- test/unit/printer/parenthesis.spec.ts | 4 +- test/unit/printer/semicolons.spec.ts | 2 +- test/unit/printer/sourcemaps.spec.ts | 4 +- test/unit/spread.spec.ts | 31 +++++++-------- test/unit/templateLiterals.spec.ts | 15 +++++--- test/unit/typeof.spec.ts | 14 +++---- test/util.ts | 16 ++++---- 97 files changed, 396 insertions(+), 384 deletions(-) diff --git a/.prettierrc.json b/.prettierrc.json index f8774a2f2..c1af7b57f 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -3,5 +3,6 @@ "tabWidth": 4, "trailingComma": "es5", "endOfLine": "lf", - "overrides": [{ "files": ["**/*.md", "**/*.yml"], "options": { "tabWidth": 2 } }] + "overrides": [{ "files": ["**/*.md", "**/*.yml"], "options": { "tabWidth": 2 } }], + "arrowParens": "always" } diff --git a/src/LuaPrinter.ts b/src/LuaPrinter.ts index 63654c595..df479996e 100644 --- a/src/LuaPrinter.ts +++ b/src/LuaPrinter.ts @@ -23,7 +23,8 @@ const escapeStringMap: Record = { "\0": "\\0", }; -export const escapeString = (value: string) => `"${value.replace(escapeStringRegExp, char => escapeStringMap[char])}"`; +export const escapeString = (value: string) => + `"${value.replace(escapeStringRegExp, (char) => escapeStringMap[char])}"`; /** * Checks that a name is valid for use in lua function declaration syntax: @@ -45,7 +46,7 @@ function isSimpleExpression(expression: lua.Expression): boolean { case lua.SyntaxKind.TableExpression: const tableExpression = expression as lua.TableExpression; - return tableExpression.fields.every(e => isSimpleExpression(e)); + return tableExpression.fields.every((e) => isSimpleExpression(e)); case lua.SyntaxKind.TableFieldExpression: const fieldExpression = expression as lua.TableFieldExpression; @@ -271,7 +272,7 @@ export class LuaPrinter { private nodeStartsWithParenthesis(sourceNode: SourceNode): boolean { let result: boolean | undefined; - sourceNode.walk(chunk => { + sourceNode.walk((chunk) => { if (result === undefined) { chunk = chunk.trimLeft(); // Ignore leading whitespace @@ -358,11 +359,11 @@ export class LuaPrinter { // Print all local functions as `local function foo()` instead of `local foo = function` to allow recursion chunks.push(this.printFunctionDefinition(statement)); } else { - chunks.push(...this.joinChunksWithComma(statement.left.map(e => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.left.map((e) => this.printExpression(e)))); if (statement.right) { chunks.push(" = "); - chunks.push(...this.joinChunksWithComma(statement.right.map(e => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.right.map((e) => this.printExpression(e)))); } } @@ -386,9 +387,9 @@ export class LuaPrinter { } } - chunks.push(...this.joinChunksWithComma(statement.left.map(e => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.left.map((e) => this.printExpression(e)))); chunks.push(" = "); - chunks.push(...this.joinChunksWithComma(statement.right.map(e => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.right.map((e) => this.printExpression(e)))); return this.createSourceNode(statement, chunks); } @@ -472,8 +473,8 @@ export class LuaPrinter { } public printForInStatement(statement: lua.ForInStatement): SourceNode { - const names = this.joinChunksWithComma(statement.names.map(i => this.printIdentifier(i))); - const expressions = this.joinChunksWithComma(statement.expressions.map(e => this.printExpression(e))); + const names = this.joinChunksWithComma(statement.names.map((i) => this.printIdentifier(i))); + const expressions = this.joinChunksWithComma(statement.expressions.map((e) => this.printExpression(e))); const chunks: SourceChunk[] = []; @@ -502,7 +503,7 @@ export class LuaPrinter { const chunks: SourceChunk[] = []; - chunks.push(...this.joinChunksWithComma(statement.expressions.map(e => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.expressions.map((e) => this.printExpression(e)))); return this.createSourceNode(statement, [this.indent(), "return ", ...chunks]); } @@ -573,7 +574,7 @@ export class LuaPrinter { } private printFunctionParameters(expression: lua.FunctionExpression): SourceChunk[] { - const parameterChunks = (expression.params ?? []).map(i => this.printIdentifier(i)); + const parameterChunks = (expression.params ?? []).map((i) => this.printIdentifier(i)); if (expression.dots) { parameterChunks.push(this.printDotsLiteral(expression.dots)); @@ -594,7 +595,7 @@ export class LuaPrinter { chunks.push(" "); const returnNode: SourceChunk[] = [ "return ", - ...this.joinChunksWithComma(returnStatement.expressions.map(e => this.printExpression(e))), + ...this.joinChunksWithComma(returnStatement.expressions.map((e) => this.printExpression(e))), ]; chunks.push(this.createSourceNode(returnStatement, returnNode)); chunks.push(this.createSourceNode(expression, " end")); @@ -750,7 +751,7 @@ export class LuaPrinter { const chunks: SourceChunk[] = []; if (expressions.every(isSimpleExpression)) { - chunks.push(...this.joinChunksWithComma(expressions.map(e => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(expressions.map((e) => this.printExpression(e)))); } else { chunks.push("\n"); this.pushIndent(); diff --git a/src/cli/information.ts b/src/cli/information.ts index 4c4b3ce1a..2ab1f8d8f 100644 --- a/src/cli/information.ts +++ b/src/cli/information.ts @@ -19,7 +19,7 @@ export function getHelpString(): string { result += "Options:\n"; for (const option of optionDeclarations) { - const aliasStrings = (option.aliases ?? []).map(a => "-" + a); + const aliasStrings = (option.aliases ?? []).map((a) => "-" + a); const optionString = [...aliasStrings, "--" + option.name].join("|"); const valuesHint = option.type === "enum" ? option.choices.join("|") : option.type; diff --git a/src/cli/parse.ts b/src/cli/parse.ts index 1ffa50d6a..d7040daf3 100644 --- a/src/cli/parse.ts +++ b/src/cli/parse.ts @@ -72,7 +72,7 @@ export const optionDeclarations: CommandLineOption[] = [ export function updateParsedConfigFile(parsedConfigFile: ts.ParsedCommandLine): ParsedCommandLine { let hasRootLevelOptions = false; for (const [name, rawValue] of Object.entries(parsedConfigFile.raw)) { - const option = optionDeclarations.find(option => option.name === name); + const option = optionDeclarations.find((option) => option.name === name); if (!option) continue; if (parsedConfigFile.raw.tstl === undefined) parsedConfigFile.raw.tstl = {}; @@ -86,7 +86,7 @@ export function updateParsedConfigFile(parsedConfigFile: ts.ParsedCommandLine): } for (const [name, rawValue] of Object.entries(parsedConfigFile.raw.tstl)) { - const option = optionDeclarations.find(option => option.name === name); + const option = optionDeclarations.find((option) => option.name === name); if (!option) { parsedConfigFile.errors.push(cliDiagnostics.unknownCompilerOption(name)); continue; @@ -111,10 +111,10 @@ function updateParsedCommandLine(parsedCommandLine: ts.ParsedCommandLine, args: const isShorthand = !args[i].startsWith("--"); const argumentName = args[i].substr(isShorthand ? 1 : 2); - const option = optionDeclarations.find(option => { + const option = optionDeclarations.find((option) => { if (option.name.toLowerCase() === argumentName.toLowerCase()) return true; if (isShorthand && option.aliases) { - return option.aliases.some(a => a.toLowerCase() === argumentName.toLowerCase()); + return option.aliases.some((a) => a.toLowerCase() === argumentName.toLowerCase()); } return false; @@ -124,7 +124,7 @@ function updateParsedCommandLine(parsedCommandLine: ts.ParsedCommandLine, args: // Ignore errors caused by tstl specific compiler options const tsInvalidCompilerOptionErrorCode = 5023; parsedCommandLine.errors = parsedCommandLine.errors.filter( - e => !(e.code === tsInvalidCompilerOptionErrorCode && String(e.messageText).endsWith(`'${args[i]}'.`)) + (e) => !(e.code === tsInvalidCompilerOptionErrorCode && String(e.messageText).endsWith(`'${args[i]}'.`)) ); const { error, value, increment } = readCommandLineArgument(option, args[i + 1]); @@ -192,7 +192,7 @@ function readValue(option: CommandLineOption, value: unknown): ReadValueResult { }; } - const enumValue = option.choices.find(c => c.toLowerCase() === value.toLowerCase()); + const enumValue = option.choices.find((c) => c.toLowerCase() === value.toLowerCase()); if (enumValue === undefined) { const optionChoices = option.choices.join(", "); return { diff --git a/src/cli/report.ts b/src/cli/report.ts index 19fd02d1e..5cea5de97 100644 --- a/src/cli/report.ts +++ b/src/cli/report.ts @@ -5,5 +5,5 @@ export const prepareDiagnosticForFormatting = (diagnostic: ts.Diagnostic) => export function createDiagnosticReporter(pretty: boolean, system = ts.sys): ts.DiagnosticReporter { const reporter = ts.createDiagnosticReporter(system, pretty); - return diagnostic => reporter(prepareDiagnosticForFormatting(diagnostic)); + return (diagnostic) => reporter(prepareDiagnosticForFormatting(diagnostic)); } diff --git a/src/cli/tsconfig.ts b/src/cli/tsconfig.ts index bec7c2d31..07c472334 100644 --- a/src/cli/tsconfig.ts +++ b/src/cli/tsconfig.ts @@ -56,7 +56,7 @@ export function createConfigFileUpdater( optionsToExtend: CompilerOptions ): (options: ts.CompilerOptions) => ts.Diagnostic[] { const configFileMap = new WeakMap(); - return options => { + return (options) => { const { configFile, configFilePath } = options; if (!configFile || !configFilePath) return []; diff --git a/src/lualib/StringReplace.ts b/src/lualib/StringReplace.ts index 7a22992ed..bed78bb9a 100644 --- a/src/lualib/StringReplace.ts +++ b/src/lualib/StringReplace.ts @@ -14,7 +14,7 @@ function __TS__StringReplace( const [result] = string.gsub( source, searchValue, - match => (replaceValue as (substring: string) => string)(match), + (match) => (replaceValue as (substring: string) => string)(match), 1 ); return result; diff --git a/src/transformation/context/context.ts b/src/transformation/context/context.ts index e310a9e19..da412426e 100644 --- a/src/transformation/context/context.ts +++ b/src/transformation/context/context.ts @@ -54,7 +54,7 @@ export class TransformationContext { public transformNode(node: ts.Node, isExpression?: boolean): lua.Node[]; public transformNode(node: ts.Node, isExpression?: boolean): lua.Node[] { // TODO: Move to visitors? - if (node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DeclareKeyword)) { + if (node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword)) { return []; } @@ -105,10 +105,10 @@ export class TransformationContext { } public transformStatements(node: StatementLikeNode | readonly StatementLikeNode[]): lua.Statement[] { - return castArray(node).flatMap(n => this.transformNode(n) as lua.Statement[]); + return castArray(node).flatMap((n) => this.transformNode(n) as lua.Statement[]); } public superTransformStatements(node: StatementLikeNode | readonly StatementLikeNode[]): lua.Statement[] { - return castArray(node).flatMap(n => this.superTransformNode(n) as lua.Statement[]); + return castArray(node).flatMap((n) => this.superTransformNode(n) as lua.Statement[]); } } diff --git a/src/transformation/utils/annotations.ts b/src/transformation/utils/annotations.ts index bd9d052ab..c2cb3f890 100644 --- a/src/transformation/utils/annotations.ts +++ b/src/transformation/utils/annotations.ts @@ -25,7 +25,7 @@ export interface Annotation { } function createAnnotation(name: string, args: string[]): Annotation | undefined { - const kind = Object.values(AnnotationKind).find(k => k.toLowerCase() === name.toLowerCase()); + const kind = Object.values(AnnotationKind).find((k) => k.toLowerCase() === name.toLowerCase()); if (kind !== undefined) { return { kind, args }; } @@ -78,7 +78,7 @@ export function getFileAnnotations(sourceFile: ts.SourceFile): AnnotationsMap { // Manually collect jsDoc because `getJSDocTags` includes tags only from closest comment const jsDoc = sourceFile.statements[0].jsDoc; if (jsDoc) { - for (const tag of jsDoc.flatMap(x => x.tags ?? [])) { + for (const tag of jsDoc.flatMap((x) => x.tags ?? [])) { const tagName = tag.tagName.text; const annotation = createAnnotation(tagName, tag.comment ? tag.comment.split(" ") : []); if (annotation) { @@ -157,7 +157,7 @@ export function isInTupleReturnFunction(context: TransformationContext, node: ts // Check all overloads for directive const signatures = functionType.getCallSignatures(); - if (signatures?.some(s => getSignatureAnnotations(context, s).has(AnnotationKind.TupleReturn))) { + if (signatures?.some((s) => getSignatureAnnotations(context, s).has(AnnotationKind.TupleReturn))) { return true; } diff --git a/src/transformation/utils/export.ts b/src/transformation/utils/export.ts index d11109427..b7d334f5d 100644 --- a/src/transformation/utils/export.ts +++ b/src/transformation/utils/export.ts @@ -7,7 +7,7 @@ import { getSymbolInfo } from "./symbols"; import { findFirstNodeAbove } from "./typescript"; export function hasDefaultExportModifier(node: ts.Node): boolean { - return (node.modifiers ?? []).some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword); + return (node.modifiers ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword); } export const createDefaultExportIdentifier = (original: ts.Node): lua.Identifier => @@ -19,7 +19,7 @@ export const createDefaultExportStringLiteral = (original: ts.Node): lua.StringL export function getExportedSymbolDeclaration(symbol: ts.Symbol): ts.Declaration | undefined { const declarations = symbol.getDeclarations(); if (declarations) { - return declarations.find(d => (ts.getCombinedModifierFlags(d) & ts.ModifierFlags.Export) !== 0); + return declarations.find((d) => (ts.getCombinedModifierFlags(d) & ts.ModifierFlags.Export) !== 0); } } @@ -94,7 +94,7 @@ export function getExportedSymbolsFromScope( } export function getDependenciesOfSymbol(context: TransformationContext, originalSymbol: ts.Symbol): ts.Symbol[] { - return getExportedSymbolsFromScope(context, context.sourceFile).filter(exportSymbol => + return getExportedSymbolsFromScope(context, context.sourceFile).filter((exportSymbol) => exportSymbol.declarations .filter(ts.isExportSpecifier) .map(context.checker.getExportSpecifierLocalTargetSymbol) diff --git a/src/transformation/utils/function-context.ts b/src/transformation/utils/function-context.ts index 8bf05255c..980ccc005 100644 --- a/src/transformation/utils/function-context.ts +++ b/src/transformation/utils/function-context.ts @@ -30,7 +30,7 @@ function hasNoSelfAncestor(declaration: ts.Declaration): boolean { function getExplicitThisParameter(signatureDeclaration: ts.SignatureDeclaration): ts.ParameterDeclaration | undefined { return signatureDeclaration.parameters.find( - param => ts.isIdentifier(param.name) && param.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword + (param) => ts.isIdentifier(param.name) && param.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword ); } @@ -111,7 +111,7 @@ function getSignatureDeclarations( context: TransformationContext, signatures: readonly ts.Signature[] ): ts.SignatureDeclaration[] { - return signatures.flatMap(signature => { + return signatures.flatMap((signature) => { const signatureDeclaration = signature.getDeclaration(); if ( (ts.isFunctionExpression(signatureDeclaration) || ts.isArrowFunction(signatureDeclaration)) && @@ -122,7 +122,7 @@ function getSignatureDeclarations( if (inferredType) { const inferredSignatures = getAllCallSignatures(inferredType); if (inferredSignatures.length > 0) { - return inferredSignatures.map(s => s.getDeclaration()); + return inferredSignatures.map((s) => s.getDeclaration()); } } } @@ -137,7 +137,7 @@ export function getFunctionContextType(context: TransformationContext, type: ts. } if (type.isUnion()) { - return reduceContextTypes(type.types.map(t => getFunctionContextType(context, t))); + return reduceContextTypes(type.types.map((t) => getFunctionContextType(context, t))); } const signatures = context.checker.getSignaturesOfType(type, ts.SignatureKind.Call); @@ -146,5 +146,5 @@ export function getFunctionContextType(context: TransformationContext, type: ts. } const signatureDeclarations = getSignatureDeclarations(context, signatures); - return reduceContextTypes(signatureDeclarations.map(s => getDeclarationContextType(context, s))); + return reduceContextTypes(signatureDeclarations.map((s) => getDeclarationContextType(context, s))); } diff --git a/src/transformation/utils/lua-ast.ts b/src/transformation/utils/lua-ast.ts index dfce4b2fc..297aaa0c4 100644 --- a/src/transformation/utils/lua-ast.ts +++ b/src/transformation/utils/lua-ast.ts @@ -65,7 +65,7 @@ export function createUnpackCall( } export function wrapInTable(...expressions: lua.Expression[]): lua.TableExpression { - const fields = expressions.map(e => lua.createTableFieldExpression(e)); + const fields = expressions.map((e) => lua.createTableFieldExpression(e)); return lua.createTableExpression(fields); } @@ -126,7 +126,7 @@ export function createLocalOrExportedOrGlobalDeclaration( return []; } else { assignment = lua.createAssignmentStatement( - identifiers.map(identifier => createExportedIdentifier(context, identifier, exportScope)), + identifiers.map((identifier) => createExportedIdentifier(context, identifier, exportScope)), rhs, tsOriginal ); diff --git a/src/transformation/utils/safe-names.ts b/src/transformation/utils/safe-names.ts index b10ed414f..1ac3f4c3c 100644 --- a/src/transformation/utils/safe-names.ts +++ b/src/transformation/utils/safe-names.ts @@ -72,7 +72,7 @@ export function hasUnsafeSymbolName( symbol: ts.Symbol, tsOriginal: ts.Identifier ): boolean { - const isAmbient = symbol.declarations && symbol.declarations.some(d => isAmbientNode(d)); + const isAmbient = symbol.declarations && symbol.declarations.some((d) => isAmbientNode(d)); // Catch ambient declarations of identifiers with bad names if (isAmbient && checkName(context, symbol.name, tsOriginal)) { @@ -101,7 +101,7 @@ export function hasUnsafeIdentifierName( const fixInvalidLuaIdentifier = (name: string) => name.replace( /[^a-zA-Z0-9_]/g, - c => + (c) => `_${c .charCodeAt(0) .toString(16) diff --git a/src/transformation/utils/scope.ts b/src/transformation/utils/scope.ts index 2c9f267dd..94503c34b 100644 --- a/src/transformation/utils/scope.ts +++ b/src/transformation/utils/scope.ts @@ -69,7 +69,7 @@ export function peekScope(context: TransformationContext): Scope { } export function findScope(context: TransformationContext, scopeTypes: ScopeType): Scope | undefined { - return [...getScopeStack(context)].reverse().find(s => scopeTypes & s.type); + return [...getScopeStack(context)].reverse().find((s) => scopeTypes & s.type); } const scopeIdCounters = new WeakMap(); @@ -149,8 +149,8 @@ function hoistVariableDeclarations( const result = [...statements]; const hoistedLocals: lua.Identifier[] = []; for (const declaration of scope.variableDeclarations) { - const symbols = declaration.left.map(i => i.symbolId).filter(isNonNull); - if (symbols.some(s => shouldHoistSymbol(context, s, scope))) { + const symbols = declaration.left.map((i) => i.symbolId).filter(isNonNull); + if (symbols.some((s) => shouldHoistSymbol(context, s, scope))) { const index = result.indexOf(declaration); assert(index > -1); diff --git a/src/transformation/utils/typescript/index.ts b/src/transformation/utils/typescript/index.ts index 394d67656..41fb6c110 100644 --- a/src/transformation/utils/typescript/index.ts +++ b/src/transformation/utils/typescript/index.ts @@ -7,7 +7,7 @@ export * from "./types"; // TODO: Move to separate files? export function hasExportEquals(sourceFile: ts.SourceFile): boolean { - return sourceFile.statements.some(node => ts.isExportAssignment(node) && node.isExportEquals); + return sourceFile.statements.some((node) => ts.isExportAssignment(node) && node.isExportEquals); } /** @@ -26,7 +26,7 @@ export function findFirstNodeAbove(node: ts.Node, callback: ( export function getFirstDeclarationInFile(symbol: ts.Symbol, sourceFile: ts.SourceFile): ts.Declaration | undefined { const originalSourceFile = ts.getParseTreeNode(sourceFile) ?? sourceFile; - const declarations = (symbol.getDeclarations() ?? []).filter(d => d.getSourceFile() === originalSourceFile); + const declarations = (symbol.getDeclarations() ?? []).filter((d) => d.getSourceFile() === originalSourceFile); return declarations.length > 0 ? declarations.reduce((p, c) => (p.pos < c.pos ? p : c)) : undefined; } diff --git a/src/transformation/utils/typescript/types.ts b/src/transformation/utils/typescript/types.ts index 2c6e69dcb..fab5e7c70 100644 --- a/src/transformation/utils/typescript/types.ts +++ b/src/transformation/utils/typescript/types.ts @@ -25,11 +25,11 @@ export function typeAlwaysSatisfies( } if (type.isUnion()) { - return type.types.every(t => typeAlwaysSatisfies(context, t, predicate)); + return type.types.every((t) => typeAlwaysSatisfies(context, t, predicate)); } if (type.isIntersection()) { - return type.types.some(t => typeAlwaysSatisfies(context, t, predicate)); + return type.types.some((t) => typeAlwaysSatisfies(context, t, predicate)); } return false; @@ -45,11 +45,11 @@ export function typeCanSatisfy( } if (type.isUnion()) { - return type.types.some(t => typeCanSatisfy(context, t, predicate)); + return type.types.some((t) => typeCanSatisfy(context, t, predicate)); } if (type.isIntersection()) { - return type.types.some(t => typeCanSatisfy(context, t, predicate)); + return type.types.some((t) => typeCanSatisfy(context, t, predicate)); } return false; @@ -72,7 +72,7 @@ function isExplicitArrayType(context: TransformationContext, type: ts.Type): boo } if (type.isUnionOrIntersection()) { - return type.types.some(t => isExplicitArrayType(context, t)); + return type.types.some((t) => isExplicitArrayType(context, t)); } const flags = ts.NodeBuilderFlags.InTypeAlias | ts.NodeBuilderFlags.AllowEmptyTuple; @@ -100,11 +100,11 @@ export function forTypeOrAnySupertype( type = context.checker.getDeclaredTypeOfSymbol(type.symbol); } - return (type.getBaseTypes() ?? []).some(superType => forTypeOrAnySupertype(context, superType, predicate)); + return (type.getBaseTypes() ?? []).some((superType) => forTypeOrAnySupertype(context, superType, predicate)); } export function isArrayType(context: TransformationContext, type: ts.Type): boolean { - return forTypeOrAnySupertype(context, type, t => isExplicitArrayType(context, t)); + return forTypeOrAnySupertype(context, type, (t) => isExplicitArrayType(context, t)); } export function isFunctionType(context: TransformationContext, type: ts.Type): boolean { diff --git a/src/transformation/visitors/binary-expression/assignments.ts b/src/transformation/visitors/binary-expression/assignments.ts index 94e17e9c7..ed46ae1e1 100644 --- a/src/transformation/visitors/binary-expression/assignments.ts +++ b/src/transformation/visitors/binary-expression/assignments.ts @@ -59,7 +59,7 @@ export function transformAssignment( return [ rootAssignment, - ...dependentSymbols.map(symbol => { + ...dependentSymbols.map((symbol) => { const [left] = rootAssignment.left; const identifierToAssign = createExportedIdentifier(context, lua.createIdentifier(symbol.name)); return lua.createAssignmentStatement(identifierToAssign, left); @@ -152,7 +152,7 @@ const canBeTransformedToLuaAssignmentStatement = ( node: ts.DestructuringAssignment ): node is ts.ArrayDestructuringAssignment => ts.isArrayLiteralExpression(node.left) && - node.left.elements.every(element => { + node.left.elements.every((element) => { if (isArrayLength(context, element)) { return false; } @@ -188,7 +188,7 @@ export function transformAssignmentStatement( right = createUnpackCall(context, right, expression.right); } - const left = expression.left.elements.map(e => transformAssignmentLeftHandSideExpression(context, e)); + const left = expression.left.elements.map((e) => transformAssignmentLeftHandSideExpression(context, e)); return [lua.createAssignmentStatement(left, right, expression)]; } diff --git a/src/transformation/visitors/call.ts b/src/transformation/visitors/call.ts index 366ff8041..8c4ed418e 100644 --- a/src/transformation/visitors/call.ts +++ b/src/transformation/visitors/call.ts @@ -49,7 +49,7 @@ function transformSpreadableExpressionsIntoArrayConcatArguments( } } - return chunks.map(chunk => wrapInTable(...chunk.map(expression => context.transformExpression(expression)))); + return chunks.map((chunk) => wrapInTable(...chunk.map((expression) => context.transformExpression(expression)))); } export function flattenSpreadExpressions( @@ -57,7 +57,7 @@ export function flattenSpreadExpressions( expressions: readonly ts.Expression[] ): lua.Expression[] { const [preSpreadExpressions, postSpreadExpressions] = getExpressionsBeforeAndAfterFirstSpread(expressions); - const transformedPreSpreadExpressions = preSpreadExpressions.map(a => context.transformExpression(a)); + const transformedPreSpreadExpressions = preSpreadExpressions.map((a) => context.transformExpression(a)); // Nothing special required if (postSpreadExpressions.length === 0) { diff --git a/src/transformation/visitors/class/decorators.ts b/src/transformation/visitors/class/decorators.ts index 5cae0cf17..2bc662b08 100644 --- a/src/transformation/visitors/class/decorators.ts +++ b/src/transformation/visitors/class/decorators.ts @@ -21,7 +21,7 @@ export function createConstructorDecorationStatement( return undefined; } - const decoratorExpressions = decorators.map(decorator => { + const decoratorExpressions = decorators.map((decorator) => { const expression = decorator.expression; const type = context.checker.getTypeAtLocation(expression); const callContext = getFunctionContextType(context, type); @@ -33,7 +33,7 @@ export function createConstructorDecorationStatement( }); const decoratorTable = lua.createTableExpression( - decoratorExpressions.map(expression => lua.createTableFieldExpression(expression)) + decoratorExpressions.map((expression) => lua.createTableFieldExpression(expression)) ); return lua.createAssignmentStatement( diff --git a/src/transformation/visitors/class/index.ts b/src/transformation/visitors/class/index.ts index 59ecc10b7..c2c01a4fe 100644 --- a/src/transformation/visitors/class/index.ts +++ b/src/transformation/visitors/class/index.ts @@ -49,7 +49,7 @@ export const transformClassDeclaration: FunctionVisitor return statements; }; -export const transformThisExpression: FunctionVisitor = node => createSelfIdentifier(node); +export const transformThisExpression: FunctionVisitor = (node) => createSelfIdentifier(node); export function transformClassAsExpression( expression: ts.ClassLikeDeclaration, @@ -131,11 +131,11 @@ function transformClassLikeDeclaration( } // Get all properties with value - const properties = classDeclaration.members.filter(ts.isPropertyDeclaration).filter(member => member.initializer); + const properties = classDeclaration.members.filter(ts.isPropertyDeclaration).filter((member) => member.initializer); // Divide properties into static and non-static const staticFields = properties.filter(isStaticNode); - const instanceFields = properties.filter(prop => !isStaticNode(prop)); + const instanceFields = properties.filter((prop) => !isStaticNode(prop)); const result: lua.Statement[] = []; @@ -237,7 +237,7 @@ function transformClassLikeDeclaration( if (constructorResult) result.push(constructorResult); } else if ( instanceFields.length > 0 || - classDeclaration.members.some(m => isGetAccessorOverride(context, m, classDeclaration)) + classDeclaration.members.some((m) => isGetAccessorOverride(context, m, classDeclaration)) ) { // Generate a constructor if none was defined in a class with instance fields that need initialization // localClassName.prototype.____constructor = function(self, ...) @@ -286,7 +286,7 @@ function transformClassLikeDeclaration( result.push( ...classDeclaration.members .filter(ts.isMethodDeclaration) - .map(m => transformMethodDeclaration(context, m, localClassName, isExtension || isMetaExtension)) + .map((m) => transformMethodDeclaration(context, m, localClassName, isExtension || isMetaExtension)) .filter(isNonNull) ); diff --git a/src/transformation/visitors/class/members/accessors.ts b/src/transformation/visitors/class/members/accessors.ts index 88a7f1545..508fc87f0 100644 --- a/src/transformation/visitors/class/members/accessors.ts +++ b/src/transformation/visitors/class/members/accessors.ts @@ -80,7 +80,7 @@ export const hasMemberInClassOrAncestor = ( context: TransformationContext, classDeclaration: ts.ClassLikeDeclarationBase, callback: (m: ts.ClassElement) => boolean -) => [...classWithAncestors(context, classDeclaration)].some(c => c.members.some(callback)); +) => [...classWithAncestors(context, classDeclaration)].some((c) => c.members.some(callback)); function getPropertyName(propertyName: ts.PropertyName): string | number | undefined { if (ts.isIdentifier(propertyName) || ts.isStringLiteral(propertyName) || ts.isNumericLiteral(propertyName)) { @@ -108,6 +108,6 @@ export function isGetAccessorOverride( return hasMemberInClassOrAncestor( context, classDeclaration, - m => ts.isPropertyDeclaration(m) && m.initializer !== undefined && isSamePropertyName(m.name, element.name) + (m) => ts.isPropertyDeclaration(m) && m.initializer !== undefined && isSamePropertyName(m.name, element.name) ); } diff --git a/src/transformation/visitors/class/members/constructor.ts b/src/transformation/visitors/class/members/constructor.ts index fe25a21b2..ebbb289d1 100644 --- a/src/transformation/visitors/class/members/constructor.ts +++ b/src/transformation/visitors/class/members/constructor.ts @@ -40,7 +40,7 @@ export function transformConstructorDeclaration( const bodyWithFieldInitializers = transformFunctionBodyHeader(context, scope, statement.parameters, restParamName); // Check for field declarations in constructor - const constructorFieldsDeclarations = statement.parameters.filter(p => p.modifiers !== undefined); + const constructorFieldsDeclarations = statement.parameters.filter((p) => p.modifiers !== undefined); const classInstanceFields = transformClassInstanceFields(context, classDeclaration, instanceFields); diff --git a/src/transformation/visitors/class/utils.ts b/src/transformation/visitors/class/utils.ts index 9ba263818..f383d3cc1 100644 --- a/src/transformation/visitors/class/utils.ts +++ b/src/transformation/visitors/class/utils.ts @@ -3,11 +3,11 @@ import { TransformationContext } from "../../context"; import { AnnotationKind, getTypeAnnotations } from "../../utils/annotations"; export function isStaticNode(node: ts.Node): boolean { - return (node.modifiers ?? []).some(m => m.kind === ts.SyntaxKind.StaticKeyword); + return (node.modifiers ?? []).some((m) => m.kind === ts.SyntaxKind.StaticKeyword); } export function getExtendsClause(node: ts.ClassLikeDeclarationBase): ts.HeritageClause | undefined { - return (node.heritageClauses ?? []).find(clause => clause.token === ts.SyntaxKind.ExtendsKeyword); + return (node.heritageClauses ?? []).find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword); } export function getExtendedNode( diff --git a/src/transformation/visitors/conditional.ts b/src/transformation/visitors/conditional.ts index 2fab7494c..ebecc32bd 100644 --- a/src/transformation/visitors/conditional.ts +++ b/src/transformation/visitors/conditional.ts @@ -21,7 +21,7 @@ function canBeFalsy(context: TransformationContext, type: ts.Type): boolean { } else if (!strictNullChecks && !type.isLiteral()) { return true; } else if (type.isUnion()) { - return type.types.some(subType => canBeFalsy(context, subType)); + return type.types.some((subType) => canBeFalsy(context, subType)); } else { return false; } diff --git a/src/transformation/visitors/function.ts b/src/transformation/visitors/function.ts index 7c82a89be..f873e6f90 100644 --- a/src/transformation/visitors/function.ts +++ b/src/transformation/visitors/function.ts @@ -48,7 +48,7 @@ function isRestParameterReferenced(context: TransformationContext, identifier: l return false; } // Ignore references to @vararg types in spread elements - return references.some(r => !r.parent || !ts.isSpreadElement(r.parent) || !isVarargType(context, r)); + return references.some((r) => !r.parent || !ts.isSpreadElement(r.parent) || !isVarargType(context, r)); } export function transformFunctionBodyStatements(context: TransformationContext, body: ts.Block): lua.Statement[] { @@ -215,7 +215,7 @@ export function transformFunctionLikeDeclaration( if (symbol) { // TODO: Not using symbol ids because of https://github.com/microsoft/TypeScript/issues/37131 const isReferenced = [...scope.referencedSymbols].some(([, nodes]) => - nodes.some(n => context.checker.getSymbolAtLocation(n)?.valueDeclaration === symbol.valueDeclaration) + nodes.some((n) => context.checker.getSymbolAtLocation(n)?.valueDeclaration === symbol.valueDeclaration) ); // Only wrap if the name is actually referenced inside the function diff --git a/src/transformation/visitors/literal.ts b/src/transformation/visitors/literal.ts index 6544367a2..1e48f12dd 100644 --- a/src/transformation/visitors/literal.ts +++ b/src/transformation/visitors/literal.ts @@ -51,7 +51,7 @@ export function createShorthandIdentifier( return identifier; } -const transformNumericLiteralExpression: FunctionVisitor = expression => { +const transformNumericLiteralExpression: FunctionVisitor = (expression) => { if (expression.text === "Infinity") { const math = lua.createIdentifier("math"); const huge = lua.createStringLiteral("huge"); @@ -129,21 +129,21 @@ const transformObjectLiteralExpression: FunctionVisitor = (expression, context) => { - const filteredElements = expression.elements.map(e => + const filteredElements = expression.elements.map((e) => ts.isOmittedExpression(e) ? ts.createIdentifier("undefined") : e ); - const values = flattenSpreadExpressions(context, filteredElements).map(e => lua.createTableFieldExpression(e)); + const values = flattenSpreadExpressions(context, filteredElements).map((e) => lua.createTableFieldExpression(e)); return lua.createTableExpression(values, expression); }; export const literalVisitors: Visitors = { - [ts.SyntaxKind.NullKeyword]: node => lua.createNilLiteral(node), - [ts.SyntaxKind.TrueKeyword]: node => lua.createBooleanLiteral(true, node), - [ts.SyntaxKind.FalseKeyword]: node => lua.createBooleanLiteral(false, node), + [ts.SyntaxKind.NullKeyword]: (node) => lua.createNilLiteral(node), + [ts.SyntaxKind.TrueKeyword]: (node) => lua.createBooleanLiteral(true, node), + [ts.SyntaxKind.FalseKeyword]: (node) => lua.createBooleanLiteral(false, node), [ts.SyntaxKind.NumericLiteral]: transformNumericLiteralExpression, - [ts.SyntaxKind.StringLiteral]: node => lua.createStringLiteral(node.text, node), - [ts.SyntaxKind.NoSubstitutionTemplateLiteral]: node => lua.createStringLiteral(node.text, node), + [ts.SyntaxKind.StringLiteral]: (node) => lua.createStringLiteral(node.text, node), + [ts.SyntaxKind.NoSubstitutionTemplateLiteral]: (node) => lua.createStringLiteral(node.text, node), [ts.SyntaxKind.ObjectLiteralExpression]: transformObjectLiteralExpression, [ts.SyntaxKind.ArrayLiteralExpression]: transformArrayLiteralExpression, }; diff --git a/src/transformation/visitors/loops/for-of.ts b/src/transformation/visitors/loops/for-of.ts index 44656088a..6cb5aae14 100644 --- a/src/transformation/visitors/loops/for-of.ts +++ b/src/transformation/visitors/loops/for-of.ts @@ -25,7 +25,7 @@ function transformForRangeStatement( ); } - if (statement.expression.arguments.some(a => !isNumberType(context, context.checker.getTypeAtLocation(a)))) { + if (statement.expression.arguments.some((a) => !isNumberType(context, context.checker.getTypeAtLocation(a)))) { context.diagnostics.push(invalidForRangeCall(statement.expression, "arguments must be numbers")); } @@ -81,7 +81,7 @@ function transformForOfLuaIteratorStatement( const binding = getVariableDeclarationBinding(context, statement.initializer); if (ts.isArrayBindingPattern(binding)) { - identifiers = binding.elements.map(e => transformArrayBindingElement(context, e)); + identifiers = binding.elements.map((e) => transformArrayBindingElement(context, e)); } else { context.diagnostics.push(luaIteratorForbiddenUsage(binding)); } @@ -94,7 +94,7 @@ function transformForOfLuaIteratorStatement( if (identifiers.length > 0) { block.statements.unshift( lua.createAssignmentStatement( - statement.initializer.elements.map(e => + statement.initializer.elements.map((e) => cast(context.transformExpression(e), lua.isAssignmentLeftHandSideExpression) ), identifiers diff --git a/src/transformation/visitors/loops/for.ts b/src/transformation/visitors/loops/for.ts index f81a62199..bc2375654 100644 --- a/src/transformation/visitors/loops/for.ts +++ b/src/transformation/visitors/loops/for.ts @@ -11,7 +11,7 @@ export const transformForStatement: FunctionVisitor = (statemen if (ts.isVariableDeclarationList(statement.initializer)) { checkVariableDeclarationList(context, statement.initializer); // local initializer = value - result.push(...statement.initializer.declarations.flatMap(d => transformVariableDeclaration(context, d))); + result.push(...statement.initializer.declarations.flatMap((d) => transformVariableDeclaration(context, d))); } else { result.push(...context.transformStatements(ts.createExpressionStatement(statement.initializer))); } diff --git a/src/transformation/visitors/modules/export.ts b/src/transformation/visitors/modules/export.ts index 5e12c6c5e..a7af1997f 100644 --- a/src/transformation/visitors/modules/export.ts +++ b/src/transformation/visitors/modules/export.ts @@ -93,7 +93,7 @@ function transformExportSpecifiersFrom( // First transpile as import clause const importClause = ts.createImportClause( undefined, - ts.createNamedImports(exportSpecifiers.map(s => ts.createImportSpecifier(s.propertyName, s.name))) + ts.createNamedImports(exportSpecifiers.map((s) => ts.createImportSpecifier(s.propertyName, s.name))) ); const importDeclaration = ts.createImportDeclaration( @@ -122,7 +122,7 @@ function transformExportSpecifiersFrom( } export const getExported = (context: TransformationContext, exportSpecifiers: ts.NamedExports) => - exportSpecifiers.elements.filter(exportSpecifier => context.resolver.isValueAliasDeclaration(exportSpecifier)); + exportSpecifiers.elements.filter((exportSpecifier) => context.resolver.isValueAliasDeclaration(exportSpecifier)); export const transformExportDeclaration: FunctionVisitor = (node, context) => { if (!node.exportClause) { @@ -143,7 +143,7 @@ export const transformExportDeclaration: FunctionVisitor = // export { ... }; if (!node.moduleSpecifier) { - return exportSpecifiers.map(exportSpecifier => transformExportSpecifier(context, exportSpecifier)); + return exportSpecifiers.map((exportSpecifier) => transformExportSpecifier(context, exportSpecifier)); } // export { ... } from "..."; diff --git a/src/transformation/visitors/modules/import.ts b/src/transformation/visitors/modules/import.ts index 34fa216d6..1214d0091 100644 --- a/src/transformation/visitors/modules/import.ts +++ b/src/transformation/visitors/modules/import.ts @@ -156,8 +156,8 @@ export const transformImportDeclaration: FunctionVisitor = // local c = __module.c if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) { const assignmentStatements = statement.importClause.namedBindings.elements - .filter(importSpecifier => shouldBeImported(context, importSpecifier)) - .map(importSpecifier => transformImportSpecifier(context, importSpecifier, importUniqueName)); + .filter((importSpecifier) => shouldBeImported(context, importSpecifier)) + .map((importSpecifier) => transformImportSpecifier(context, importSpecifier, importUniqueName)); if (assignmentStatements.length > 0) { usingRequireStatement = true; diff --git a/src/transformation/visitors/namespace.ts b/src/transformation/visitors/namespace.ts index 35190705f..97924a51c 100644 --- a/src/transformation/visitors/namespace.ts +++ b/src/transformation/visitors/namespace.ts @@ -37,7 +37,7 @@ function moduleHasEmittedBody( if (node.body) { if (ts.isModuleBlock(node.body)) { // Ignore if body has no emitted statements - return node.body.statements.some(s => !ts.isInterfaceDeclaration(s) && !ts.isTypeAliasDeclaration(s)); + return node.body.statements.some((s) => !ts.isInterfaceDeclaration(s) && !ts.isTypeAliasDeclaration(s)); } else if (ts.isModuleDeclaration(node.body)) { return true; } @@ -74,7 +74,7 @@ export const transformModuleDeclaration: FunctionVisitor = // - declared as a class or function at all (TS requires these to be before module, unless module is empty) const isFirstDeclaration = symbol === undefined || - (!symbol.declarations.some(d => ts.isClassLike(d) || ts.isFunctionDeclaration(d)) && + (!symbol.declarations.some((d) => ts.isClassLike(d) || ts.isFunctionDeclaration(d)) && node === symbol.declarations.find(ts.isModuleDeclaration)); if (isNonModuleMergeable) { diff --git a/src/transformation/visitors/return.ts b/src/transformation/visitors/return.ts index 970db6be0..5bc4e23ab 100644 --- a/src/transformation/visitors/return.ts +++ b/src/transformation/visitors/return.ts @@ -33,7 +33,7 @@ export const transformReturnStatement: FunctionVisitor = (st // Parent function is a TupleReturn function if (ts.isArrayLiteralExpression(statement.expression)) { // If return expression is an array literal, leave out brackets. - results = statement.expression.elements.map(e => context.transformExpression(e)); + results = statement.expression.elements.map((e) => context.transformExpression(e)); } else if (!isTupleReturnCall(context, statement.expression) && isArrayType(context, expressionType)) { // If return expression is an array-type and not another TupleReturn call, unpack it results = [ diff --git a/src/transformation/visitors/template.ts b/src/transformation/visitors/template.ts index 784cf7e4e..004906ad0 100644 --- a/src/transformation/visitors/template.ts +++ b/src/transformation/visitors/template.ts @@ -48,9 +48,9 @@ export const transformTaggedTemplateExpression: FunctionVisitor span.literal.text)); - rawStrings.push(...expression.template.templateSpans.map(span => getRawLiteral(span.literal))); - expressions.push(...expression.template.templateSpans.map(span => span.expression)); + strings.push(...expression.template.templateSpans.map((span) => span.literal.text)); + rawStrings.push(...expression.template.templateSpans.map((span) => getRawLiteral(span.literal))); + expressions.push(...expression.template.templateSpans.map((span) => span.expression)); } else { // No expressions are in the string. strings.push(expression.template.text); @@ -60,11 +60,11 @@ export const transformTaggedTemplateExpression: FunctionVisitor lua.createTableFieldExpression(lua.createStringLiteral(text))) + rawStrings.map((text) => lua.createTableFieldExpression(lua.createStringLiteral(text))) ); const stringTableLiteral = lua.createTableExpression([ - ...strings.map(partialString => lua.createTableFieldExpression(lua.createStringLiteral(partialString))), + ...strings.map((partialString) => lua.createTableFieldExpression(lua.createStringLiteral(partialString))), lua.createTableFieldExpression(rawStringsTable, lua.createStringLiteral("raw")), ]); diff --git a/src/transformation/visitors/variable-declaration.ts b/src/transformation/visitors/variable-declaration.ts index 12ffeb763..99a833fab 100644 --- a/src/transformation/visitors/variable-declaration.ts +++ b/src/transformation/visitors/variable-declaration.ts @@ -75,7 +75,7 @@ export function transformBindingPattern( if (isObjectBindingPattern) { const elements = pattern.elements as ts.NodeArray; - const usedProperties = elements.map(e => + const usedProperties = elements.map((e) => lua.createTableFieldExpression( lua.createBooleanLiteral(true), lua.createStringLiteral( @@ -156,7 +156,7 @@ export function transformBindingVariableDeclaration( const vars = bindingPattern.elements.length > 0 - ? bindingPattern.elements.map(e => transformArrayBindingElement(context, e)) + ? bindingPattern.elements.map((e) => transformArrayBindingElement(context, e)) : lua.createAnonymousIdentifier(); if (initializer) { @@ -174,7 +174,7 @@ export function transformBindingVariableDeclaration( // Don't unpack array literals const values = initializer.elements.length > 0 - ? initializer.elements.map(e => context.transformExpression(e)) + ? initializer.elements.map((e) => context.transformExpression(e)) : lua.createNilLiteral(); statements.push(...createLocalOrExportedOrGlobalDeclaration(context, vars, values, initializer)); } else { @@ -245,5 +245,7 @@ export function checkVariableDeclarationList(context: TransformationContext, nod export const transformVariableStatement: FunctionVisitor = (node, context) => { checkVariableDeclarationList(context, node.declarationList); - return node.declarationList.declarations.flatMap(declaration => transformVariableDeclaration(context, declaration)); + return node.declarationList.declarations.flatMap((declaration) => + transformVariableDeclaration(context, declaration) + ); }; diff --git a/src/transpilation/bundle.ts b/src/transpilation/bundle.ts index 2acda7399..b4fe8d26f 100644 --- a/src/transpilation/bundle.ts +++ b/src/transpilation/bundle.ts @@ -32,17 +32,17 @@ export function bundleTranspiledFiles( // Resolve source files relative to common source directory. const sourceRootDir = program.getCommonSourceDirectory(); - if (!transpiledFiles.some(f => path.resolve(sourceRootDir, f.fileName) === resolvedEntryModule)) { + if (!transpiledFiles.some((f) => path.resolve(sourceRootDir, f.fileName) === resolvedEntryModule)) { return [[diagnosticFactories.couldNotFindBundleEntryPoint(entryModule)], { fileName: bundleFile }]; } // For each file: [""] = function() end, - const moduleTableEntries: SourceChunk[] = transpiledFiles.map(f => + const moduleTableEntries: SourceChunk[] = transpiledFiles.map((f) => moduleSourceNode(f, createModulePath(sourceRootDir, f.fileName)) ); // If any of the modules contains a require for lualib_bundle, add it to the module table. - const lualibRequired = transpiledFiles.some(f => f.lua?.includes('require("lualib_bundle")')); + const lualibRequired = transpiledFiles.some((f) => f.lua?.includes('require("lualib_bundle")')); if (lualibRequired) { moduleTableEntries.push(`["lualib_bundle"] = function() ${getLuaLibBundle(emitHost)} end,\n`); } diff --git a/src/transpilation/emit.ts b/src/transpilation/emit.ts index 854f0cc7e..1229ff672 100644 --- a/src/transpilation/emit.ts +++ b/src/transpilation/emit.ts @@ -54,7 +54,7 @@ export function emitTranspiledFiles( luaLibImport === LuaLibImportKind.Require || luaLibImport === LuaLibImportKind.Always) ) { - const lualibRequired = files.some(f => f.text?.includes('require("lualib_bundle")')); + const lualibRequired = files.some((f) => f.text?.includes('require("lualib_bundle")')); if (lualibRequired) { let outPath = path.resolve(rootDir, "lualib_bundle.lua"); if (outDir !== rootDir) { diff --git a/src/transpilation/index.ts b/src/transpilation/index.ts index 76c0e9634..363cce8fa 100644 --- a/src/transpilation/index.ts +++ b/src/transpilation/index.ts @@ -43,7 +43,7 @@ const libCache: { [key: string]: ts.SourceFile } = {}; export function createVirtualProgram(input: Record, options: CompilerOptions = {}): ts.Program { const compilerHost: ts.CompilerHost = { fileExists: () => true, - getCanonicalFileName: fileName => fileName, + getCanonicalFileName: (fileName) => fileName, getCurrentDirectory: () => "", getDefaultLibFileName: ts.getDefaultLibFileName, readFile: () => "", diff --git a/src/transpilation/transformers.ts b/src/transpilation/transformers.ts index cefb4dd90..54cad3f5c 100644 --- a/src/transpilation/transformers.ts +++ b/src/transpilation/transformers.ts @@ -5,8 +5,8 @@ import { CompilerOptions, TransformerImport } from "../CompilerOptions"; import * as diagnosticFactories from "./diagnostics"; import { getConfigDirectory, resolvePlugin } from "./utils"; -export const noImplicitSelfTransformer: ts.TransformerFactory = () => node => { - const transformSourceFile: ts.Transformer = node => { +export const noImplicitSelfTransformer: ts.TransformerFactory = () => (node) => { + const transformSourceFile: ts.Transformer = (node) => { const empty = ts.createNotEmittedStatement(undefined!); ts.addSyntheticLeadingComment(empty, ts.SyntaxKind.MultiLineCommentTrivia, "* @noSelfInFile ", true); return ts.updateSourceFileNode(node, [empty, ...node.statements], node.isDeclarationFile); @@ -23,7 +23,7 @@ export function getTransformers( customTransformers: ts.CustomTransformers, onSourceFile: (sourceFile: ts.SourceFile) => void ): ts.CustomTransformers { - const luaTransformer: ts.TransformerFactory = () => sourceFile => { + const luaTransformer: ts.TransformerFactory = () => (sourceFile) => { onSourceFile(sourceFile); return ts.createSourceFile(sourceFile.fileName, "", ts.ScriptTarget.ESNext); }; diff --git a/src/transpilation/transpile.ts b/src/transpilation/transpile.ts index 9046477e8..7755f2ee1 100644 --- a/src/transpilation/transpile.ts +++ b/src/transpilation/transpile.ts @@ -51,7 +51,7 @@ export function transpile({ let transpiledFiles: TranspiledFile[] = []; const updateTranspiledFile = (fileName: string, update: Omit) => { - const file = transpiledFiles.find(f => f.fileName === fileName); + const file = transpiledFiles.find((f) => f.fileName === fileName); if (file) { Object.assign(file, update); } else { @@ -86,8 +86,8 @@ export function transpile({ } const plugins = getPlugins(program, diagnostics, customPlugins); - const visitorMap = createVisitorMap(plugins.map(p => p.visitors).filter(isNonNull)); - const printer = createPrinter(plugins.map(p => p.printer).filter(isNonNull)); + const visitorMap = createVisitorMap(plugins.map((p) => p.visitors).filter(isNonNull)); + const printer = createPrinter(plugins.map((p) => p.printer).filter(isNonNull)); const processSourceFile = (sourceFile: ts.SourceFile) => { const { luaAst, luaLibFeatures, diagnostics: transformDiagnostics } = transformSourceFile( program, diff --git a/src/tstl.ts b/src/tstl.ts index 00b6d7606..456ebbb38 100644 --- a/src/tstl.ts +++ b/src/tstl.ts @@ -36,7 +36,7 @@ function executeCommandLine(args: string[]): void { // TODO: ParsedCommandLine.errors isn't meant to contain warnings. Once root-level options // support would be dropped it should be changed to `commandLine.errors.length > 0`. - if (commandLine.errors.some(e => e.category === ts.DiagnosticCategory.Error)) { + if (commandLine.errors.some((e) => e.category === ts.DiagnosticCategory.Error)) { commandLine.errors.forEach(reportDiagnostic); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } @@ -157,7 +157,7 @@ function updateWatchCompilationHost( let fullRecompile = true; const updateConfigFile = createConfigFileUpdater(optionsToExtend); - host.afterProgramCreate = builderProgram => { + host.afterProgramCreate = (builderProgram) => { const program = builderProgram.getProgram(); const options = builderProgram.getCompilerOptions() as tstl.CompilerOptions; const configFileParsingDiagnostics: ts.Diagnostic[] = updateConfigFile(options); @@ -193,7 +193,7 @@ function updateWatchCompilationHost( diagnostics.forEach(reportDiagnostic); - const errors = diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error); + const errors = diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); // do a full recompile after an error fullRecompile = errors.length > 0; diff --git a/test/cli/parse.spec.ts b/test/cli/parse.spec.ts index 3ce9b35ba..9765a3148 100644 --- a/test/cli/parse.spec.ts +++ b/test/cli/parse.spec.ts @@ -59,7 +59,7 @@ describe("command line", () => { }); describe("boolean options", () => { - test.each([true, false])("should parse booleans (%p)", value => { + test.each([true, false])("should parse booleans (%p)", (value) => { const result = tstl.parseCommandLine(["--noHeader", value.toString()]); expect(result.errors).not.toHaveDiagnostics(); @@ -188,7 +188,7 @@ describe("tsconfig", () => { }); describe("boolean options", () => { - test.each([true, false])("should parse booleans (%p)", value => { + test.each([true, false])("should parse booleans (%p)", (value) => { const result = parseConfigFileContent({ tstl: { noHeader: value } }); expect(result.errors).not.toHaveDiagnostics(); diff --git a/test/cli/run.ts b/test/cli/run.ts index cee7e19b2..07fe95b02 100644 --- a/test/cli/run.ts +++ b/test/cli/run.ts @@ -25,7 +25,7 @@ export async function runCli(args: string[]): Promise { child.stdout!.on("data", (data: Buffer) => (output += data.toString())); child.stderr!.on("data", (data: Buffer) => (output += data.toString())); - return new Promise(resolve => { - child.on("close", exitCode => resolve({ exitCode, output })); + return new Promise((resolve) => { + child.on("close", (exitCode) => resolve({ exitCode, output })); }); } diff --git a/test/cli/watch.spec.ts b/test/cli/watch.spec.ts index 35d2f2f59..69ded3f84 100644 --- a/test/cli/watch.spec.ts +++ b/test/cli/watch.spec.ts @@ -4,12 +4,12 @@ import { forkCli } from "./run"; let testsCleanup: Array<() => void> = []; afterEach(() => { - testsCleanup.forEach(x => x()); + testsCleanup.forEach((x) => x()); testsCleanup = []; }); async function waitForFileExists(filePath: string): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { const intervalTimerId = setInterval(() => { if (fs.existsSync(filePath)) { clearInterval(intervalTimerId); diff --git a/test/legacy-utils.ts b/test/legacy-utils.ts index 685b90544..a7de90b0e 100644 --- a/test/legacy-utils.ts +++ b/test/legacy-utils.ts @@ -13,7 +13,7 @@ export function transpileString( const { diagnostics, file } = transpileStringResult(str, options); expect(file.lua).toBeDefined(); - const errors = diagnostics.filter(d => !ignoreDiagnostics || d.source === "typescript-to-lua"); + const errors = diagnostics.filter((d) => !ignoreDiagnostics || d.source === "typescript-to-lua"); expect(errors).not.toHaveDiagnostics(); return file.lua!.trim(); @@ -83,7 +83,7 @@ export function executeLua(luaStr: string, withLib = true): any { // Throw a JS error with the message, retrieved by reading a string from the stack. // Filter control characters out of string which are in there because ???? - throw new Error("LUA ERROR: " + to_jsstring(lua.lua_tostring(L, -1).filter(c => c >= 20))); + throw new Error("LUA ERROR: " + to_jsstring(lua.lua_tostring(L, -1).filter((c) => c >= 20))); } } @@ -117,14 +117,14 @@ export function transpileAndExecuteProjectReturningMainExport( exportName: string, options: tstl.CompilerOptions = {} ): [any, string] { - const mainFile = Object.keys(typeScriptFiles).find(typeScriptFileName => typeScriptFileName === "main.ts"); + const mainFile = Object.keys(typeScriptFiles).find((typeScriptFileName) => typeScriptFileName === "main.ts"); if (!mainFile) { throw new Error("An entry point file needs to be specified. This should be called main.ts"); } const joinedTranspiledFiles = Object.keys(typeScriptFiles) - .filter(typeScriptFileName => typeScriptFileName !== "main.ts") - .map(typeScriptFileName => { + .filter((typeScriptFileName) => typeScriptFileName !== "main.ts") + .map((typeScriptFileName) => { const modulePath = getExportPath(typeScriptFileName, options); const tsCode = typeScriptFiles[typeScriptFileName]; const luaCode = transpileString(tsCode, options); diff --git a/test/setup.ts b/test/setup.ts index 6d92e3332..f9b2e426b 100644 --- a/test/setup.ts +++ b/test/setup.ts @@ -20,7 +20,7 @@ expect.extend({ const diagnosticMessages = ts.formatDiagnosticsWithColorAndContext( diagnostics.map(tstl.prepareDiagnosticForFormatting), - { getCurrentDirectory: () => "", getCanonicalFileName: fileName => fileName, getNewLine: () => "\n" } + { getCurrentDirectory: () => "", getCanonicalFileName: (fileName) => fileName, getNewLine: () => "\n" } ); if (this.isNot && expected !== undefined) { @@ -37,7 +37,9 @@ expect.extend({ const message = this.isNot ? diagnosticMessages : expected - ? `Expected:\n${expected.join("\n")}\nReceived:\n${diagnostics.map(diag => diag.code).join("\n")}\n` + ? `Expected:\n${expected.join("\n")}\nReceived:\n${diagnostics + .map((diag) => diag.code) + .join("\n")}\n` : `Received: ${this.utils.printReceived([])}\n`; return matcherHint + "\n\n" + message; diff --git a/test/translation/transformation.spec.ts b/test/translation/transformation.spec.ts index 7a5088fcb..4a6536bc3 100644 --- a/test/translation/transformation.spec.ts +++ b/test/translation/transformation.spec.ts @@ -6,9 +6,9 @@ import * as util from "../util"; const fixturesPath = path.join(__dirname, "./transformation"); const fixtures = fs .readdirSync(fixturesPath) - .filter(f => path.extname(f) === ".ts") + .filter((f) => path.extname(f) === ".ts") .sort() - .map(f => [path.parse(f).name, fs.readFileSync(path.join(fixturesPath, f), "utf8")]); + .map((f) => [path.parse(f).name, fs.readFileSync(path.join(fixturesPath, f), "utf8")]); test.each(fixtures)("Transformation (%s)", (_name, content) => { util.testModule(content) diff --git a/test/transpile/plugins/plugins.spec.ts b/test/transpile/plugins/plugins.spec.ts index ce2ebc7a6..d31896729 100644 --- a/test/transpile/plugins/plugins.spec.ts +++ b/test/transpile/plugins/plugins.spec.ts @@ -4,7 +4,7 @@ import * as util from "../../util"; test("printer", () => { util.testModule`` .setOptions({ luaPlugins: [{ name: path.join(__dirname, "printer.ts") }] }) - .tap(builder => expect(builder.getMainLuaCodeChunk()).toMatch("Plugin")); + .tap((builder) => expect(builder.getMainLuaCodeChunk()).toMatch("Plugin")); }); test("visitor", () => { diff --git a/test/transpile/run.ts b/test/transpile/run.ts index 72afa7ca2..52cb31a59 100644 --- a/test/transpile/run.ts +++ b/test/transpile/run.ts @@ -13,7 +13,7 @@ export function buildVirtualProject(rootNames: string[], options: tstl.CompilerO options.types = []; const { diagnostics, emitResult } = tstl.transpileFiles(rootNames, options); - const emittedFiles = emitResult.map(result => path.relative(__dirname, result.name).replace(/\\/g, "/")).sort(); + const emittedFiles = emitResult.map((result) => path.relative(__dirname, result.name).replace(/\\/g, "/")).sort(); return { diagnostics, emitResult, emittedFiles }; } diff --git a/test/transpile/transformers/fixtures.ts b/test/transpile/transformers/fixtures.ts index c998d6efc..e2ece47f7 100644 --- a/test/transpile/transformers/fixtures.ts +++ b/test/transpile/transformers/fixtures.ts @@ -6,34 +6,33 @@ import { visitAndReplace } from "./utils"; export const program = (program: ts.Program, options: { value: any }): ts.TransformerFactory => checker(program.getTypeChecker(), options); -export const config = ({ value }: { value: any }): ts.TransformerFactory => context => file => - visitAndReplace(context, file, node => { +export const config = ({ value }: { value: any }): ts.TransformerFactory => (context) => (file) => + visitAndReplace(context, file, (node) => { if (!ts.isReturnStatement(node)) return; return ts.updateReturn(node, ts.createLiteral(value)); }); -export const checker = ( - checker: ts.TypeChecker, - { value }: { value: any } -): ts.TransformerFactory => context => file => - visitAndReplace(context, file, node => { +export const checker = (checker: ts.TypeChecker, { value }: { value: any }): ts.TransformerFactory => ( + context +) => (file) => + visitAndReplace(context, file, (node) => { if (!ts.isReturnStatement(node) || !node.expression) return; const type = checker.getTypeAtLocation(node.expression); if ((type.flags & ts.TypeFlags.BooleanLiteral) === 0) return; return ts.updateReturn(node, ts.createLiteral(value)); }); -export const raw: ts.TransformerFactory = context => file => - visitAndReplace(context, file, node => { +export const raw: ts.TransformerFactory = (context) => (file) => + visitAndReplace(context, file, (node) => { if (!ts.isReturnStatement(node)) return; return ts.updateReturn(node, ts.createLiteral(true)); }); -export const compilerOptions = ( - options: tstl.CompilerOptions -): ts.TransformerFactory => context => file => { +export const compilerOptions = (options: tstl.CompilerOptions): ts.TransformerFactory => (context) => ( + file +) => { assert(options.plugins?.length === 1); - return visitAndReplace(context, file, node => { + return visitAndReplace(context, file, (node) => { if (!ts.isReturnStatement(node)) return; return ts.updateReturn(node, ts.createLiteral(true)); }); diff --git a/test/transpile/transformers/transformers.spec.ts b/test/transpile/transformers/transformers.spec.ts index e166198bd..00f83da4d 100644 --- a/test/transpile/transformers/transformers.spec.ts +++ b/test/transpile/transformers/transformers.spec.ts @@ -24,7 +24,7 @@ test("transformer resolution error", () => { }); describe("factory types", () => { - test.each(["program", "config", "checker", "raw", "compilerOptions"] as const)("%s", type => { + test.each(["program", "config", "checker", "raw", "compilerOptions"] as const)("%s", (type) => { util.testFunction` return false; ` diff --git a/test/transpile/transformers/utils.ts b/test/transpile/transformers/utils.ts index 3e1503ba0..7cd54f2d7 100644 --- a/test/transpile/transformers/utils.ts +++ b/test/transpile/transformers/utils.ts @@ -1,6 +1,6 @@ import * as ts from "typescript"; export function visitAndReplace(context: ts.TransformationContext, node: T, visitor: ts.Visitor): T { - const visit: ts.Visitor = node => visitor(node) ?? ts.visitEachChild(node, visit, context); + const visit: ts.Visitor = (node) => visitor(node) ?? ts.visitEachChild(node, visit, context); return ts.visitNode(node, visit); } diff --git a/test/unit/annotations/compileMembersOnly.spec.ts b/test/unit/annotations/compileMembersOnly.spec.ts index 5db0fe974..aad3395e9 100644 --- a/test/unit/annotations/compileMembersOnly.spec.ts +++ b/test/unit/annotations/compileMembersOnly.spec.ts @@ -12,7 +12,7 @@ test("@compileMembersOnly", () => { return { A: TestEnum.A, B: TestEnum.B, C: TestEnum.C, D: TestEnum.D }; ` - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("TestEnum")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("TestEnum")) .expectToMatchJsResult(); }); @@ -29,6 +29,6 @@ test("@compileMembersOnly in a namespace", () => { export const A = Test.TestEnum.A; ` .setReturnExport("A") - .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("Test.A")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain("Test.A")) .expectToEqual("A"); }); diff --git a/test/unit/annotations/extension.spec.ts b/test/unit/annotations/extension.spec.ts index c8da1b81b..344be25a4 100644 --- a/test/unit/annotations/extension.spec.ts +++ b/test/unit/annotations/extension.spec.ts @@ -5,7 +5,7 @@ import { } from "../../../src/transformation/utils/diagnostics"; import * as util from "../../util"; -test.each(["extension", "metaExtension"])("Class extends extension (%p)", extensionType => { +test.each(["extension", "metaExtension"])("Class extends extension (%p)", (extensionType) => { util.testModule` declare class A {} /** @${extensionType} **/ @@ -14,7 +14,7 @@ test.each(["extension", "metaExtension"])("Class extends extension (%p)", extens `.expectDiagnosticsToMatchSnapshot([extensionCannotExtend.code]); }); -test.each(["extension", "metaExtension"])("Class construct extension (%p)", extensionType => { +test.each(["extension", "metaExtension"])("Class construct extension (%p)", (extensionType) => { util.testModule` declare class A {} /** @${extensionType} **/ @@ -23,7 +23,7 @@ test.each(["extension", "metaExtension"])("Class construct extension (%p)", exte `.expectDiagnosticsToMatchSnapshot([extensionCannotConstruct.code]); }); -test.each(["extension", "metaExtension"])("instanceof extension (%p)", extensionType => { +test.each(["extension", "metaExtension"])("instanceof extension (%p)", (extensionType) => { util.testModule` declare class A {} /** @${extensionType} **/ diff --git a/test/unit/annotations/forRange.spec.ts b/test/unit/annotations/forRange.spec.ts index 661c45253..900166d52 100644 --- a/test/unit/annotations/forRange.spec.ts +++ b/test/unit/annotations/forRange.spec.ts @@ -32,7 +32,7 @@ describe("invalid usage", () => { `.expectDiagnosticsToMatchSnapshot([invalidForRangeCall.code]); }); - test.each<[number[]]>([[[]], [[1]], [[1, 2, 3, 4]]])("argument count (%p)", args => { + test.each<[number[]]>([[[]], [[1]], [[1, 2, 3, 4]]])("argument count (%p)", (args) => { util.testModule` ${createForRangeDeclaration("...args: number[]")} for (const i of luaRange(${args})) {} @@ -74,7 +74,7 @@ describe("invalid usage", () => { "let array = [0, luaRange, 1];", "const call = undefined as any; call(luaRange);", "for (const i of [...luaRange(1, 10)]) {}", - ])("reference (%p)", statement => { + ])("reference (%p)", (statement) => { util.testModule` ${createForRangeDeclaration()} ${statement} diff --git a/test/unit/annotations/luaTable.spec.ts b/test/unit/annotations/luaTable.spec.ts index 8829938bb..342ce84f1 100644 --- a/test/unit/annotations/luaTable.spec.ts +++ b/test/unit/annotations/luaTable.spec.ts @@ -34,7 +34,7 @@ declare const Table: new (notAllowed?: any) => Table declare let tbl: Table; `; -test.each([tableLibClass])("LuaTables cannot be constructed with arguments", tableLib => { +test.each([tableLibClass])("LuaTables cannot be constructed with arguments", (tableLib) => { util.testModule(tableLib + "const table = new Table(true);").expectDiagnosticsToMatchSnapshot([ luaTableForbiddenUsage.code, ]); @@ -42,37 +42,37 @@ test.each([tableLibClass])("LuaTables cannot be constructed with arguments", tab test.each([tableLibClass, tableLibInterface])( "LuaTable set() cannot be used in a LuaTable call expression", - tableLib => { + (tableLib) => { util.testModule(tableLib + 'const exp = tbl.set("value", 5)').expectDiagnosticsToMatchSnapshot([ unsupportedProperty.code, ]); } ); -test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", tableLib => { +test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", (tableLib) => { util.testModule(tableLib + "tbl.other()").expectDiagnosticsToMatchSnapshot([unsupportedProperty.code]); }); -test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", tableLib => { +test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", (tableLib) => { util.testModule(tableLib + "let x = tbl.other()").expectDiagnosticsToMatchSnapshot([unsupportedProperty.code]); }); -test.each([tableLibClass])("LuaTable new", tableLib => { +test.each([tableLibClass])("LuaTable new", (tableLib) => { const content = tableLib + "tbl = new Table();"; expect(util.transpileString(content)).toEqual("tbl = {}"); }); -test.each([tableLibClass])("LuaTable length", tableLib => { +test.each([tableLibClass])("LuaTable length", (tableLib) => { const content = tableLib + "tbl = new Table();\nreturn tbl.length;"; const lua = util.transpileString(content); expect(util.executeLua(lua)).toEqual(0); }); -test.each([tableLibClass, tableLibInterface])("Cannot set LuaTable length", tableLib => { +test.each([tableLibClass, tableLibInterface])("Cannot set LuaTable length", (tableLib) => { util.testModule(tableLib + "tbl.length = 2;").expectDiagnosticsToMatchSnapshot([luaTableForbiddenUsage.code]); }); -test.each([tableLibClass, tableLibInterface])("Forbidden LuaTable use", tableLib => { +test.each([tableLibClass, tableLibInterface])("Forbidden LuaTable use", (tableLib) => { test.each([ "tbl.get()", 'tbl.get("field", "field2")', @@ -81,15 +81,15 @@ test.each([tableLibClass, tableLibInterface])("Forbidden LuaTable use", tableLib 'tbl.set("field", 0, 1)', 'tbl.set(...(["field", 0] as const))', 'tbl.set("field", ...([0] as const))', - ])("Forbidden LuaTable use (%p)", invalidCode => { + ])("Forbidden LuaTable use (%p)", (invalidCode) => { util.testModule(tableLib + invalidCode).expectDiagnosticsToMatchSnapshot([luaTableForbiddenUsage.code]); }); }); -test.each([tableLibClass])("Cannot extend LuaTable class", tableLib => { +test.each([tableLibClass])("Cannot extend LuaTable class", (tableLib) => { test.each(["class Ext extends Table {}", "const c = class Ext extends Table {}"])( "Cannot extend LuaTable class (%p)", - code => { + (code) => { util.testModule(tableLib + code).expectDiagnosticsToMatchSnapshot([luaTableCannotBeExtended.code]); } ); @@ -99,20 +99,20 @@ test.each([ "/** @luaTable */ class Table {}", "/** @luaTable */ export class Table {}", "/** @luaTable */ const c = class Table {}", -])("LuaTable classes must be ambient (%p)", code => { +])("LuaTable classes must be ambient (%p)", (code) => { util.testModule(code).expectDiagnosticsToMatchSnapshot([luaTableMustBeAmbient.code]); }); -test.each([tableLibClass])("Cannot extend LuaTable class", tableLib => { - test.each(["tbl instanceof Table"])("Cannot use instanceof on a LuaTable class (%p)", code => { +test.each([tableLibClass])("Cannot extend LuaTable class", (tableLib) => { + test.each(["tbl instanceof Table"])("Cannot use instanceof on a LuaTable class (%p)", (code) => { util.testModule(tableLib + code).expectDiagnosticsToMatchSnapshot([luaTableInvalidInstanceOf.code]); }); }); -test.each([tableLibClass, tableLibInterface])("Cannot use ElementAccessExpression on a LuaTable", tableLib => { +test.each([tableLibClass, tableLibInterface])("Cannot use ElementAccessExpression on a LuaTable", (tableLib) => { test.each(['tbl["get"]("field")', 'tbl["set"]("field")', 'tbl["length"]'])( "Cannot use ElementAccessExpression on a LuaTable (%p)", - code => { + (code) => { util.testModule(tableLib + code).expectDiagnosticsToMatchSnapshot([ luaTableCannotBeAccessedDynamically.code, ]); @@ -120,15 +120,15 @@ test.each([tableLibClass, tableLibInterface])("Cannot use ElementAccessExpressio ); }); -test.each([tableLibClass, tableLibInterface])("Cannot isolate LuaTable methods", tableLib => { - test.each(["set", "get"])("Cannot isolate LuaTable method (%p)", propertyName => { +test.each([tableLibClass, tableLibInterface])("Cannot isolate LuaTable methods", (tableLib) => { + test.each(["set", "get"])("Cannot isolate LuaTable method (%p)", (propertyName) => { util.testModule(`${tableLib} let property = tbl.${propertyName}`).expectDiagnosticsToMatchSnapshot([ unsupportedProperty.code, ]); }); }); -test.each([tableLibClass])("LuaTable functional tests", tableLib => { +test.each([tableLibClass])("LuaTable functional tests", (tableLib) => { test.each<[string, any]>([ ['const t = new Table(); t.set("field", "value"); return t.get("field");', "value"], ['const t = new Table(); t.set("field", 0); return t.get("field");', 0], diff --git a/test/unit/annotations/tupleReturn.spec.ts b/test/unit/annotations/tupleReturn.spec.ts index 7c7c7ae9b..2a91c5a83 100644 --- a/test/unit/annotations/tupleReturn.spec.ts +++ b/test/unit/annotations/tupleReturn.spec.ts @@ -1,6 +1,6 @@ import * as util from "../../util"; -const expectNoUnpack: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack"); +const expectNoUnpack: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack"); test("Tuple Return Access", () => { util.testFunction` diff --git a/test/unit/annotations/vararg.spec.ts b/test/unit/annotations/vararg.spec.ts index 1635ef13a..ffa44fc4d 100644 --- a/test/unit/annotations/vararg.spec.ts +++ b/test/unit/annotations/vararg.spec.ts @@ -17,8 +17,8 @@ test("@vararg", () => { } return bar("A", "B", "C", "D"); ` - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("b = ")) - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("b = ")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) .expectToMatchJsResult(); }); @@ -39,7 +39,7 @@ test("@vararg global", () => { declare const arg: LuaVararg; export const result = [...arg].join(""); ` - .setLuaFactory(code => `return (function(...) ${code} end)("A", "B", "C", "D")`) - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) + .setLuaFactory((code) => `return (function(...) ${code} end)("A", "B", "C", "D")`) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) .expectToEqual({ result: "ABCD" }); }); diff --git a/test/unit/assignments.spec.ts b/test/unit/assignments.spec.ts index 178d72bab..bb85eb1a2 100644 --- a/test/unit/assignments.spec.ts +++ b/test/unit/assignments.spec.ts @@ -1,7 +1,7 @@ import { unsupportedVarDeclaration } from "../../src/transformation/utils/diagnostics"; import * as util from "../util"; -test.each(["const", "let"])("%s declaration not top-level is not global", declarationKind => { +test.each(["const", "let"])("%s declaration not top-level is not global", (declarationKind) => { util.testModule` { ${declarationKind} foo = true; @@ -11,7 +11,7 @@ test.each(["const", "let"])("%s declaration not top-level is not global", declar `.expectToEqual(false); }); -test.each(["const", "let"])("top-level %s declaration is global", declarationKind => { +test.each(["const", "let"])("top-level %s declaration is global", (declarationKind) => { // TODO [typescript@>=3.9]: Remove `@ts-ignore` comments before module imports util.testBundle` // @ts-ignore @@ -50,7 +50,7 @@ describe("var is disallowed", () => { test.each(["let result;", "const result = null;", "const result = undefined;"])( "Null assignments (%p)", - declaration => { + (declaration) => { util.testFunction` ${declaration} return result; @@ -58,7 +58,7 @@ test.each(["let result;", "const result = null;", "const result = undefined;"])( } ); -test.each(["x = y", "x += y"])("Assignment expressions (%p)", expression => { +test.each(["x = y", "x += y"])("Assignment expressions (%p)", (expression) => { util.testFunction` let x = "x"; let y = "y"; @@ -66,7 +66,7 @@ test.each(["x = y", "x += y"])("Assignment expressions (%p)", expression => { `.expectToMatchJsResult(); }); -test.each(["x = o.p", "x = a[0]", "x = y = o.p", "x = o.p"])("Assignment expressions using temp (%p)", expression => { +test.each(["x = o.p", "x = a[0]", "x = y = o.p", "x = o.p"])("Assignment expressions using temp (%p)", (expression) => { util.testFunction` let x = "x"; let y = "y"; @@ -78,7 +78,7 @@ test.each(["x = o.p", "x = a[0]", "x = y = o.p", "x = o.p"])("Assignment express test.each(["o.p = x", "a[0] = x", "o.p = a[0]", "o.p = a[0] = x"])( "Property assignment expressions (%p)", - expression => { + (expression) => { util.testFunction` let x = "x"; let o = {p: "o"}; @@ -95,7 +95,7 @@ test.each([ "[x[1], x[0]] = tr()", "x = [y[1], y[0]]", "[x[0], x[1]] = [y[1], y[0]]", -])("Tuple assignment expressions (%p)", expression => { +])("Tuple assignment expressions (%p)", (expression) => { util.testFunction` let x: [string, string] = ["x0", "x1"]; let y: [string, string] = ["y0", "y1"]; @@ -123,7 +123,7 @@ test.each([ "x ^= y", "x <<= y", "x >>>= y", -])("Operator assignment statements (%p)", statement => { +])("Operator assignment statements (%p)", (statement) => { util.testFunction` let x = 3; let y = 6; @@ -148,7 +148,7 @@ test.each([ "o.p ^= a[0]", "o.p <<= a[0]", "o.p >>>= a[0]", -])("Operator assignment to simple property statements (%p)", statement => { +])("Operator assignment to simple property statements (%p)", (statement) => { util.testFunction` let o = { p: 3 }; let a = [6]; @@ -173,7 +173,7 @@ test.each([ "o.p.d ^= a[0][0]", "o.p.d <<= a[0][0]", "o.p.d >>>= a[0][0]", -])("Operator assignment to deep property statements (%p)", statement => { +])("Operator assignment to deep property statements (%p)", (statement) => { util.testFunction` let o = { p: { d: 3 } }; let a = [[6,11], [7,13]]; @@ -198,7 +198,7 @@ test.each([ "of().p ^= af()[i()]", "of().p <<= af()[i()]", "of().p >>>= af()[i()]", -])("Operator assignment to complex property statements (%p)", statement => { +])("Operator assignment to complex property statements (%p)", (statement) => { util.testFunction` let o = { p: 3 }; let a = [6]; @@ -226,7 +226,7 @@ test.each([ "of().p.d ^= af()[i()][i()]", "of().p.d <<= af()[i()][i()]", "of().p.d >>>= af()[i()][i()]", -])("Operator assignment to complex deep property statements (%p)", statement => { +])("Operator assignment to complex deep property statements (%p)", (statement) => { util.testFunction` let o = { p: { d: 3 } }; let a = [[7, 6], [11, 13]]; @@ -258,7 +258,7 @@ test.each([ "x + (y += 7)", "x + (y += 7)", "x++ + (y += 7)", -])("Operator assignment expressions (%p)", expression => { +])("Operator assignment expressions (%p)", (expression) => { util.testFunction` let x = 3; let y = 6; @@ -286,7 +286,7 @@ test.each([ "o.p + (a[0] += 7)", "o.p += (a[0] += 7)", "o.p++ + (a[0] += 7)", -])("Operator assignment to simple property expressions (%p)", expression => { +])("Operator assignment to simple property expressions (%p)", (expression) => { util.testFunction` let o = { p: 3 }; let a = [6]; @@ -314,7 +314,7 @@ test.each([ "of().p + (af()[i()] += 7)", "of().p += (af()[i()] += 7)", "of().p++ + (af()[i()] += 7)", -])("Operator assignment to complex property expressions (%p)", expression => { +])("Operator assignment to complex property expressions (%p)", (expression) => { util.testFunction` let o = { p: 3 }; let a = [6]; diff --git a/test/unit/builtins/array.spec.ts b/test/unit/builtins/array.spec.ts index 35294be6d..7d6953018 100644 --- a/test/unit/builtins/array.spec.ts +++ b/test/unit/builtins/array.spec.ts @@ -156,11 +156,11 @@ describe("array.length", () => { `.expectToEqual(newLength); }); - test.each([0, 1, 7])("returns right-hand side value", length => { + test.each([0, 1, 7])("returns right-hand side value", (length) => { util.testExpression`[1, 2, 3].length = ${length}`.expectToEqual(length); }); - test.each([-1, -7, 0.1, NaN, Infinity, -Infinity])("throws on invalid values (%p)", length => { + test.each([-1, -7, 0.1, NaN, Infinity, -Infinity])("throws on invalid values (%p)", (length) => { util.testFunction` [1, 2, 3].length = ${length}; `.expectToEqual(new util.ExecutionError(`invalid array length: ${length}`)); @@ -538,7 +538,7 @@ test.each([ util.testExpressionTemplate`${array}.flatMap(${map})`.expectToMatchJsResult(); }); -describe.each(["reduce", "reduceRight"])("array.%s", reduce => { +describe.each(["reduce", "reduceRight"])("array.%s", (reduce) => { test.each<[[(total: number, currentItem: number, index: number, array: number[]) => number, number?]]>([ [[(total, currentItem) => total + currentItem]], [[(total, currentItem) => total * currentItem]], @@ -546,7 +546,7 @@ describe.each(["reduce", "reduceRight"])("array.%s", reduce => { [[(total, currentItem) => total * currentItem, 10]], [[(total, _, index, array) => total + array[index]]], [[(a, b) => a + b]], - ])("usage (%p)", args => { + ])("usage (%p)", (args) => { util.testExpression`[1, 3, 5, 7].${reduce}(${util.formatCode(...args)})`.expectToMatchJsResult(); }); @@ -576,7 +576,7 @@ const genericChecks = [ "function generic(array: T)", ]; -test.each(genericChecks)("array constrained generic foreach (%p)", signature => { +test.each(genericChecks)("array constrained generic foreach (%p)", (signature) => { const code = ` ${signature}: number { let sum = 0; @@ -592,7 +592,7 @@ test.each(genericChecks)("array constrained generic foreach (%p)", signature => expect(util.transpileAndExecute(code)).toBe(6); }); -test.each(genericChecks)("array constrained generic length (%p)", signature => { +test.each(genericChecks)("array constrained generic length (%p)", (signature) => { const code = ` ${signature}: number { return array.length; diff --git a/test/unit/builtins/console.spec.ts b/test/unit/builtins/console.spec.ts index 6cf4e6139..4129b8240 100644 --- a/test/unit/builtins/console.spec.ts +++ b/test/unit/builtins/console.spec.ts @@ -8,7 +8,7 @@ test.each([ 'console.log("Hello %s", "there")', 'console.log("Hello %%s", "there")', 'console.log("Hello", "There")', -])("console.log (%p)", code => { +])("console.log (%p)", (code) => { util.testFunction(code) .setOptions(compilerOptions) .expectLuaToMatchSnapshot(); @@ -20,7 +20,7 @@ test.each([ 'console.info("Hello %s", "there")', 'console.info("Hello %%s", "there")', 'console.info("Hello", "There")', -])("console.info (%p)", code => { +])("console.info (%p)", (code) => { util.testFunction(code) .setOptions(compilerOptions) .expectLuaToMatchSnapshot(); @@ -32,7 +32,7 @@ test.each([ 'console.error("Hello %s", "there")', 'console.error("Hello %%s", "there")', 'console.error("Hello", "There")', -])("console.error (%p)", code => { +])("console.error (%p)", (code) => { util.testFunction(code) .setOptions(compilerOptions) .expectLuaToMatchSnapshot(); @@ -44,7 +44,7 @@ test.each([ 'console.warn("Hello %s", "there")', 'console.warn("Hello %%s", "there")', 'console.warn("Hello", "There")', -])("console.warn (%p)", code => { +])("console.warn (%p)", (code) => { util.testFunction(code) .setOptions(compilerOptions) .expectLuaToMatchSnapshot(); @@ -56,7 +56,7 @@ test.each([ 'console.trace("Hello %s", "there")', 'console.trace("Hello %%s", "there")', 'console.trace("Hello", "there")', -])("console.trace (%p)", code => { +])("console.trace (%p)", (code) => { util.testFunction(code) .setOptions(compilerOptions) .expectLuaToMatchSnapshot(); @@ -68,7 +68,7 @@ test.each([ 'console.assert(false, "message %s", "info")', 'console.assert(false, "message %%s", "info")', 'console.assert(false, "message", "more")', -])("console.assert (%p)", code => { +])("console.assert (%p)", (code) => { util.testFunction(code) .setOptions(compilerOptions) .expectLuaToMatchSnapshot(); diff --git a/test/unit/builtins/loading.spec.ts b/test/unit/builtins/loading.spec.ts index fa213d03f..6ddcb89ec 100644 --- a/test/unit/builtins/loading.spec.ts +++ b/test/unit/builtins/loading.spec.ts @@ -6,34 +6,34 @@ describe("luaLibImport", () => { test("inline", () => { util.testExpression`[0].push(1)` .setOptions({ luaLibImport: tstl.LuaLibImportKind.Inline }) - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain('require("lualib_bundle")')) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain('require("lualib_bundle")')) .expectToMatchJsResult(); }); test("require", () => { util.testExpression`[0].push(1)` .setOptions({ luaLibImport: tstl.LuaLibImportKind.Require }) - .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) .expectToMatchJsResult(); }); test("always", () => { util.testModule`` .setOptions({ luaLibImport: tstl.LuaLibImportKind.Always }) - .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) .expectToEqual(undefined); }); }); test.each([tstl.LuaLibImportKind.Inline, tstl.LuaLibImportKind.None, tstl.LuaLibImportKind.Require])( "should not include lualib without code (%p)", - luaLibImport => { - util.testModule``.setOptions({ luaLibImport }).tap(builder => expect(builder.getMainLuaCodeChunk()).toBe("")); + (luaLibImport) => { + util.testModule``.setOptions({ luaLibImport }).tap((builder) => expect(builder.getMainLuaCodeChunk()).toBe("")); } ); test("lualib should not include tstl header", () => { - util.testExpression`[0].push(1)`.tap(builder => + util.testExpression`[0].push(1)`.tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("Generated with") ); }); diff --git a/test/unit/builtins/map.spec.ts b/test/unit/builtins/map.spec.ts index e9edd2508..6e700bebe 100644 --- a/test/unit/builtins/map.spec.ts +++ b/test/unit/builtins/map.spec.ts @@ -97,7 +97,7 @@ test.each([ '[["b", "c"], ["a", null]]', '[["a", null], ["b", "c"]]', '[["b", "c"], ["a", null], ["x", "y"]]', -])("map (%p) has null", entries => { +])("map (%p) has null", (entries) => { util.testFunction` let mymap = new Map(${entries}); return mymap.has("a"); @@ -109,7 +109,7 @@ test.each([ '[["b", "c"], ["a", undefined]]', '[["a", undefined], ["b", "c"]]', '[["b", "c"], ["a", undefined], ["x", "y"]]', -])("map (%p) has undefined", entries => { +])("map (%p) has undefined", (entries) => { util.testFunction` let mymap = new Map(${entries}); return mymap.has("a"); @@ -156,7 +156,7 @@ test("map size", () => { }); const iterationMethods = ["entries", "keys", "values"]; -describe.each(iterationMethods)("map.%s() preserves insertion order", iterationMethod => { +describe.each(iterationMethods)("map.%s() preserves insertion order", (iterationMethod) => { test("basic", () => { util.testFunction` const mymap = new Map(); diff --git a/test/unit/builtins/math.spec.ts b/test/unit/builtins/math.spec.ts index 163095d9d..6fbbf5a4a 100644 --- a/test/unit/builtins/math.spec.ts +++ b/test/unit/builtins/math.spec.ts @@ -12,27 +12,27 @@ test.each([ "Math.log1p(3)", "Math.round(3.3)", "Math.PI", -])("%s", code => { +])("%s", (code) => { // TODO: Remove? util.testFunction(code) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(["E", "LN10", "LN2", "LOG10E", "LOG2E", "SQRT1_2", "SQRT2"])("Math.%s", constant => { - util.testExpression`Math.${constant}`.tap(builder => { +test.each(["E", "LN10", "LN2", "LOG10E", "LOG2E", "SQRT1_2", "SQRT2"])("Math.%s", (constant) => { + util.testExpression`Math.${constant}`.tap((builder) => { expect(builder.getLuaExecutionResult()).toBeCloseTo(builder.getJsExecutionResult()); }); }); -const expectMathAtan2: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toContain("math.atan2("); -const expectMathAtan: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toContain("math.atan("); +const expectMathAtan2: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toContain("math.atan2("); +const expectMathAtan: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toContain("math.atan("); util.testEachVersion("Math.atan2", () => util.testExpression`Math.atan2(4, 5)`, { - [tstl.LuaTarget.LuaJIT]: builder => builder.tap(expectMathAtan2), - [tstl.LuaTarget.Lua51]: builder => builder.tap(expectMathAtan2), - [tstl.LuaTarget.Lua52]: builder => builder.tap(expectMathAtan2), - [tstl.LuaTarget.Lua53]: builder => builder.tap(expectMathAtan), + [tstl.LuaTarget.LuaJIT]: (builder) => builder.tap(expectMathAtan2), + [tstl.LuaTarget.Lua51]: (builder) => builder.tap(expectMathAtan2), + [tstl.LuaTarget.Lua52]: (builder) => builder.tap(expectMathAtan2), + [tstl.LuaTarget.Lua53]: (builder) => builder.tap(expectMathAtan), }); test("Math.atan2(4, 5)", () => { diff --git a/test/unit/builtins/numbers.spec.ts b/test/unit/builtins/numbers.spec.ts index 2f52c1d7d..6f8d5e3f7 100644 --- a/test/unit/builtins/numbers.spec.ts +++ b/test/unit/builtins/numbers.spec.ts @@ -18,11 +18,11 @@ test.each([ "Infinity * -1", "Infinity + 1", "Infinity - 1", -])("%s", code => { +])("%s", (code) => { util.testExpression(code).expectToMatchJsResult(); }); -test.skip.each(["NaN", "Infinity"])("%s reassignment", name => { +test.skip.each(["NaN", "Infinity"])("%s reassignment", (name) => { util.testFunction` const ${name} = 1; return ${name}; @@ -35,36 +35,36 @@ const restCases = [true, false, "", " ", "\t", "\n", "foo", {}]; const cases = [...numberCases, ...stringCases, ...restCases]; describe("Number", () => { - test.each(cases)("constructor(%p)", value => { + test.each(cases)("constructor(%p)", (value) => { util.testExpressionTemplate`Number(${value})`.expectToMatchJsResult(); }); - test.each(cases)("isNaN(%p)", value => { + test.each(cases)("isNaN(%p)", (value) => { util.testExpressionTemplate`Number.isNaN(${value} as any)`.expectToMatchJsResult(); }); - test.each(cases)("isFinite(%p)", value => { + test.each(cases)("isFinite(%p)", (value) => { util.testExpressionTemplate`Number.isFinite(${value} as any)`.expectToMatchJsResult(); }); }); const toStringRadixes = [undefined, 10, 2, 8, 9, 16, 17, 36, 36.9]; const toStringValues = [-1, 0, 1, 1.5, 1024, 1.2]; -const toStringPairs = toStringValues.flatMap(value => toStringRadixes.map(radix => [value, radix] as const)); +const toStringPairs = toStringValues.flatMap((value) => toStringRadixes.map((radix) => [value, radix] as const)); test.each(toStringPairs)("(%p).toString(%p)", (value, radix) => { util.testExpressionTemplate`(${value}).toString(${radix})`.expectToMatchJsResult(); }); -test.each([NaN, Infinity, -Infinity])("%p.toString(2)", value => { +test.each([NaN, Infinity, -Infinity])("%p.toString(2)", (value) => { util.testExpressionTemplate`(${value}).toString(2)`.expectToMatchJsResult(); }); -test.each(cases)("isNaN(%p)", value => { +test.each(cases)("isNaN(%p)", (value) => { util.testExpressionTemplate`isNaN(${value} as any)`.expectToMatchJsResult(); }); -test.each(cases)("isFinite(%p)", value => { +test.each(cases)("isFinite(%p)", (value) => { util.testExpressionTemplate`isFinite(${value} as any)`.expectToMatchJsResult(); }); diff --git a/test/unit/builtins/object.spec.ts b/test/unit/builtins/object.spec.ts index 067da81f6..959027a0b 100644 --- a/test/unit/builtins/object.spec.ts +++ b/test/unit/builtins/object.spec.ts @@ -10,21 +10,21 @@ test.each([ util.testExpression`Object.assign(${util.formatCode(initial)}, ${argsString})`.expectToMatchJsResult(); }); -test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.entries (%p)", obj => { +test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.entries (%p)", (obj) => { util.testExpressionTemplate`Object.entries(${obj})`.expectToMatchJsResult(); }); -test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.keys (%p)", obj => { +test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.keys (%p)", (obj) => { util.testExpressionTemplate`Object.keys(${obj})`.expectToMatchJsResult(); }); -test.each([{}, { abc: "def" }, { abc: 3, def: "xyz" }])("Object.values (%p)", obj => { +test.each([{}, { abc: "def" }, { abc: 3, def: "xyz" }])("Object.values (%p)", (obj) => { util.testExpressionTemplate`Object.values(${obj})`.expectToMatchJsResult(); }); test.each(["[]", '[["a", 1], ["b", 2]]', '[["a", 1], ["a", 2]]', 'new Map([["foo", "bar"]])'])( "Object.fromEntries(%s)", - entries => { + (entries) => { util.testExpression`Object.fromEntries(${entries})`.expectToMatchJsResult(); } ); diff --git a/test/unit/builtins/set.spec.ts b/test/unit/builtins/set.spec.ts index 8f81edfe8..440478597 100644 --- a/test/unit/builtins/set.spec.ts +++ b/test/unit/builtins/set.spec.ts @@ -129,12 +129,12 @@ test.each([ "let m = new Set([1, 2])", "let m = new Set([1, 2]); m.clear()", "let m = new Set([1, 2]); m.delete(2)", -])("set size (%p)", code => { +])("set size (%p)", (code) => { util.testFunction`${code}; return m.size`.expectToMatchJsResult(); }); const iterationMethods = ["entries", "keys", "values"]; -describe.each(iterationMethods)("set.%s() preserves insertion order", iterationMethod => { +describe.each(iterationMethods)("set.%s() preserves insertion order", (iterationMethod) => { test("basic", () => { util.testFunction` const myset = new Set(); diff --git a/test/unit/builtins/string.spec.ts b/test/unit/builtins/string.spec.ts index a9b6afba4..30a24acf1 100644 --- a/test/unit/builtins/string.spec.ts +++ b/test/unit/builtins/string.spec.ts @@ -64,7 +64,7 @@ test.each([ ["hello", 42], [42, "hello"], ])("string.concat[+] (%p)", (...elements: any[]) => { - util.testExpression(elements.map(e => util.formatCode(e)).join(" + ")).expectToMatchJsResult(); + util.testExpression(elements.map((e) => util.formatCode(e)).join(" + ")).expectToMatchJsResult(); }); test.each([ @@ -148,15 +148,15 @@ test.each([ expect(result).toBe(inp.substr(start, end)); }); -test.each(["", "h", "hello"])("string.length (%p)", input => { +test.each(["", "h", "hello"])("string.length (%p)", (input) => { util.testExpressionTemplate`${input}.length`.expectToMatchJsResult(); }); -test.each(["hello TEST"])("string.toLowerCase (%p)", inp => { +test.each(["hello TEST"])("string.toLowerCase (%p)", (inp) => { util.testExpressionTemplate`${inp}.toLowerCase()`.expectToMatchJsResult(); }); -test.each(["hello test"])("string.toUpperCase (%p)", inp => { +test.each(["hello test"])("string.toUpperCase (%p)", (inp) => { util.testExpressionTemplate`${inp}.toUpperCase()`.expectToMatchJsResult(); }); @@ -249,7 +249,7 @@ test.each(padCases)("string.padEnd (%p)", ({ inp, args }) => { test.each([ "function generic(string: T)", "type StringType = string; function generic(string: T)", -])("string constrained generic foreach (%p)", signature => { +])("string constrained generic foreach (%p)", (signature) => { const code = ` ${signature}: number { return string.length; @@ -275,8 +275,8 @@ const trimTestCases = [ "\r\nfoo\n\r\n", "\r\nfoo\nbar\n\r\n", ]; -describe.each(["trim", "trimEnd", "trimRight", "trimStart", "trimLeft"])("string.%s", trim => { - test.each(trimTestCases)("matches JS result (%p)", testString => { +describe.each(["trim", "trimEnd", "trimRight", "trimStart", "trimLeft"])("string.%s", (trim) => { + test.each(trimTestCases)("matches JS result (%p)", (testString) => { util.testExpression`${util.formatCode(testString)}.${trim}()`.expectToMatchJsResult(); }); }); diff --git a/test/unit/builtins/symbol.spec.ts b/test/unit/builtins/symbol.spec.ts index 3d6b35d8a..d8ceeeeaf 100644 --- a/test/unit/builtins/symbol.spec.ts +++ b/test/unit/builtins/symbol.spec.ts @@ -1,10 +1,10 @@ import * as util from "../../util"; -test.each([undefined, 1, "name"])("symbol.toString() (%p)", description => { +test.each([undefined, 1, "name"])("symbol.toString() (%p)", (description) => { util.testExpression`Symbol(${util.formatCode(description)}).toString()`.expectToMatchJsResult(); }); -test.each([undefined, 1, "name"])("symbol.description (%p)", description => { +test.each([undefined, 1, "name"])("symbol.description (%p)", (description) => { // TODO: Supported since node 11 util.testExpression`Symbol(${util.formatCode(description)}).description`.expectToEqual(description); }); diff --git a/test/unit/builtins/weakMap.spec.ts b/test/unit/builtins/weakMap.spec.ts index ab3ba12fb..d5f1c0c34 100644 --- a/test/unit/builtins/weakMap.spec.ts +++ b/test/unit/builtins/weakMap.spec.ts @@ -116,7 +116,7 @@ test("weakMap has no map features (size)", () => { test.each(["clear()", "keys()", "values()", "entries()", "forEach(() => {})"])( "weakMap has no map features (%p)", - call => { + (call) => { expect(() => util.transpileAndExecute(`(new WeakMap() as any).${call}`)).toThrow(); } ); diff --git a/test/unit/builtins/weakSet.spec.ts b/test/unit/builtins/weakSet.spec.ts index fe6accf45..59654576a 100644 --- a/test/unit/builtins/weakSet.spec.ts +++ b/test/unit/builtins/weakSet.spec.ts @@ -73,7 +73,7 @@ test("weakSet has no set features (size)", () => { test.each(["clear()", "keys()", "values()", "entries()", "forEach(() => {})"])( "weakSet has no set features (%p)", - call => { + (call) => { expect(() => util.transpileAndExecute(`(new WeakSet() as any).${call}`)).toThrow(); } ); diff --git a/test/unit/classes/classes.spec.ts b/test/unit/classes/classes.spec.ts index 6bf2fc85f..11ddad9b7 100644 --- a/test/unit/classes/classes.spec.ts +++ b/test/unit/classes/classes.spec.ts @@ -666,7 +666,7 @@ test("Exported class super call", () => { .expectToMatchJsResult(); }); -test.each(["(new Foo())", "Foo"])("Class method name collision (%p)", input => { +test.each(["(new Foo())", "Foo"])("Class method name collision (%p)", (input) => { util.testFunction` class Foo { public method() { return "foo"; } diff --git a/test/unit/conditionals.spec.ts b/test/unit/conditionals.spec.ts index 890c6dc71..4c07c5222 100644 --- a/test/unit/conditionals.spec.ts +++ b/test/unit/conditionals.spec.ts @@ -2,7 +2,7 @@ import * as tstl from "../../src"; import { unsupportedForTarget } from "../../src/transformation/utils/diagnostics"; import * as util from "../util"; -test.each([0, 1])("if (%p)", inp => { +test.each([0, 1])("if (%p)", (inp) => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -12,7 +12,7 @@ test.each([0, 1])("if (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1])("ifelse (%p)", inp => { +test.each([0, 1])("ifelse (%p)", (inp) => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -23,7 +23,7 @@ test.each([0, 1])("ifelse (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("ifelseif (%p)", inp => { +test.each([0, 1, 2, 3])("ifelseif (%p)", (inp) => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -37,7 +37,7 @@ test.each([0, 1, 2, 3])("ifelseif (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("ifelseifelse (%p)", inp => { +test.each([0, 1, 2, 3])("ifelseifelse (%p)", (inp) => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -52,7 +52,7 @@ test.each([0, 1, 2, 3])("ifelseifelse (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switch (%p)", inp => { +test.each([0, 1, 2, 3])("switch (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -71,7 +71,7 @@ test.each([0, 1, 2, 3])("switch (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchdefault (%p)", inp => { +test.each([0, 1, 2, 3])("switchdefault (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -93,7 +93,7 @@ test.each([0, 1, 2, 3])("switchdefault (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 0, 2, 3, 4, 5, 7])("switchfallthrough (%p)", inp => { +test.each([0, 0, 2, 3, 4, 5, 7])("switchfallthrough (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -125,7 +125,7 @@ test.each([0, 0, 2, 3, 4, 5, 7])("switchfallthrough (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("nestedSwitch (%p)", inp => { +test.each([0, 1, 2, 3])("nestedSwitch (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -196,7 +196,7 @@ test("switch using variable re-declared in cases", () => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2])("switch with block statement scope (%p)", inp => { +test.each([0, 1, 2])("switch with block statement scope (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -220,7 +220,7 @@ test.each([0, 1, 2])("switch with block statement scope (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchReturn (%p)", inp => { +test.each([0, 1, 2, 3])("switchReturn (%p)", (inp) => { util.testFunction` switch (${inp}) { case 0: @@ -237,7 +237,7 @@ test.each([0, 1, 2, 3])("switchReturn (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchWithBrackets (%p)", inp => { +test.each([0, 1, 2, 3])("switchWithBrackets (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -259,7 +259,7 @@ test.each([0, 1, 2, 3])("switchWithBrackets (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchWithBracketsBreakInConditional (%p)", inp => { +test.each([0, 1, 2, 3])("switchWithBracketsBreakInConditional (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -282,7 +282,7 @@ test.each([0, 1, 2, 3])("switchWithBracketsBreakInConditional (%p)", inp => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchWithBracketsBreakInInternalLoop (%p)", inp => { +test.each([0, 1, 2, 3])("switchWithBracketsBreakInInternalLoop (%p)", (inp) => { util.testFunction` let result: number = -1; @@ -391,7 +391,7 @@ test.each([ util.testExpressionTemplate`${condition} ? ${lhs} : ${rhs}`.expectToMatchJsResult(); }); -test.each(["true", "false", "a < 4", "a == 8"])("Ternary Conditional Delayed (%p)", condition => { +test.each(["true", "false", "a < 4", "a == 8"])("Ternary Conditional Delayed (%p)", (condition) => { util.testFunction` let a = 3; let delay = () => ${condition} ? a + 3 : a + 5; diff --git a/test/unit/destructuring.spec.ts b/test/unit/destructuring.spec.ts index 761930ec2..830caad97 100644 --- a/test/unit/destructuring.spec.ts +++ b/test/unit/destructuring.spec.ts @@ -88,7 +88,7 @@ test.each(assignmentTestCases)("in assignment expression (%p)", ({ binding, valu `.expectToMatchJsResult(); }); -test.each(["[]", "{}"])("empty binding pattern", bindingPattern => { +test.each(["[]", "{}"])("empty binding pattern", (bindingPattern) => { util.testFunction` let i = 1; const ${bindingPattern} = [i++]; @@ -133,7 +133,7 @@ describe("array destructuring optimization", () => { const [a, b, c] = array; return { a, b, c }; ` - .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) .expectToMatchJsResult(); }); @@ -142,7 +142,7 @@ describe("array destructuring optimization", () => { const [a, b, c] = [3, 5, 1]; return { a, b, c }; ` - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) .expectToMatchJsResult(); }); @@ -153,7 +153,7 @@ describe("array destructuring optimization", () => { const [head] = ["foo", set()]; return { head, called }; ` - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) .expectToMatchJsResult(); }); @@ -164,7 +164,7 @@ describe("array destructuring optimization", () => { [x] = array; return x; ` - .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) .expectToMatchJsResult(); }); }); diff --git a/test/unit/enum.spec.ts b/test/unit/enum.spec.ts index 8da16355c..325a03ccc 100644 --- a/test/unit/enum.spec.ts +++ b/test/unit/enum.spec.ts @@ -95,10 +95,10 @@ describe("initializers", () => { }); describe("const enum", () => { - const expectToBeConst: util.TapCallback = builder => + const expectToBeConst: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("TestEnum"); - test.each(["", "declare "])("%swithout initializer", modifier => { + test.each(["", "declare "])("%swithout initializer", (modifier) => { util.testModule` ${modifier} const enum TestEnum { A, diff --git a/test/unit/error.spec.ts b/test/unit/error.spec.ts index 27e0ce839..bb4c09c9c 100644 --- a/test/unit/error.spec.ts +++ b/test/unit/error.spec.ts @@ -6,7 +6,7 @@ test("throwString", () => { `.expectToEqual(new util.ExecutionError("Some Error")); }); -test.skip.each([0, 1, 2])("re-throw (%p)", i => { +test.skip.each([0, 1, 2])("re-throw (%p)", (i) => { util.testFunction` const i: number = ${i}; function foo() { @@ -295,7 +295,7 @@ test.each([ "undefined", '{ x: "error object" }', '() => "error function"', -])("throw and catch %s", error => { +])("throw and catch %s", (error) => { util.testFunction` try { throw ${error}; @@ -311,14 +311,14 @@ test.each([ const builtinErrors = ["Error", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError"]; -test.each([...builtinErrors, ...builtinErrors.map(type => `new ${type}`)])("%s properties", errorType => { +test.each([...builtinErrors, ...builtinErrors.map((type) => `new ${type}`)])("%s properties", (errorType) => { util.testFunction` const error = ${errorType}(); return { name: error.name, message: error.message, string: error.toString() }; `.expectToMatchJsResult(); }); -test.each([...builtinErrors, "CustomError"])("get stack from %s", errorType => { +test.each([...builtinErrors, "CustomError"])("get stack from %s", (errorType) => { const stack = util.testFunction` class CustomError extends Error { public name = "CustomError"; diff --git a/test/unit/expressions.spec.ts b/test/unit/expressions.spec.ts index 25f4c20ed..c5f4b3702 100644 --- a/test/unit/expressions.spec.ts +++ b/test/unit/expressions.spec.ts @@ -14,24 +14,24 @@ test.each([ "delete tbl['test']", "let a = delete tbl.test", "delete tbl.test", -])("Unary expressions basic (%p)", input => { +])("Unary expressions basic (%p)", (input) => { util.testFunction(input) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(["3+4", "5-2", "6*3", "6**3", "20/5", "15/10", "15%3"])("Binary expressions basic numeric (%p)", input => { +test.each(["3+4", "5-2", "6*3", "6**3", "20/5", "15/10", "15%3"])("Binary expressions basic numeric (%p)", (input) => { util.testExpression(input).expectToMatchJsResult(); }); test.each(["1==1", "1===1", "1!=1", "1!==1", "1>1", "1>=1", "1<1", "1<=1", "1&&1", "1||1"])( "Binary expressions basic boolean (%p)", - input => { + (input) => { util.testExpression(input).expectToMatchJsResult(); } ); -test.each(["'key' in obj", "'existingKey' in obj", "0 in obj", "9 in obj"])("Binary expression in (%p)", input => { +test.each(["'key' in obj", "'existingKey' in obj", "0 in obj", "9 in obj"])("Binary expression in (%p)", (input) => { const tsHeader = "declare var obj: any;"; const tsSource = `return ${input}`; const luaHeader = "obj = { existingKey = 1 }"; @@ -40,19 +40,22 @@ test.each(["'key' in obj", "'existingKey' in obj", "0 in obj", "9 in obj"])("Bin expect(result).toBe(eval(`let obj = { existingKey: 1 }; ${input}`)); }); -test.each(["a+=b", "a-=b", "a*=b", "a/=b", "a%=b", "a**=b"])("Binary expressions overridden operators (%p)", input => { - util.testFunction` +test.each(["a+=b", "a-=b", "a*=b", "a/=b", "a%=b", "a**=b"])( + "Binary expressions overridden operators (%p)", + (input) => { + util.testFunction` let a = 5; let b = 3; ${input}; return a; `.expectToMatchJsResult(); -}); + } +); const supportedInAll = ["~a", "a&b", "a&=b", "a|b", "a|=b", "a^b", "a^=b", "a<>>b", "a>>>=b"]; const unsupportedIn53 = ["a>>b", "a>>=b"]; const allBinaryOperators = [...supportedInAll, ...unsupportedIn53]; -test.each(allBinaryOperators)("Bitop [5.1] (%p)", input => { +test.each(allBinaryOperators)("Bitop [5.1] (%p)", (input) => { // Bit operations not supported in 5.1, expect an exception util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua51, luaLibImport: tstl.LuaLibImportKind.None }) @@ -60,28 +63,28 @@ test.each(allBinaryOperators)("Bitop [5.1] (%p)", input => { .expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]); }); -test.each(allBinaryOperators)("Bitop [JIT] (%p)", input => { +test.each(allBinaryOperators)("Bitop [JIT] (%p)", (input) => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.LuaJIT, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(allBinaryOperators)("Bitop [5.2] (%p)", input => { +test.each(allBinaryOperators)("Bitop [5.2] (%p)", (input) => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua52, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(supportedInAll)("Bitop [5.3] (%p)", input => { +test.each(supportedInAll)("Bitop [5.3] (%p)", (input) => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua53, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(unsupportedIn53)("Unsupported bitop 5.3 (%p)", input => { +test.each(unsupportedIn53)("Unsupported bitop 5.3 (%p)", (input) => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua53, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() @@ -90,7 +93,7 @@ test.each(unsupportedIn53)("Unsupported bitop 5.3 (%p)", input => { test.each(["1+1", "-1+1", "1*30+4", "1*(3+4)", "1*(3+4*2)", "10-(4+5)"])( "Binary expressions ordering parentheses (%p)", - input => { + (input) => { util.testExpression(input).expectLuaToMatchSnapshot(); } ); @@ -103,7 +106,7 @@ test("Assignment order of operations is preserved", () => { `.expectToMatchJsResult(); }); -test.each(["bar(),foo()", "foo(),bar()", "foo(),bar(),baz()"])("Binary Comma (%p)", input => { +test.each(["bar(),foo()", "foo(),bar()", "foo(),bar(),baz()"])("Binary Comma (%p)", (input) => { util.testFunction` function foo() { return 1; } function bar() { return 2; }; @@ -128,7 +131,7 @@ test("Undefined Expression", () => { expect(util.transpileString("undefined")).toBe("local ____ = nil"); }); -test.each(["i++", "i--", "++i", "--i"])("Incrementor value (%p)", expression => { +test.each(["i++", "i--", "++i", "--i"])("Incrementor value (%p)", (expression) => { util.testFunction` let i = 10; return ${expression}; @@ -159,7 +162,7 @@ test.each([ "Math.log2(2)", "Math.log10(2)", '"".indexOf("")', -])("Expression statements (%p)", input => { +])("Expression statements (%p)", (input) => { util.testFunction` function foo() { return 17; } const bar = { foo }; diff --git a/test/unit/functions/functions.spec.ts b/test/unit/functions/functions.spec.ts index 2f2f3b212..9384c3dec 100644 --- a/test/unit/functions/functions.spec.ts +++ b/test/unit/functions/functions.spec.ts @@ -14,7 +14,7 @@ test("Returning arrow function from arrow function", () => { `.expectToMatchJsResult(); }); -test.each(["i++", "i--", "++i", "--i"])("Arrow function unary expression (%p)", lambda => { +test.each(["i++", "i--", "++i", "--i"])("Arrow function unary expression (%p)", (lambda) => { util.testFunction` let i = 10; [1,2,3,4,5].forEach(() => ${lambda}); @@ -24,7 +24,7 @@ test.each(["i++", "i--", "++i", "--i"])("Arrow function unary expression (%p)", test.each(["b => a = b", "b => a += b", "b => a -= b", "b => a *= b", "b => a /= b", "b => a **= b", "b => a %= b"])( "Arrow function assignment (%p)", - lambda => { + (lambda) => { util.testFunction` let a = 10; let lambda = ${lambda}; @@ -351,7 +351,7 @@ test("Complex element access call statement", () => { `.expectToMatchJsResult(); }); -test.each([1, 2])("Generator functions value (%p)", iterations => { +test.each([1, 2])("Generator functions value (%p)", (iterations) => { util.testFunction` function* seq(value: number) { let a = yield value + 1; @@ -366,7 +366,7 @@ test.each([1, 2])("Generator functions value (%p)", iterations => { `.expectToMatchJsResult(); }); -test.each([1, 2])("Generator functions done (%p)", iterations => { +test.each([1, 2])("Generator functions done (%p)", (iterations) => { util.testFunction` function* seq(value: number) { let a = yield value + 1; @@ -473,7 +473,7 @@ test("Function rest parameter (unreferenced)", () => { } return foo("A", "B", "C", "D"); ` - .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("{...}")) + .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("{...}")) .expectToMatchJsResult(); }); diff --git a/test/unit/functions/noImplicitSelfOption.spec.ts b/test/unit/functions/noImplicitSelfOption.spec.ts index f61e37cb2..eba51eaae 100644 --- a/test/unit/functions/noImplicitSelfOption.spec.ts +++ b/test/unit/functions/noImplicitSelfOption.spec.ts @@ -28,7 +28,7 @@ test("generates declaration files with @noSelfInFile", () => { .setOptions({ declaration: true, noImplicitSelf: true }) .expectToHaveNoDiagnostics(); - const fooDeclaration = fooBuilder.getLuaResult().transpiledFiles.find(f => f.declaration)?.declaration; + const fooDeclaration = fooBuilder.getLuaResult().transpiledFiles.find((f) => f.declaration)?.declaration; util.assert(fooDeclaration !== undefined); util.testModule` diff --git a/test/unit/functions/noSelfAnnotation.spec.ts b/test/unit/functions/noSelfAnnotation.spec.ts index ab77ec03e..96abcb1ed 100644 --- a/test/unit/functions/noSelfAnnotation.spec.ts +++ b/test/unit/functions/noSelfAnnotation.spec.ts @@ -10,7 +10,7 @@ test("@noSelf on declared function removes context argument", () => { `.expectLuaToMatchSnapshot(); }); -test.each(methodHolders)("@noSelf on method inside %s declaration removes context argument", holderType => { +test.each(methodHolders)("@noSelf on method inside %s declaration removes context argument", (holderType) => { util.testModule` declare ${holderType} MethodHolder { /** @noSelf */ @@ -21,7 +21,7 @@ test.each(methodHolders)("@noSelf on method inside %s declaration removes contex `.expectLuaToMatchSnapshot(); }); -test.each(methodHolders)("@noSelf on parent %s declaration removes context argument", holderType => { +test.each(methodHolders)("@noSelf on parent %s declaration removes context argument", (holderType) => { util.testModule` /** @noSelf */ declare ${holderType} MethodHolder { diff --git a/test/unit/functions/validation/functionExpressionTypeInference.spec.ts b/test/unit/functions/validation/functionExpressionTypeInference.spec.ts index e475f2216..a1eba6a70 100644 --- a/test/unit/functions/validation/functionExpressionTypeInference.spec.ts +++ b/test/unit/functions/validation/functionExpressionTypeInference.spec.ts @@ -1,6 +1,6 @@ import * as util from "../../../util"; -test.each(["noSelf", "noSelfInFile"])("noSelf function method argument (%p)", noSelfTag => { +test.each(["noSelf", "noSelfInFile"])("noSelf function method argument (%p)", (noSelfTag) => { const header = ` /** @${noSelfTag} */ namespace NS { export class C { @@ -29,7 +29,7 @@ test("noSelfInFile works when first statement has other annotations", () => { test.each(["(this: void, s: string) => string", "(this: any, s: string) => string", "(s: string) => string"])( "Function expression type inference in binary operator (%p)", - funcType => { + (funcType) => { const header = `declare const undefinedFunc: ${funcType};`; const code = ` let func: ${funcType} = s => s; @@ -42,7 +42,7 @@ test.each(["(this: void, s: string) => string", "(this: any, s: string) => strin test.each(["s => s", "(s => s)", "function(s) { return s; }", "(function(s) { return s; })"])( "Function expression type inference in class (%p)", - funcExp => { + (funcExp) => { const code = ` class Foo { func: (this: void, s: string) => string = ${funcExp}; diff --git a/test/unit/functions/validation/invalidFunctionAssignments.spec.ts b/test/unit/functions/validation/invalidFunctionAssignments.spec.ts index 7d678496b..4a039dd64 100644 --- a/test/unit/functions/validation/invalidFunctionAssignments.spec.ts +++ b/test/unit/functions/validation/invalidFunctionAssignments.spec.ts @@ -155,7 +155,7 @@ test.each([ "(this: void, s1: string, s2: string) => string", "{(this: void, s: string): string}", "{(this: any, s1: string, s2: string): string}", -])("Invalid function overload assignment (%p)", assignType => { +])("Invalid function overload assignment (%p)", (assignType) => { util.testModule` interface O { (this: any, s1: string, s2: string): string; diff --git a/test/unit/functions/validation/validFunctionAssignments.spec.ts b/test/unit/functions/validation/validFunctionAssignments.spec.ts index a491ccd7b..70947b027 100644 --- a/test/unit/functions/validation/validFunctionAssignments.spec.ts +++ b/test/unit/functions/validation/validFunctionAssignments.spec.ts @@ -180,7 +180,7 @@ test.each([ } const o: O = (s1: string, s2?: string) => s1 + (s2 || "bar"); let f: ${assignType} = o; - return f(${args.map(a => '"' + a + '"').join(", ")});`; + return f(${args.map((a) => '"' + a + '"').join(", ")});`; const result = util.transpileAndExecute(code); expect(result).toBe(expectResult); }); diff --git a/test/unit/hoisting.spec.ts b/test/unit/hoisting.spec.ts index 997c53f73..17a192b29 100644 --- a/test/unit/hoisting.spec.ts +++ b/test/unit/hoisting.spec.ts @@ -1,7 +1,7 @@ import * as ts from "typescript"; import * as util from "../util"; -test.each(["let", "const"])("Let/Const Hoisting (%p)", varType => { +test.each(["let", "const"])("Let/Const Hoisting (%p)", (varType) => { const code = ` let bar: string; function setBar() { bar = foo; } @@ -13,7 +13,7 @@ test.each(["let", "const"])("Let/Const Hoisting (%p)", varType => { expect(result).toBe("foo"); }); -test.each(["let", "const"])("Exported Let/Const Hoisting (%p)", varType => { +test.each(["let", "const"])("Exported Let/Const Hoisting (%p)", (varType) => { const code = ` let bar: string; function setBar() { bar = foo; } @@ -115,7 +115,7 @@ test("Hoisting with synthetic source file node", () => { ` .setCustomTransformers({ before: [ - () => sourceFile => + () => (sourceFile) => ts.updateSourceFileNode( sourceFile, [ts.createNotEmittedStatement(undefined!), ...sourceFile.statements], diff --git a/test/unit/identifiers.spec.ts b/test/unit/identifiers.spec.ts index 27046c81b..4622d9467 100644 --- a/test/unit/identifiers.spec.ts +++ b/test/unit/identifiers.spec.ts @@ -19,35 +19,35 @@ const validTsInvalidLuaKeywordNames = [ const invalidLuaNames = [...invalidLuaCharNames, ...luaKeywords]; const validTsInvalidLuaNames = [...invalidLuaCharNames, ...validTsInvalidLuaKeywordNames]; -test.each(validTsInvalidLuaNames)("invalid lua identifier name (%p)", name => { +test.each(validTsInvalidLuaNames)("invalid lua identifier name (%p)", (name) => { util.testFunction` const ${name} = "foobar"; return ${name}; `.expectToMatchJsResult(); }); -test.each([...luaKeywords.values()])("lua keyword as property name (%p)", keyword => { +test.each([...luaKeywords.values()])("lua keyword as property name (%p)", (keyword) => { util.testFunction` const x = { ${keyword}: "foobar" }; return x.${keyword}; `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaKeywordNames)("destructuring lua keyword (%p)", keyword => { +test.each(validTsInvalidLuaKeywordNames)("destructuring lua keyword (%p)", (keyword) => { util.testFunction` const { foo: ${keyword} } = { foo: "foobar" }; return ${keyword}; `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaKeywordNames)("destructuring shorthand lua keyword (%p)", keyword => { +test.each(validTsInvalidLuaKeywordNames)("destructuring shorthand lua keyword (%p)", (keyword) => { util.testFunction` const { ${keyword} } = { ${keyword}: "foobar" }; return ${keyword}; `.expectToMatchJsResult(); }); -test.each(invalidLuaNames)("lua keyword or invalid identifier as method call (%p)", name => { +test.each(invalidLuaNames)("lua keyword or invalid identifier as method call (%p)", (name) => { util.testFunction` const foo = { ${name}(arg: string) { return "foo" + arg; } @@ -56,7 +56,7 @@ test.each(invalidLuaNames)("lua keyword or invalid identifier as method call (%p `.expectToMatchJsResult(); }); -test.each(invalidLuaNames)("lua keyword or invalid identifier as complex method call (%p)", name => { +test.each(invalidLuaNames)("lua keyword or invalid identifier as complex method call (%p)", (name) => { util.testFunction` const foo = { ${name}(arg: string) { return "foo" + arg; } @@ -76,7 +76,7 @@ test.each([ "module local { export const bar: any; }", "enum local {}", "function local() {}", -])("ambient identifier cannot be a lua keyword (%p)", statement => { +])("ambient identifier cannot be a lua keyword (%p)", (statement) => { util.testModule` declare ${statement} local; @@ -95,7 +95,7 @@ test.each([ "module $$$ { export const bar: any; }", "enum $$$ {}", "function $$$();", -])("ambient identifier must be a valid lua identifier (%p)", statement => { +])("ambient identifier must be a valid lua identifier (%p)", (statement) => { util.testModule` declare ${statement} $$$; @@ -104,7 +104,7 @@ test.each([ test.each(validTsInvalidLuaNames)( "ambient identifier must be a valid lua identifier (object literal shorthand) (%p)", - name => { + (name) => { util.testModule` declare var ${name}: any; const foo = { ${name} }; @@ -112,7 +112,7 @@ test.each(validTsInvalidLuaNames)( } ); -test.each(validTsInvalidLuaNames)("undeclared identifier must be a valid lua identifier (%p)", name => { +test.each(validTsInvalidLuaNames)("undeclared identifier must be a valid lua identifier (%p)", (name) => { util.testModule` const foo = ${name}; ` @@ -122,7 +122,7 @@ test.each(validTsInvalidLuaNames)("undeclared identifier must be a valid lua ide test.each(validTsInvalidLuaNames)( "undeclared identifier must be a valid lua identifier (object literal shorthand) (%p)", - name => { + (name) => { util.testModule` const foo = { ${name} }; ` @@ -131,7 +131,7 @@ test.each(validTsInvalidLuaNames)( } ); -test.each(validTsInvalidLuaNames)("exported values with invalid lua identifier names (%p)", name => { +test.each(validTsInvalidLuaNames)("exported values with invalid lua identifier names (%p)", (name) => { const code = `export const ${name} = "foobar";`; const lua = util.transpileString(code); expect(lua.indexOf(`"${name}"`)).toBeGreaterThanOrEqual(0); @@ -174,7 +174,7 @@ test("exported identifiers referenced in nested scope (%p)", () => { test.each(validTsInvalidLuaNames)( "exported values with invalid lua identifier names referenced in different scope (%p)", - name => { + (name) => { const code = ` export const ${name} = "foobar"; namespace NS { @@ -185,14 +185,14 @@ test.each(validTsInvalidLuaNames)( } ); -test.each(validTsInvalidLuaNames)("class with invalid lua name has correct name property", name => { +test.each(validTsInvalidLuaNames)("class with invalid lua name has correct name property", (name) => { util.testFunction` class ${name} {} return ${name}.name; `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaNames)("decorated class with invalid lua name", name => { +test.each(validTsInvalidLuaNames)("decorated class with invalid lua name", (name) => { util.testFunction` function decorator(c: T): T { c.bar = "foobar"; @@ -205,7 +205,7 @@ test.each(validTsInvalidLuaNames)("decorated class with invalid lua name", name `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaNames)("exported decorated class with invalid lua name", name => { +test.each(validTsInvalidLuaNames)("exported decorated class with invalid lua name", (name) => { const code = ` function decorator(c: T): T { c.bar = "foobar"; @@ -573,7 +573,7 @@ describe("lua keyword as identifier doesn't interfere with lua's value", () => { expect(util.transpileAndExecute(code)).toBe("foobar|string"); }); - test.each(["type", "type as type"])("imported variable (%p)", importName => { + test.each(["type", "type as type"])("imported variable (%p)", (importName) => { const luaHeader = ` package.loaded.someModule = {type = "foobar"}`; @@ -602,7 +602,7 @@ describe("lua keyword as identifier doesn't interfere with lua's value", () => { expect(util.transpileExecuteAndReturnExport(code, returnExport)).toBe(expectResult); }); - test.each(["type", "type as type"])("re-exported variable with lua keyword as name (%p)", importName => { + test.each(["type", "type as type"])("re-exported variable with lua keyword as name (%p)", (importName) => { const code = ` export { ${importName} } from "someModule"`; diff --git a/test/unit/json.spec.ts b/test/unit/json.spec.ts index b61e64fd1..5738a45c3 100644 --- a/test/unit/json.spec.ts +++ b/test/unit/json.spec.ts @@ -1,6 +1,6 @@ import * as util from "../util"; -test.each([0, "", [], [1, "2", []], { a: "b" }, { a: { b: "c" } }])("JSON (%p)", json => { +test.each([0, "", [], [1, "2", []], { a: "b" }, { a: { b: "c" } }])("JSON (%p)", (json) => { util.testModule(JSON.stringify(json)) .setMainFileName("main.json") .expectToEqual(json); diff --git a/test/unit/loops.spec.ts b/test/unit/loops.spec.ts index 172150c47..c01f92afa 100644 --- a/test/unit/loops.spec.ts +++ b/test/unit/loops.spec.ts @@ -526,11 +526,11 @@ for (const testCase of [ "for (const a in {}) { continue; }", "for (const a of []) { continue; }", ]) { - const expectContinueGotoLabel: util.TapCallback = builder => + const expectContinueGotoLabel: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toMatch("::__continue2::"); util.testEachVersion(`loop continue (${testCase})`, () => util.testModule(testCase), { - [tstl.LuaTarget.Lua51]: builder => builder.expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]), + [tstl.LuaTarget.Lua51]: (builder) => builder.expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]), [tstl.LuaTarget.Lua52]: expectContinueGotoLabel, [tstl.LuaTarget.Lua53]: expectContinueGotoLabel, [tstl.LuaTarget.LuaJIT]: expectContinueGotoLabel, diff --git a/test/unit/modules/modules.spec.ts b/test/unit/modules/modules.spec.ts index 885f24541..8c973bb69 100644 --- a/test/unit/modules/modules.spec.ts +++ b/test/unit/modules/modules.spec.ts @@ -9,7 +9,7 @@ describe("module import/export elision", () => { } `; - const expectToElideImport: util.TapCallback = builder => { + const expectToElideImport: util.TapCallback = (builder) => { builder.addExtraFile("module.d.ts", moduleDeclaration).setOptions({ module: ts.ModuleKind.CommonJS }); expect(builder.getLuaExecutionResult()).not.toBeInstanceOf(util.ExecutionError); }; @@ -53,7 +53,7 @@ describe("module import/export elision", () => { test.each(["ke-bab", "dollar$", "singlequote'", "hash#", "s p a c e", "ɥɣɎɌͼƛಠ", "_̀ः٠‿"])( "Import module names with invalid lua identifier characters (%p)", - name => { + (name) => { util.testModule` import { foo } from "./${name}"; export { foo }; @@ -65,7 +65,7 @@ test.each(["ke-bab", "dollar$", "singlequote'", "hash#", "s p a c e", "ɥɣɎɌ } ); -test.each(["export default value;", "export { value as default };"])("Export Default From (%p)", exportStatement => { +test.each(["export default value;", "export { value as default };"])("Export Default From (%p)", (exportStatement) => { const [result] = util.transpileAndExecuteProjectReturningMainExport( { "main.ts": ` @@ -203,7 +203,7 @@ const reassignmentTestCases = [ "({ x = 1 } = { x: undefined })", ]; -test.each(reassignmentTestCases)("export specifier with reassignment afterwards (%p)", reassignment => { +test.each(reassignmentTestCases)("export specifier with reassignment afterwards (%p)", (reassignment) => { util.testModule` let x = 0; export { x }; @@ -211,7 +211,7 @@ test.each(reassignmentTestCases)("export specifier with reassignment afterwards `.expectToMatchJsResult(); }); -test.each(reassignmentTestCases)("export specifier fork (%p)", reassignment => { +test.each(reassignmentTestCases)("export specifier fork (%p)", (reassignment) => { util.testModule` let x = 0; export { x as a }; diff --git a/test/unit/modules/resolution.spec.ts b/test/unit/modules/resolution.spec.ts index 541c28c56..5ebf569f1 100644 --- a/test/unit/modules/resolution.spec.ts +++ b/test/unit/modules/resolution.spec.ts @@ -3,7 +3,7 @@ import { unresolvableRequirePath } from "../../../src/transformation/utils/diagn import * as util from "../../util"; const requireRegex = /require\("(.*?)"\)/; -const expectToRequire = (expected: string): util.TapCallback => builder => { +const expectToRequire = (expected: string): util.TapCallback => (builder) => { const [, requiredPath] = builder.getMainLuaCodeChunk().match(requireRegex) ?? []; expect(requiredPath).toBe(expected); }; diff --git a/test/unit/nullishCoalescing.spec.ts b/test/unit/nullishCoalescing.spec.ts index 67dbc1cec..0064e856b 100644 --- a/test/unit/nullishCoalescing.spec.ts +++ b/test/unit/nullishCoalescing.spec.ts @@ -1,14 +1,14 @@ import * as util from "../util"; -test.each(["null", "undefined"])("nullish-coalesing operator returns rhs", nullishValue => { +test.each(["null", "undefined"])("nullish-coalesing operator returns rhs", (nullishValue) => { util.testExpression`${nullishValue} ?? "Hello, World!"`.expectToMatchJsResult(); }); -test.each([3, "foo", {}, [], true, false])("nullish-coalesing operator returns lhs", value => { +test.each([3, "foo", {}, [], true, false])("nullish-coalesing operator returns lhs", (value) => { util.testExpression`${util.formatCode(value)} ?? "Hello, World!"`.expectToMatchJsResult(); }); -test.each(["any", "unknown"])("nullish-coalesing operator with any/unknown type", type => { +test.each(["any", "unknown"])("nullish-coalesing operator with any/unknown type", (type) => { util.testFunction` const unknownType = false as ${type}; return unknownType ?? "This should not be returned!"; @@ -17,7 +17,7 @@ test.each(["any", "unknown"])("nullish-coalesing operator with any/unknown type" test.each(["boolean | string", "number | false", "undefined | true"])( "nullish-coalesing operator with union type", - unionType => { + (unionType) => { util.testFunction` const unknownType = false as ${unionType}; return unknownType ?? "This should not be returned!"; diff --git a/test/unit/objectLiteral.spec.ts b/test/unit/objectLiteral.spec.ts index 819143e1f..42c9545b9 100644 --- a/test/unit/objectLiteral.spec.ts +++ b/test/unit/objectLiteral.spec.ts @@ -2,7 +2,7 @@ import * as util from "../util"; test.each(['{ a: 3, b: "4" }', '{ "a": 3, b: "4" }', '{ ["a"]: 3, b: "4" }', '{ ["a" + 123]: 3, b: "4" }'])( "Object Literal (%p)", - inp => { + (inp) => { util.testExpression(inp).expectToMatchJsResult(); } ); @@ -30,7 +30,7 @@ describe("property shorthand", () => { `.expectToMatchJsResult(); }); - test.each([NaN, Infinity])("should support %p shorthand", identifier => { + test.each([NaN, Infinity])("should support %p shorthand", (identifier) => { util.testExpression`({ ${identifier} }).${identifier}`.expectToMatchJsResult(); }); @@ -59,7 +59,7 @@ test("undefined as object key", () => { test.each(['{x: "foobar"}.x', '{x: "foobar"}["x"]', '{x: () => "foobar"}.x()', '{x: () => "foobar"}["x"]()'])( "object literal property access (%p)", - expression => { + (expression) => { util.testExpression(expression).expectToMatchJsResult(); } ); diff --git a/test/unit/printer/parenthesis.spec.ts b/test/unit/printer/parenthesis.spec.ts index ef08a6e3d..d791d73e4 100644 --- a/test/unit/printer/parenthesis.spec.ts +++ b/test/unit/printer/parenthesis.spec.ts @@ -19,7 +19,7 @@ test.each([ "(x as any).foo;", "((x as unknown) as any).foo;", "((x) as any).foo;", -])("'as' type assertion should strip parenthesis (%p)", expression => { +])("'as' type assertion should strip parenthesis (%p)", (expression) => { const code = ` declare let x: unknown; declare let y: { x: unknown; z(this: void): unknown; }; @@ -44,7 +44,7 @@ test.each([ "((!x as unknown) as any).foo;", "(!x as any).foo;", "((!x) as any).foo;", -])("'as' type assertion should not strip parenthesis (%p)", expression => { +])("'as' type assertion should not strip parenthesis (%p)", (expression) => { const code = ` declare let x: number; declare let y: {}; diff --git a/test/unit/printer/semicolons.spec.ts b/test/unit/printer/semicolons.spec.ts index addb66e53..a3dc7e017 100644 --- a/test/unit/printer/semicolons.spec.ts +++ b/test/unit/printer/semicolons.spec.ts @@ -2,7 +2,7 @@ import * as util from "../../util"; test.each(["const a = 1; const b = a;", "const a = 1; let b: number; b = a;", "{}", "function bar() {} bar();"])( "semicolon insertion (%p)", - leadingStatement => { + (leadingStatement) => { util.testFunction` let result = ""; function foo() { result = "foo"; } diff --git a/test/unit/printer/sourcemaps.spec.ts b/test/unit/printer/sourcemaps.spec.ts index 6b4487ac9..bb28464bd 100644 --- a/test/unit/printer/sourcemaps.spec.ts +++ b/test/unit/printer/sourcemaps.spec.ts @@ -236,7 +236,7 @@ test.each([ const consumer = await new SourceMapConsumer(file.sourceMap); const typescriptPosition = lineAndColumnOf(code, name); let mappedName: string | undefined; - consumer.eachMapping(mapping => { + consumer.eachMapping((mapping) => { if (mapping.originalLine === typescriptPosition.line && mapping.originalColumn === typescriptPosition.column) { mappedName = mapping.name; } @@ -313,7 +313,7 @@ function lineAndColumnOf(text: string, pattern: string): Position { return { line: -1, column: -1 }; } - const lineLengths = text.split("\n").map(s => s.length); + const lineLengths = text.split("\n").map((s) => s.length); let totalPos = 0; for (let line = 1; line <= lineLengths.length; line++) { diff --git a/test/unit/spread.spec.ts b/test/unit/spread.spec.ts index dec923d83..405a1a826 100644 --- a/test/unit/spread.spec.ts +++ b/test/unit/spread.spec.ts @@ -3,8 +3,9 @@ import * as util from "../util"; import { formatCode } from "../util"; // TODO: Make some utils for testing other targets -const expectUnpack: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toMatch(/[^.]unpack\(/); -const expectTableUnpack: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toContain("table.unpack"); +const expectUnpack: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toMatch(/[^.]unpack\(/); +const expectTableUnpack: util.TapCallback = (builder) => + expect(builder.getMainLuaCodeChunk()).toContain("table.unpack"); const arrayLiteralCases = [ "1, 2, ...[3, 4, 5]", @@ -14,14 +15,14 @@ const arrayLiteralCases = [ "1, 2, ...[3, 4], ...[5, 6]", ]; -describe.each(["function call", "array literal"] as const)("in %s", kind => { +describe.each(["function call", "array literal"] as const)("in %s", (kind) => { const factory = (code: string) => (kind === "function call" ? `((...args: any[]) => args)(${code})` : `[${code}]`); - test.each(arrayLiteralCases)("of array literal (%p)", expression => { + test.each(arrayLiteralCases)("of array literal (%p)", (expression) => { util.testExpression(factory(expression)).expectToMatchJsResult(); }); - test.each(arrayLiteralCases)("of tuple return call (%p)", expression => { + test.each(arrayLiteralCases)("of tuple return call (%p)", (expression) => { util.testFunction` /** @tupleReturn */ function tuple(...args: any[]) { @@ -36,7 +37,7 @@ describe.each(["function call", "array literal"] as const)("in %s", kind => { util.testExpression(factory('..."spread", ..."string"')).expectToMatchJsResult(); }); - test.each(["", "string", "string with spaces", "string 1 2 3"])("of string literal (%p)", str => { + test.each(["", "string", "string with spaces", "string 1 2 3"])("of string literal (%p)", (str) => { util.testExpression(factory(`...${formatCode(str)}`)).expectToMatchJsResult(); }); @@ -72,20 +73,20 @@ describe("in function call", () => { return foo(...array); `, { - [tstl.LuaTarget.LuaJIT]: builder => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua51]: builder => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua52]: builder => builder.tap(expectTableUnpack), - [tstl.LuaTarget.Lua53]: builder => builder.tap(expectTableUnpack).expectToMatchJsResult(), + [tstl.LuaTarget.LuaJIT]: (builder) => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua51]: (builder) => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua52]: (builder) => builder.tap(expectTableUnpack), + [tstl.LuaTarget.Lua53]: (builder) => builder.tap(expectTableUnpack).expectToMatchJsResult(), } ); }); describe("in array literal", () => { util.testEachVersion(undefined, () => util.testExpression`[...[0, 1, 2]]`, { - [tstl.LuaTarget.LuaJIT]: builder => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua51]: builder => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua52]: builder => builder.tap(expectTableUnpack), - [tstl.LuaTarget.Lua53]: builder => builder.tap(expectTableUnpack).expectToMatchJsResult(), + [tstl.LuaTarget.LuaJIT]: (builder) => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua51]: (builder) => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua52]: (builder) => builder.tap(expectTableUnpack), + [tstl.LuaTarget.Lua53]: (builder) => builder.tap(expectTableUnpack).expectToMatchJsResult(), }); test("of array literal /w OmittedExpression", () => { @@ -103,7 +104,7 @@ describe("in object literal", () => { "{ ...{ x: true }, ...{ y: true, z: true } }", "{ ...{ x: false }, x: true }", "{ ...{ x: false }, x: false, ...{ x: true } }", - ])("of object literal (%p)", expression => { + ])("of object literal (%p)", (expression) => { util.testExpression(expression).expectToMatchJsResult(); }); diff --git a/test/unit/templateLiterals.spec.ts b/test/unit/templateLiterals.spec.ts index 7db192a88..6a5aa5777 100644 --- a/test/unit/templateLiterals.spec.ts +++ b/test/unit/templateLiterals.spec.ts @@ -11,16 +11,19 @@ test.each([ util.testExpressionTemplate`\`\${${a}} \${${b}} test \${${c}}\``.expectToMatchJsResult(); }); -test.each(["a++", "a--", "--a", "++a"])("template literal with expression (%p)", expression => { +test.each(["a++", "a--", "--a", "++a"])("template literal with expression (%p)", (expression) => { util.testFunction` let a = 3; return \`value\${${expression}}\`; `.expectToMatchJsResult(); }); -test.each(["`foo${'bar'}`.length", "`foo${'bar'}`.repeat(2)"])("template literal property access (%p)", expression => { - util.testExpression(expression).expectToMatchJsResult(); -}); +test.each(["`foo${'bar'}`.length", "`foo${'bar'}`.repeat(2)"])( + "template literal property access (%p)", + (expression) => { + util.testExpression(expression).expectToMatchJsResult(); + } +); test.each([ "func``", @@ -36,7 +39,7 @@ test.each([ "func`hello \\``", "obj.func`hello ${'propertyAccessExpression'}`", "obj['func']`hello ${'elementAccessExpression'}`", -])("tagged template literal (%p)", expression => { +])("tagged template literal (%p)", (expression) => { util.testFunction` function func(strings: TemplateStringsArray, ...expressions: any[]) { return { strings: [...strings], raw: strings.raw, expressions }; @@ -49,7 +52,7 @@ test.each([ test.each(["func`noSelfParameter`", "obj.func`noSelfParameter`", "obj[`func`]`noSelfParameter`"])( "tagged template literal function context (%p)", - expression => { + (expression) => { util.testFunction` function func(this: void, strings: TemplateStringsArray) { return [...strings]; diff --git a/test/unit/typeof.spec.ts b/test/unit/typeof.spec.ts index f8a063c1c..28bbbce1e 100644 --- a/test/unit/typeof.spec.ts +++ b/test/unit/typeof.spec.ts @@ -1,18 +1,18 @@ import * as util from "../util"; -test.each(["0", "30", "30_000", "30.00"])("typeof number (%p)", inp => { +test.each(["0", "30", "30_000", "30.00"])("typeof number (%p)", (inp) => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); -test.each(['"abc"', "`abc`"])("typeof string (%p)", inp => { +test.each(['"abc"', "`abc`"])("typeof string (%p)", (inp) => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); -test.each(["false", "true"])("typeof boolean (%p)", inp => { +test.each(["false", "true"])("typeof boolean (%p)", (inp) => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); -test.each(["{}", "[]"])("typeof object literal (%p)", inp => { +test.each(["{}", "[]"])("typeof object literal (%p)", (inp) => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); @@ -34,7 +34,7 @@ test("typeof function", () => { util.testExpression`typeof (() => 3)`.expectToMatchJsResult(); }); -test.each(["null", "undefined"])("typeof %s", inp => { +test.each(["null", "undefined"])("typeof %s", (inp) => { util.testExpression`typeof ${inp}`.expectToEqual("undefined"); }); @@ -63,8 +63,8 @@ const relationalComparisonCases: ComparisonCase[] = [ { expression: "undefined", operator: ">", compareTo: "object" }, ]; -const expectTypeOfHelper: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toMatch("__TS__TypeOf"); -const expectNoTypeOfHelper: util.TapCallback = builder => +const expectTypeOfHelper: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toMatch("__TS__TypeOf"); +const expectNoTypeOfHelper: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("__TS__TypeOf"); test.each(equalityComparisonCases)("typeof literal equality comparison (%p)", ({ expression, operator, compareTo }) => { diff --git a/test/util.ts b/test/util.ts index 1b30c5105..8a655987f 100644 --- a/test/util.ts +++ b/test/util.ts @@ -18,7 +18,7 @@ export function assert(value: any, message?: string | Error): asserts value { nativeAssert(value, message); } -export const formatCode = (...values: unknown[]) => values.map(e => stringify(e)).join(", "); +export const formatCode = (...values: unknown[]) => values.map((e) => stringify(e)).join(", "); export function testEachVersion( name: string | undefined, @@ -54,7 +54,7 @@ interface TranspileJsResult { function transpileJs(program: ts.Program): TranspileJsResult { const transpiledFiles: TranspiledJsFile[] = []; const updateTranspiledFile = (fileName: string, update: Omit) => { - const file = transpiledFiles.find(f => f.fileName === fileName); + const file = transpiledFiles.find((f) => f.fileName === fileName); if (file) { Object.assign(file, update); } else { @@ -92,7 +92,7 @@ function executeLua(code: string): any { } } else { // Filter out control characters appearing on some systems - const luaStackString = lua.lua_tostring(L, -1).filter(c => c >= 20); + const luaStackString = lua.lua_tostring(L, -1).filter((c) => c >= 20); const message = to_jsstring(luaStackString).replace(/^\[string "--\.\.\."\]:\d+: /, ""); return new ExecutionError(message); } @@ -279,7 +279,7 @@ export abstract class TestBuilder { const { transpiledFiles } = this.getLuaResult(); const mainFile = this.options.luaBundle ? transpiledFiles[0] - : transpiledFiles.find(x => x.fileName === this.mainFileName); + : transpiledFiles.find((x) => x.fileName === this.mainFileName); expect(mainFile).toMatchObject({ lua: expect.any(String), sourceMap: expect.any(String) }); return mainFile as ExecutableTranspiledFile; } @@ -305,7 +305,7 @@ export abstract class TestBuilder { @memoize protected getMainJsCodeChunk(): string { const { transpiledFiles } = this.getJsResult(); - const code = transpiledFiles.find(x => x.fileName === this.mainFileName)?.js; + const code = transpiledFiles.find((x) => x.fileName === this.mainFileName)?.js; assert(code !== undefined); const header = this.jsHeader ? `${this.jsHeader.trimRight()}\n` : ""; @@ -323,7 +323,7 @@ export abstract class TestBuilder { private getLuaDiagnostics(): ts.Diagnostic[] { const { diagnostics } = this.getLuaResult(); - return diagnostics.filter(d => this.semanticCheck || d.source === "typescript-to-lua"); + return diagnostics.filter((d) => this.semanticCheck || d.source === "typescript-to-lua"); } // Actions @@ -391,7 +391,7 @@ export abstract class TestBuilder { const diagnosticMessages = ts.formatDiagnostics( this.getLuaDiagnostics().map(tstl.prepareDiagnosticForFormatting), - { getCurrentDirectory: () => "", getCanonicalFileName: fileName => fileName, getNewLine: () => "\n" } + { getCurrentDirectory: () => "", getCanonicalFileName: (fileName) => fileName, getNewLine: () => "\n" } ); expect(diagnosticMessages.trim()).toMatchSnapshot("diagnostics"); @@ -463,7 +463,7 @@ const createTestBuilderFactory = ( } else { let [raw, ...substitutions] = args; if (serializeSubstitutions) { - substitutions = substitutions.map(s => formatCode(s)); + substitutions = substitutions.map((s) => formatCode(s)); } tsCode = String.raw(Object.assign([], { raw }), ...substitutions); From 12287b4cc955864b65a4bff7e3dc2aaef20c676e Mon Sep 17 00:00:00 2001 From: ark120202 Date: Sun, 10 May 2020 00:34:12 +0000 Subject: [PATCH 2/3] Upgrade Prettier to v2 --- .prettierrc.json | 5 +---- package-lock.json | 6 +++--- package.json | 6 +++--- src/lualib/Error.ts | 2 +- src/transformation/utils/safe-names.ts | 9 +-------- src/transpilation/transpile.ts | 5 +---- src/tstl.ts | 5 +---- test/unit/builtins/console.spec.ts | 24 ++++++------------------ test/unit/builtins/math.spec.ts | 4 +--- test/unit/expressions.spec.ts | 4 +--- test/unit/json.spec.ts | 4 +--- test/unit/printer/sourcemaps.spec.ts | 10 ++-------- test/util.ts | 2 +- 13 files changed, 23 insertions(+), 63 deletions(-) diff --git a/.prettierrc.json b/.prettierrc.json index c1af7b57f..a53b1a4f5 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,8 +1,5 @@ { "printWidth": 120, "tabWidth": 4, - "trailingComma": "es5", - "endOfLine": "lf", - "overrides": [{ "files": ["**/*.md", "**/*.yml"], "options": { "tabWidth": 2 } }], - "arrowParens": "always" + "overrides": [{ "files": ["**/*.md", "**/*.yml"], "options": { "tabWidth": 2 } }] } diff --git a/package-lock.json b/package-lock.json index f3d427049..27e78daf9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4330,9 +4330,9 @@ "dev": true }, "prettier": { - "version": "1.19.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz", - "integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.5.tgz", + "integrity": "sha512-7PtVymN48hGcO4fGjybyBSIWDsLU4H4XlvOHfq91pz9kkGlonzwTfYkaIEwiRg/dAJF9YlbsduBAgtYLi+8cFg==", "dev": true }, "pretty-format": { diff --git a/package.json b/package.json index 6651b3109..9c573b30c 100644 --- a/package.json +++ b/package.json @@ -23,9 +23,9 @@ "pretest": "npm run lint && npm run build-lualib", "test": "jest", "lint": "npm run lint:eslint && npm run lint:prettier", - "lint:prettier": "prettier --check \"**/*.{js,ts,yml,json,md}\" || (echo 'Run `npm run fix:prettier` to fix it.' && exit 1)", + "lint:prettier": "prettier --check . || (echo 'Run `npm run fix:prettier` to fix it.' && exit 1)", "lint:eslint": "eslint . --ext .js,.ts", - "fix:prettier": "prettier --check --write \"**/*.{js,ts,yml,json,md}\"", + "fix:prettier": "prettier --write .", "preversion": "npm run build && npm test", "postversion": "git push && git push --tags" }, @@ -56,7 +56,7 @@ "javascript-stringify": "^2.0.1", "jest": "^25.1.0", "jest-circus": "^25.1.0", - "prettier": "^1.19.1", + "prettier": "^2.0.5", "ts-jest": "^25.2.1", "ts-node": "^8.6.2" } diff --git a/src/lualib/Error.ts b/src/lualib/Error.ts index c91223f65..d44a3b9eb 100644 --- a/src/lualib/Error.ts +++ b/src/lualib/Error.ts @@ -21,7 +21,7 @@ function __TS__GetErrorStack(constructor: Function): string { } function __TS__WrapErrorToString(getDescription: (this: T) => string): (this: T) => string { - return function(this: Error): string { + return function (this: Error): string { const description = getDescription.call(this); const caller = debug.getinfo(3, "f"); if (_VERSION === "Lua 5.1" || (caller && caller.func !== error)) { diff --git a/src/transformation/utils/safe-names.ts b/src/transformation/utils/safe-names.ts index 1ac3f4c3c..ae4b6d236 100644 --- a/src/transformation/utils/safe-names.ts +++ b/src/transformation/utils/safe-names.ts @@ -99,13 +99,6 @@ export function hasUnsafeIdentifierName( } const fixInvalidLuaIdentifier = (name: string) => - name.replace( - /[^a-zA-Z0-9_]/g, - (c) => - `_${c - .charCodeAt(0) - .toString(16) - .toUpperCase()}` - ); + name.replace(/[^a-zA-Z0-9_]/g, (c) => `_${c.charCodeAt(0).toString(16).toUpperCase()}`); export const createSafeName = (name: string) => "____" + fixInvalidLuaIdentifier(name); diff --git a/src/transpilation/transpile.ts b/src/transpilation/transpile.ts index 7755f2ee1..2f9e95f14 100644 --- a/src/transpilation/transpile.ts +++ b/src/transpilation/transpile.ts @@ -142,10 +142,7 @@ export function transpile({ diagnostics.push(...program.emit(undefined, writeFile, undefined, false, transformers).diagnostics); // JSON files don't get through transformers and aren't written when outDir is the same as rootDir - program - .getSourceFiles() - .filter(isEmittableJsonFile) - .forEach(processSourceFile); + program.getSourceFiles().filter(isEmittableJsonFile).forEach(processSourceFile); } options.noEmit = oldNoEmit; diff --git a/src/tstl.ts b/src/tstl.ts index 456ebbb38..9dc4665f0 100644 --- a/src/tstl.ts +++ b/src/tstl.ts @@ -202,10 +202,7 @@ function updateWatchCompilationHost( } function checkNodeVersion(): void { - const [major, minor] = process.version - .slice(1) - .split(".") - .map(Number); + const [major, minor] = process.version.slice(1).split(".").map(Number); const isValid = major > 12 || (major === 12 && minor >= 13); if (!isValid) { console.error(`TypeScriptToLua requires Node.js >=12.13.0, the current version is ${process.version}`); diff --git a/test/unit/builtins/console.spec.ts b/test/unit/builtins/console.spec.ts index 4129b8240..463d5e9d5 100644 --- a/test/unit/builtins/console.spec.ts +++ b/test/unit/builtins/console.spec.ts @@ -9,9 +9,7 @@ test.each([ 'console.log("Hello %%s", "there")', 'console.log("Hello", "There")', ])("console.log (%p)", (code) => { - util.testFunction(code) - .setOptions(compilerOptions) - .expectLuaToMatchSnapshot(); + util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); test.each([ @@ -21,9 +19,7 @@ test.each([ 'console.info("Hello %%s", "there")', 'console.info("Hello", "There")', ])("console.info (%p)", (code) => { - util.testFunction(code) - .setOptions(compilerOptions) - .expectLuaToMatchSnapshot(); + util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); test.each([ @@ -33,9 +29,7 @@ test.each([ 'console.error("Hello %%s", "there")', 'console.error("Hello", "There")', ])("console.error (%p)", (code) => { - util.testFunction(code) - .setOptions(compilerOptions) - .expectLuaToMatchSnapshot(); + util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); test.each([ @@ -45,9 +39,7 @@ test.each([ 'console.warn("Hello %%s", "there")', 'console.warn("Hello", "There")', ])("console.warn (%p)", (code) => { - util.testFunction(code) - .setOptions(compilerOptions) - .expectLuaToMatchSnapshot(); + util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); test.each([ @@ -57,9 +49,7 @@ test.each([ 'console.trace("Hello %%s", "there")', 'console.trace("Hello", "there")', ])("console.trace (%p)", (code) => { - util.testFunction(code) - .setOptions(compilerOptions) - .expectLuaToMatchSnapshot(); + util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); test.each([ @@ -69,9 +59,7 @@ test.each([ 'console.assert(false, "message %%s", "info")', 'console.assert(false, "message", "more")', ])("console.assert (%p)", (code) => { - util.testFunction(code) - .setOptions(compilerOptions) - .expectLuaToMatchSnapshot(); + util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); test("console.differentiation", () => { diff --git a/test/unit/builtins/math.spec.ts b/test/unit/builtins/math.spec.ts index 6fbbf5a4a..383e742cd 100644 --- a/test/unit/builtins/math.spec.ts +++ b/test/unit/builtins/math.spec.ts @@ -14,9 +14,7 @@ test.each([ "Math.PI", ])("%s", (code) => { // TODO: Remove? - util.testFunction(code) - .disableSemanticCheck() - .expectLuaToMatchSnapshot(); + util.testFunction(code).disableSemanticCheck().expectLuaToMatchSnapshot(); }); test.each(["E", "LN10", "LN2", "LOG10E", "LOG2E", "SQRT1_2", "SQRT2"])("Math.%s", (constant) => { diff --git a/test/unit/expressions.spec.ts b/test/unit/expressions.spec.ts index c5f4b3702..620fd2e29 100644 --- a/test/unit/expressions.spec.ts +++ b/test/unit/expressions.spec.ts @@ -15,9 +15,7 @@ test.each([ "let a = delete tbl.test", "delete tbl.test", ])("Unary expressions basic (%p)", (input) => { - util.testFunction(input) - .disableSemanticCheck() - .expectLuaToMatchSnapshot(); + util.testFunction(input).disableSemanticCheck().expectLuaToMatchSnapshot(); }); test.each(["3+4", "5-2", "6*3", "6**3", "20/5", "15/10", "15%3"])("Binary expressions basic numeric (%p)", (input) => { diff --git a/test/unit/json.spec.ts b/test/unit/json.spec.ts index 5738a45c3..d8061eca4 100644 --- a/test/unit/json.spec.ts +++ b/test/unit/json.spec.ts @@ -1,9 +1,7 @@ import * as util from "../util"; test.each([0, "", [], [1, "2", []], { a: "b" }, { a: { b: "c" } }])("JSON (%p)", (json) => { - util.testModule(JSON.stringify(json)) - .setMainFileName("main.json") - .expectToEqual(json); + util.testModule(JSON.stringify(json)).setMainFileName("main.json").expectToEqual(json); }); test("Empty JSON file error", () => { diff --git a/test/unit/printer/sourcemaps.spec.ts b/test/unit/printer/sourcemaps.spec.ts index bb28464bd..db14745a9 100644 --- a/test/unit/printer/sourcemaps.spec.ts +++ b/test/unit/printer/sourcemaps.spec.ts @@ -144,10 +144,7 @@ test.each([ ], }, ])("Source map has correct mapping (%p)", async ({ code, assertPatterns }) => { - const file = util - .testModule(code) - .expectToHaveNoDiagnostics() - .getMainLuaFileResult(); + const file = util.testModule(code).expectToHaveNoDiagnostics().getMainLuaFileResult(); const consumer = await new SourceMapConsumer(file.sourceMap); for (const { luaPattern, typeScriptPattern } of assertPatterns) { @@ -228,10 +225,7 @@ test.each([ { code: "class $$$ {}", name: "$$$" }, { code: 'namespace $$$ { const foo = "bar"; }', name: "$$$" }, ])("Source map has correct name mappings (%p)", async ({ code, name }) => { - const file = util - .testModule(code) - .expectToHaveNoDiagnostics() - .getMainLuaFileResult(); + const file = util.testModule(code).expectToHaveNoDiagnostics().getMainLuaFileResult(); const consumer = await new SourceMapConsumer(file.sourceMap); const typescriptPosition = lineAndColumnOf(code, name); diff --git a/test/util.ts b/test/util.ts index 8a655987f..b1d993b08 100644 --- a/test/util.ts +++ b/test/util.ts @@ -150,7 +150,7 @@ function executeJsModule(code: string): any { const memoize: MethodDecorator = (_target, _propertyKey, descriptor) => { const originalFunction = descriptor.value as any; const memoized = new WeakMap(); - descriptor.value = function(this: any, ...args: any[]): any { + descriptor.value = function (this: any, ...args: any[]): any { if (!memoized.has(this)) { memoized.set(this, originalFunction.apply(this, args)); } From 673d0a7684a78c1d9ac22209fd04a59d37c5fd19 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Sun, 24 May 2020 22:14:34 +0000 Subject: [PATCH 3/3] Revert "Set "arrowParens" option to "always"" This reverts commit 1f3a98123e63454efd4a7ca9bed2f57f2276631b. --- .prettierrc.json | 1 + src/LuaPrinter.ts | 27 +++++++------ src/cli/information.ts | 2 +- src/cli/parse.ts | 12 +++--- src/cli/report.ts | 2 +- src/cli/tsconfig.ts | 2 +- src/lualib/StringReplace.ts | 2 +- src/transformation/context/context.ts | 6 +-- src/transformation/utils/annotations.ts | 6 +-- src/transformation/utils/export.ts | 6 +-- src/transformation/utils/function-context.ts | 10 ++--- src/transformation/utils/lua-ast.ts | 4 +- src/transformation/utils/safe-names.ts | 4 +- src/transformation/utils/scope.ts | 6 +-- src/transformation/utils/typescript/index.ts | 4 +- src/transformation/utils/typescript/types.ts | 14 +++---- .../visitors/binary-expression/assignments.ts | 6 +-- src/transformation/visitors/call.ts | 4 +- .../visitors/class/decorators.ts | 4 +- src/transformation/visitors/class/index.ts | 10 ++--- .../visitors/class/members/accessors.ts | 4 +- .../visitors/class/members/constructor.ts | 2 +- src/transformation/visitors/class/utils.ts | 4 +- src/transformation/visitors/conditional.ts | 2 +- src/transformation/visitors/function.ts | 4 +- src/transformation/visitors/literal.ts | 16 ++++---- src/transformation/visitors/loops/for-of.ts | 6 +-- src/transformation/visitors/loops/for.ts | 2 +- src/transformation/visitors/modules/export.ts | 6 +-- src/transformation/visitors/modules/import.ts | 4 +- src/transformation/visitors/namespace.ts | 4 +- src/transformation/visitors/return.ts | 2 +- src/transformation/visitors/template.ts | 10 ++--- .../visitors/variable-declaration.ts | 10 ++--- src/transpilation/bundle.ts | 6 +-- src/transpilation/emit.ts | 2 +- src/transpilation/index.ts | 2 +- src/transpilation/transformers.ts | 6 +-- src/transpilation/transpile.ts | 6 +-- src/tstl.ts | 6 +-- test/cli/parse.spec.ts | 4 +- test/cli/run.ts | 4 +- test/cli/watch.spec.ts | 4 +- test/legacy-utils.ts | 10 ++--- test/setup.ts | 6 +-- test/translation/transformation.spec.ts | 4 +- test/transpile/plugins/plugins.spec.ts | 2 +- test/transpile/run.ts | 2 +- test/transpile/transformers/fixtures.ts | 25 ++++++------ .../transformers/transformers.spec.ts | 2 +- test/transpile/transformers/utils.ts | 2 +- .../annotations/compileMembersOnly.spec.ts | 4 +- test/unit/annotations/extension.spec.ts | 6 +-- test/unit/annotations/forRange.spec.ts | 4 +- test/unit/annotations/luaTable.spec.ts | 38 +++++++++---------- test/unit/annotations/tupleReturn.spec.ts | 2 +- test/unit/annotations/vararg.spec.ts | 8 ++-- test/unit/assignments.spec.ts | 30 +++++++-------- test/unit/builtins/array.spec.ts | 12 +++--- test/unit/builtins/console.spec.ts | 12 +++--- test/unit/builtins/loading.spec.ts | 12 +++--- test/unit/builtins/map.spec.ts | 6 +-- test/unit/builtins/math.spec.ts | 18 ++++----- test/unit/builtins/numbers.spec.ts | 18 ++++----- test/unit/builtins/object.spec.ts | 8 ++-- test/unit/builtins/set.spec.ts | 4 +- test/unit/builtins/string.spec.ts | 14 +++---- test/unit/builtins/symbol.spec.ts | 4 +- test/unit/builtins/weakMap.spec.ts | 2 +- test/unit/builtins/weakSet.spec.ts | 2 +- test/unit/classes/classes.spec.ts | 2 +- test/unit/conditionals.spec.ts | 28 +++++++------- test/unit/destructuring.spec.ts | 10 ++--- test/unit/enum.spec.ts | 4 +- test/unit/error.spec.ts | 8 ++-- test/unit/expressions.spec.ts | 35 ++++++++--------- test/unit/functions/functions.spec.ts | 10 ++--- .../functions/noImplicitSelfOption.spec.ts | 2 +- test/unit/functions/noSelfAnnotation.spec.ts | 4 +- .../functionExpressionTypeInference.spec.ts | 6 +-- .../invalidFunctionAssignments.spec.ts | 2 +- .../validFunctionAssignments.spec.ts | 2 +- test/unit/hoisting.spec.ts | 6 +-- test/unit/identifiers.spec.ts | 36 +++++++++--------- test/unit/json.spec.ts | 2 +- test/unit/loops.spec.ts | 4 +- test/unit/modules/modules.spec.ts | 10 ++--- test/unit/modules/resolution.spec.ts | 2 +- test/unit/nullishCoalescing.spec.ts | 8 ++-- test/unit/objectLiteral.spec.ts | 6 +-- test/unit/printer/parenthesis.spec.ts | 4 +- test/unit/printer/semicolons.spec.ts | 2 +- test/unit/printer/sourcemaps.spec.ts | 4 +- test/unit/spread.spec.ts | 31 ++++++++------- test/unit/templateLiterals.spec.ts | 15 +++----- test/unit/typeof.spec.ts | 14 +++---- test/util.ts | 16 ++++---- 97 files changed, 384 insertions(+), 394 deletions(-) diff --git a/.prettierrc.json b/.prettierrc.json index a53b1a4f5..9dd6427dc 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,5 +1,6 @@ { "printWidth": 120, "tabWidth": 4, + "arrowParens": "avoid", "overrides": [{ "files": ["**/*.md", "**/*.yml"], "options": { "tabWidth": 2 } }] } diff --git a/src/LuaPrinter.ts b/src/LuaPrinter.ts index df479996e..63654c595 100644 --- a/src/LuaPrinter.ts +++ b/src/LuaPrinter.ts @@ -23,8 +23,7 @@ const escapeStringMap: Record = { "\0": "\\0", }; -export const escapeString = (value: string) => - `"${value.replace(escapeStringRegExp, (char) => escapeStringMap[char])}"`; +export const escapeString = (value: string) => `"${value.replace(escapeStringRegExp, char => escapeStringMap[char])}"`; /** * Checks that a name is valid for use in lua function declaration syntax: @@ -46,7 +45,7 @@ function isSimpleExpression(expression: lua.Expression): boolean { case lua.SyntaxKind.TableExpression: const tableExpression = expression as lua.TableExpression; - return tableExpression.fields.every((e) => isSimpleExpression(e)); + return tableExpression.fields.every(e => isSimpleExpression(e)); case lua.SyntaxKind.TableFieldExpression: const fieldExpression = expression as lua.TableFieldExpression; @@ -272,7 +271,7 @@ export class LuaPrinter { private nodeStartsWithParenthesis(sourceNode: SourceNode): boolean { let result: boolean | undefined; - sourceNode.walk((chunk) => { + sourceNode.walk(chunk => { if (result === undefined) { chunk = chunk.trimLeft(); // Ignore leading whitespace @@ -359,11 +358,11 @@ export class LuaPrinter { // Print all local functions as `local function foo()` instead of `local foo = function` to allow recursion chunks.push(this.printFunctionDefinition(statement)); } else { - chunks.push(...this.joinChunksWithComma(statement.left.map((e) => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.left.map(e => this.printExpression(e)))); if (statement.right) { chunks.push(" = "); - chunks.push(...this.joinChunksWithComma(statement.right.map((e) => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.right.map(e => this.printExpression(e)))); } } @@ -387,9 +386,9 @@ export class LuaPrinter { } } - chunks.push(...this.joinChunksWithComma(statement.left.map((e) => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.left.map(e => this.printExpression(e)))); chunks.push(" = "); - chunks.push(...this.joinChunksWithComma(statement.right.map((e) => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.right.map(e => this.printExpression(e)))); return this.createSourceNode(statement, chunks); } @@ -473,8 +472,8 @@ export class LuaPrinter { } public printForInStatement(statement: lua.ForInStatement): SourceNode { - const names = this.joinChunksWithComma(statement.names.map((i) => this.printIdentifier(i))); - const expressions = this.joinChunksWithComma(statement.expressions.map((e) => this.printExpression(e))); + const names = this.joinChunksWithComma(statement.names.map(i => this.printIdentifier(i))); + const expressions = this.joinChunksWithComma(statement.expressions.map(e => this.printExpression(e))); const chunks: SourceChunk[] = []; @@ -503,7 +502,7 @@ export class LuaPrinter { const chunks: SourceChunk[] = []; - chunks.push(...this.joinChunksWithComma(statement.expressions.map((e) => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(statement.expressions.map(e => this.printExpression(e)))); return this.createSourceNode(statement, [this.indent(), "return ", ...chunks]); } @@ -574,7 +573,7 @@ export class LuaPrinter { } private printFunctionParameters(expression: lua.FunctionExpression): SourceChunk[] { - const parameterChunks = (expression.params ?? []).map((i) => this.printIdentifier(i)); + const parameterChunks = (expression.params ?? []).map(i => this.printIdentifier(i)); if (expression.dots) { parameterChunks.push(this.printDotsLiteral(expression.dots)); @@ -595,7 +594,7 @@ export class LuaPrinter { chunks.push(" "); const returnNode: SourceChunk[] = [ "return ", - ...this.joinChunksWithComma(returnStatement.expressions.map((e) => this.printExpression(e))), + ...this.joinChunksWithComma(returnStatement.expressions.map(e => this.printExpression(e))), ]; chunks.push(this.createSourceNode(returnStatement, returnNode)); chunks.push(this.createSourceNode(expression, " end")); @@ -751,7 +750,7 @@ export class LuaPrinter { const chunks: SourceChunk[] = []; if (expressions.every(isSimpleExpression)) { - chunks.push(...this.joinChunksWithComma(expressions.map((e) => this.printExpression(e)))); + chunks.push(...this.joinChunksWithComma(expressions.map(e => this.printExpression(e)))); } else { chunks.push("\n"); this.pushIndent(); diff --git a/src/cli/information.ts b/src/cli/information.ts index 2ab1f8d8f..4c4b3ce1a 100644 --- a/src/cli/information.ts +++ b/src/cli/information.ts @@ -19,7 +19,7 @@ export function getHelpString(): string { result += "Options:\n"; for (const option of optionDeclarations) { - const aliasStrings = (option.aliases ?? []).map((a) => "-" + a); + const aliasStrings = (option.aliases ?? []).map(a => "-" + a); const optionString = [...aliasStrings, "--" + option.name].join("|"); const valuesHint = option.type === "enum" ? option.choices.join("|") : option.type; diff --git a/src/cli/parse.ts b/src/cli/parse.ts index d7040daf3..1ffa50d6a 100644 --- a/src/cli/parse.ts +++ b/src/cli/parse.ts @@ -72,7 +72,7 @@ export const optionDeclarations: CommandLineOption[] = [ export function updateParsedConfigFile(parsedConfigFile: ts.ParsedCommandLine): ParsedCommandLine { let hasRootLevelOptions = false; for (const [name, rawValue] of Object.entries(parsedConfigFile.raw)) { - const option = optionDeclarations.find((option) => option.name === name); + const option = optionDeclarations.find(option => option.name === name); if (!option) continue; if (parsedConfigFile.raw.tstl === undefined) parsedConfigFile.raw.tstl = {}; @@ -86,7 +86,7 @@ export function updateParsedConfigFile(parsedConfigFile: ts.ParsedCommandLine): } for (const [name, rawValue] of Object.entries(parsedConfigFile.raw.tstl)) { - const option = optionDeclarations.find((option) => option.name === name); + const option = optionDeclarations.find(option => option.name === name); if (!option) { parsedConfigFile.errors.push(cliDiagnostics.unknownCompilerOption(name)); continue; @@ -111,10 +111,10 @@ function updateParsedCommandLine(parsedCommandLine: ts.ParsedCommandLine, args: const isShorthand = !args[i].startsWith("--"); const argumentName = args[i].substr(isShorthand ? 1 : 2); - const option = optionDeclarations.find((option) => { + const option = optionDeclarations.find(option => { if (option.name.toLowerCase() === argumentName.toLowerCase()) return true; if (isShorthand && option.aliases) { - return option.aliases.some((a) => a.toLowerCase() === argumentName.toLowerCase()); + return option.aliases.some(a => a.toLowerCase() === argumentName.toLowerCase()); } return false; @@ -124,7 +124,7 @@ function updateParsedCommandLine(parsedCommandLine: ts.ParsedCommandLine, args: // Ignore errors caused by tstl specific compiler options const tsInvalidCompilerOptionErrorCode = 5023; parsedCommandLine.errors = parsedCommandLine.errors.filter( - (e) => !(e.code === tsInvalidCompilerOptionErrorCode && String(e.messageText).endsWith(`'${args[i]}'.`)) + e => !(e.code === tsInvalidCompilerOptionErrorCode && String(e.messageText).endsWith(`'${args[i]}'.`)) ); const { error, value, increment } = readCommandLineArgument(option, args[i + 1]); @@ -192,7 +192,7 @@ function readValue(option: CommandLineOption, value: unknown): ReadValueResult { }; } - const enumValue = option.choices.find((c) => c.toLowerCase() === value.toLowerCase()); + const enumValue = option.choices.find(c => c.toLowerCase() === value.toLowerCase()); if (enumValue === undefined) { const optionChoices = option.choices.join(", "); return { diff --git a/src/cli/report.ts b/src/cli/report.ts index 5cea5de97..19fd02d1e 100644 --- a/src/cli/report.ts +++ b/src/cli/report.ts @@ -5,5 +5,5 @@ export const prepareDiagnosticForFormatting = (diagnostic: ts.Diagnostic) => export function createDiagnosticReporter(pretty: boolean, system = ts.sys): ts.DiagnosticReporter { const reporter = ts.createDiagnosticReporter(system, pretty); - return (diagnostic) => reporter(prepareDiagnosticForFormatting(diagnostic)); + return diagnostic => reporter(prepareDiagnosticForFormatting(diagnostic)); } diff --git a/src/cli/tsconfig.ts b/src/cli/tsconfig.ts index 07c472334..bec7c2d31 100644 --- a/src/cli/tsconfig.ts +++ b/src/cli/tsconfig.ts @@ -56,7 +56,7 @@ export function createConfigFileUpdater( optionsToExtend: CompilerOptions ): (options: ts.CompilerOptions) => ts.Diagnostic[] { const configFileMap = new WeakMap(); - return (options) => { + return options => { const { configFile, configFilePath } = options; if (!configFile || !configFilePath) return []; diff --git a/src/lualib/StringReplace.ts b/src/lualib/StringReplace.ts index bed78bb9a..7a22992ed 100644 --- a/src/lualib/StringReplace.ts +++ b/src/lualib/StringReplace.ts @@ -14,7 +14,7 @@ function __TS__StringReplace( const [result] = string.gsub( source, searchValue, - (match) => (replaceValue as (substring: string) => string)(match), + match => (replaceValue as (substring: string) => string)(match), 1 ); return result; diff --git a/src/transformation/context/context.ts b/src/transformation/context/context.ts index da412426e..e310a9e19 100644 --- a/src/transformation/context/context.ts +++ b/src/transformation/context/context.ts @@ -54,7 +54,7 @@ export class TransformationContext { public transformNode(node: ts.Node, isExpression?: boolean): lua.Node[]; public transformNode(node: ts.Node, isExpression?: boolean): lua.Node[] { // TODO: Move to visitors? - if (node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword)) { + if (node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DeclareKeyword)) { return []; } @@ -105,10 +105,10 @@ export class TransformationContext { } public transformStatements(node: StatementLikeNode | readonly StatementLikeNode[]): lua.Statement[] { - return castArray(node).flatMap((n) => this.transformNode(n) as lua.Statement[]); + return castArray(node).flatMap(n => this.transformNode(n) as lua.Statement[]); } public superTransformStatements(node: StatementLikeNode | readonly StatementLikeNode[]): lua.Statement[] { - return castArray(node).flatMap((n) => this.superTransformNode(n) as lua.Statement[]); + return castArray(node).flatMap(n => this.superTransformNode(n) as lua.Statement[]); } } diff --git a/src/transformation/utils/annotations.ts b/src/transformation/utils/annotations.ts index c2cb3f890..bd9d052ab 100644 --- a/src/transformation/utils/annotations.ts +++ b/src/transformation/utils/annotations.ts @@ -25,7 +25,7 @@ export interface Annotation { } function createAnnotation(name: string, args: string[]): Annotation | undefined { - const kind = Object.values(AnnotationKind).find((k) => k.toLowerCase() === name.toLowerCase()); + const kind = Object.values(AnnotationKind).find(k => k.toLowerCase() === name.toLowerCase()); if (kind !== undefined) { return { kind, args }; } @@ -78,7 +78,7 @@ export function getFileAnnotations(sourceFile: ts.SourceFile): AnnotationsMap { // Manually collect jsDoc because `getJSDocTags` includes tags only from closest comment const jsDoc = sourceFile.statements[0].jsDoc; if (jsDoc) { - for (const tag of jsDoc.flatMap((x) => x.tags ?? [])) { + for (const tag of jsDoc.flatMap(x => x.tags ?? [])) { const tagName = tag.tagName.text; const annotation = createAnnotation(tagName, tag.comment ? tag.comment.split(" ") : []); if (annotation) { @@ -157,7 +157,7 @@ export function isInTupleReturnFunction(context: TransformationContext, node: ts // Check all overloads for directive const signatures = functionType.getCallSignatures(); - if (signatures?.some((s) => getSignatureAnnotations(context, s).has(AnnotationKind.TupleReturn))) { + if (signatures?.some(s => getSignatureAnnotations(context, s).has(AnnotationKind.TupleReturn))) { return true; } diff --git a/src/transformation/utils/export.ts b/src/transformation/utils/export.ts index b7d334f5d..d11109427 100644 --- a/src/transformation/utils/export.ts +++ b/src/transformation/utils/export.ts @@ -7,7 +7,7 @@ import { getSymbolInfo } from "./symbols"; import { findFirstNodeAbove } from "./typescript"; export function hasDefaultExportModifier(node: ts.Node): boolean { - return (node.modifiers ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword); + return (node.modifiers ?? []).some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword); } export const createDefaultExportIdentifier = (original: ts.Node): lua.Identifier => @@ -19,7 +19,7 @@ export const createDefaultExportStringLiteral = (original: ts.Node): lua.StringL export function getExportedSymbolDeclaration(symbol: ts.Symbol): ts.Declaration | undefined { const declarations = symbol.getDeclarations(); if (declarations) { - return declarations.find((d) => (ts.getCombinedModifierFlags(d) & ts.ModifierFlags.Export) !== 0); + return declarations.find(d => (ts.getCombinedModifierFlags(d) & ts.ModifierFlags.Export) !== 0); } } @@ -94,7 +94,7 @@ export function getExportedSymbolsFromScope( } export function getDependenciesOfSymbol(context: TransformationContext, originalSymbol: ts.Symbol): ts.Symbol[] { - return getExportedSymbolsFromScope(context, context.sourceFile).filter((exportSymbol) => + return getExportedSymbolsFromScope(context, context.sourceFile).filter(exportSymbol => exportSymbol.declarations .filter(ts.isExportSpecifier) .map(context.checker.getExportSpecifierLocalTargetSymbol) diff --git a/src/transformation/utils/function-context.ts b/src/transformation/utils/function-context.ts index 980ccc005..8bf05255c 100644 --- a/src/transformation/utils/function-context.ts +++ b/src/transformation/utils/function-context.ts @@ -30,7 +30,7 @@ function hasNoSelfAncestor(declaration: ts.Declaration): boolean { function getExplicitThisParameter(signatureDeclaration: ts.SignatureDeclaration): ts.ParameterDeclaration | undefined { return signatureDeclaration.parameters.find( - (param) => ts.isIdentifier(param.name) && param.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword + param => ts.isIdentifier(param.name) && param.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword ); } @@ -111,7 +111,7 @@ function getSignatureDeclarations( context: TransformationContext, signatures: readonly ts.Signature[] ): ts.SignatureDeclaration[] { - return signatures.flatMap((signature) => { + return signatures.flatMap(signature => { const signatureDeclaration = signature.getDeclaration(); if ( (ts.isFunctionExpression(signatureDeclaration) || ts.isArrowFunction(signatureDeclaration)) && @@ -122,7 +122,7 @@ function getSignatureDeclarations( if (inferredType) { const inferredSignatures = getAllCallSignatures(inferredType); if (inferredSignatures.length > 0) { - return inferredSignatures.map((s) => s.getDeclaration()); + return inferredSignatures.map(s => s.getDeclaration()); } } } @@ -137,7 +137,7 @@ export function getFunctionContextType(context: TransformationContext, type: ts. } if (type.isUnion()) { - return reduceContextTypes(type.types.map((t) => getFunctionContextType(context, t))); + return reduceContextTypes(type.types.map(t => getFunctionContextType(context, t))); } const signatures = context.checker.getSignaturesOfType(type, ts.SignatureKind.Call); @@ -146,5 +146,5 @@ export function getFunctionContextType(context: TransformationContext, type: ts. } const signatureDeclarations = getSignatureDeclarations(context, signatures); - return reduceContextTypes(signatureDeclarations.map((s) => getDeclarationContextType(context, s))); + return reduceContextTypes(signatureDeclarations.map(s => getDeclarationContextType(context, s))); } diff --git a/src/transformation/utils/lua-ast.ts b/src/transformation/utils/lua-ast.ts index 297aaa0c4..dfce4b2fc 100644 --- a/src/transformation/utils/lua-ast.ts +++ b/src/transformation/utils/lua-ast.ts @@ -65,7 +65,7 @@ export function createUnpackCall( } export function wrapInTable(...expressions: lua.Expression[]): lua.TableExpression { - const fields = expressions.map((e) => lua.createTableFieldExpression(e)); + const fields = expressions.map(e => lua.createTableFieldExpression(e)); return lua.createTableExpression(fields); } @@ -126,7 +126,7 @@ export function createLocalOrExportedOrGlobalDeclaration( return []; } else { assignment = lua.createAssignmentStatement( - identifiers.map((identifier) => createExportedIdentifier(context, identifier, exportScope)), + identifiers.map(identifier => createExportedIdentifier(context, identifier, exportScope)), rhs, tsOriginal ); diff --git a/src/transformation/utils/safe-names.ts b/src/transformation/utils/safe-names.ts index ae4b6d236..c072135f4 100644 --- a/src/transformation/utils/safe-names.ts +++ b/src/transformation/utils/safe-names.ts @@ -72,7 +72,7 @@ export function hasUnsafeSymbolName( symbol: ts.Symbol, tsOriginal: ts.Identifier ): boolean { - const isAmbient = symbol.declarations && symbol.declarations.some((d) => isAmbientNode(d)); + const isAmbient = symbol.declarations && symbol.declarations.some(d => isAmbientNode(d)); // Catch ambient declarations of identifiers with bad names if (isAmbient && checkName(context, symbol.name, tsOriginal)) { @@ -99,6 +99,6 @@ export function hasUnsafeIdentifierName( } const fixInvalidLuaIdentifier = (name: string) => - name.replace(/[^a-zA-Z0-9_]/g, (c) => `_${c.charCodeAt(0).toString(16).toUpperCase()}`); + name.replace(/[^a-zA-Z0-9_]/g, c => `_${c.charCodeAt(0).toString(16).toUpperCase()}`); export const createSafeName = (name: string) => "____" + fixInvalidLuaIdentifier(name); diff --git a/src/transformation/utils/scope.ts b/src/transformation/utils/scope.ts index 94503c34b..2c9f267dd 100644 --- a/src/transformation/utils/scope.ts +++ b/src/transformation/utils/scope.ts @@ -69,7 +69,7 @@ export function peekScope(context: TransformationContext): Scope { } export function findScope(context: TransformationContext, scopeTypes: ScopeType): Scope | undefined { - return [...getScopeStack(context)].reverse().find((s) => scopeTypes & s.type); + return [...getScopeStack(context)].reverse().find(s => scopeTypes & s.type); } const scopeIdCounters = new WeakMap(); @@ -149,8 +149,8 @@ function hoistVariableDeclarations( const result = [...statements]; const hoistedLocals: lua.Identifier[] = []; for (const declaration of scope.variableDeclarations) { - const symbols = declaration.left.map((i) => i.symbolId).filter(isNonNull); - if (symbols.some((s) => shouldHoistSymbol(context, s, scope))) { + const symbols = declaration.left.map(i => i.symbolId).filter(isNonNull); + if (symbols.some(s => shouldHoistSymbol(context, s, scope))) { const index = result.indexOf(declaration); assert(index > -1); diff --git a/src/transformation/utils/typescript/index.ts b/src/transformation/utils/typescript/index.ts index 41fb6c110..394d67656 100644 --- a/src/transformation/utils/typescript/index.ts +++ b/src/transformation/utils/typescript/index.ts @@ -7,7 +7,7 @@ export * from "./types"; // TODO: Move to separate files? export function hasExportEquals(sourceFile: ts.SourceFile): boolean { - return sourceFile.statements.some((node) => ts.isExportAssignment(node) && node.isExportEquals); + return sourceFile.statements.some(node => ts.isExportAssignment(node) && node.isExportEquals); } /** @@ -26,7 +26,7 @@ export function findFirstNodeAbove(node: ts.Node, callback: ( export function getFirstDeclarationInFile(symbol: ts.Symbol, sourceFile: ts.SourceFile): ts.Declaration | undefined { const originalSourceFile = ts.getParseTreeNode(sourceFile) ?? sourceFile; - const declarations = (symbol.getDeclarations() ?? []).filter((d) => d.getSourceFile() === originalSourceFile); + const declarations = (symbol.getDeclarations() ?? []).filter(d => d.getSourceFile() === originalSourceFile); return declarations.length > 0 ? declarations.reduce((p, c) => (p.pos < c.pos ? p : c)) : undefined; } diff --git a/src/transformation/utils/typescript/types.ts b/src/transformation/utils/typescript/types.ts index fab5e7c70..2c6e69dcb 100644 --- a/src/transformation/utils/typescript/types.ts +++ b/src/transformation/utils/typescript/types.ts @@ -25,11 +25,11 @@ export function typeAlwaysSatisfies( } if (type.isUnion()) { - return type.types.every((t) => typeAlwaysSatisfies(context, t, predicate)); + return type.types.every(t => typeAlwaysSatisfies(context, t, predicate)); } if (type.isIntersection()) { - return type.types.some((t) => typeAlwaysSatisfies(context, t, predicate)); + return type.types.some(t => typeAlwaysSatisfies(context, t, predicate)); } return false; @@ -45,11 +45,11 @@ export function typeCanSatisfy( } if (type.isUnion()) { - return type.types.some((t) => typeCanSatisfy(context, t, predicate)); + return type.types.some(t => typeCanSatisfy(context, t, predicate)); } if (type.isIntersection()) { - return type.types.some((t) => typeCanSatisfy(context, t, predicate)); + return type.types.some(t => typeCanSatisfy(context, t, predicate)); } return false; @@ -72,7 +72,7 @@ function isExplicitArrayType(context: TransformationContext, type: ts.Type): boo } if (type.isUnionOrIntersection()) { - return type.types.some((t) => isExplicitArrayType(context, t)); + return type.types.some(t => isExplicitArrayType(context, t)); } const flags = ts.NodeBuilderFlags.InTypeAlias | ts.NodeBuilderFlags.AllowEmptyTuple; @@ -100,11 +100,11 @@ export function forTypeOrAnySupertype( type = context.checker.getDeclaredTypeOfSymbol(type.symbol); } - return (type.getBaseTypes() ?? []).some((superType) => forTypeOrAnySupertype(context, superType, predicate)); + return (type.getBaseTypes() ?? []).some(superType => forTypeOrAnySupertype(context, superType, predicate)); } export function isArrayType(context: TransformationContext, type: ts.Type): boolean { - return forTypeOrAnySupertype(context, type, (t) => isExplicitArrayType(context, t)); + return forTypeOrAnySupertype(context, type, t => isExplicitArrayType(context, t)); } export function isFunctionType(context: TransformationContext, type: ts.Type): boolean { diff --git a/src/transformation/visitors/binary-expression/assignments.ts b/src/transformation/visitors/binary-expression/assignments.ts index ed46ae1e1..94e17e9c7 100644 --- a/src/transformation/visitors/binary-expression/assignments.ts +++ b/src/transformation/visitors/binary-expression/assignments.ts @@ -59,7 +59,7 @@ export function transformAssignment( return [ rootAssignment, - ...dependentSymbols.map((symbol) => { + ...dependentSymbols.map(symbol => { const [left] = rootAssignment.left; const identifierToAssign = createExportedIdentifier(context, lua.createIdentifier(symbol.name)); return lua.createAssignmentStatement(identifierToAssign, left); @@ -152,7 +152,7 @@ const canBeTransformedToLuaAssignmentStatement = ( node: ts.DestructuringAssignment ): node is ts.ArrayDestructuringAssignment => ts.isArrayLiteralExpression(node.left) && - node.left.elements.every((element) => { + node.left.elements.every(element => { if (isArrayLength(context, element)) { return false; } @@ -188,7 +188,7 @@ export function transformAssignmentStatement( right = createUnpackCall(context, right, expression.right); } - const left = expression.left.elements.map((e) => transformAssignmentLeftHandSideExpression(context, e)); + const left = expression.left.elements.map(e => transformAssignmentLeftHandSideExpression(context, e)); return [lua.createAssignmentStatement(left, right, expression)]; } diff --git a/src/transformation/visitors/call.ts b/src/transformation/visitors/call.ts index 8c4ed418e..366ff8041 100644 --- a/src/transformation/visitors/call.ts +++ b/src/transformation/visitors/call.ts @@ -49,7 +49,7 @@ function transformSpreadableExpressionsIntoArrayConcatArguments( } } - return chunks.map((chunk) => wrapInTable(...chunk.map((expression) => context.transformExpression(expression)))); + return chunks.map(chunk => wrapInTable(...chunk.map(expression => context.transformExpression(expression)))); } export function flattenSpreadExpressions( @@ -57,7 +57,7 @@ export function flattenSpreadExpressions( expressions: readonly ts.Expression[] ): lua.Expression[] { const [preSpreadExpressions, postSpreadExpressions] = getExpressionsBeforeAndAfterFirstSpread(expressions); - const transformedPreSpreadExpressions = preSpreadExpressions.map((a) => context.transformExpression(a)); + const transformedPreSpreadExpressions = preSpreadExpressions.map(a => context.transformExpression(a)); // Nothing special required if (postSpreadExpressions.length === 0) { diff --git a/src/transformation/visitors/class/decorators.ts b/src/transformation/visitors/class/decorators.ts index 2bc662b08..5cae0cf17 100644 --- a/src/transformation/visitors/class/decorators.ts +++ b/src/transformation/visitors/class/decorators.ts @@ -21,7 +21,7 @@ export function createConstructorDecorationStatement( return undefined; } - const decoratorExpressions = decorators.map((decorator) => { + const decoratorExpressions = decorators.map(decorator => { const expression = decorator.expression; const type = context.checker.getTypeAtLocation(expression); const callContext = getFunctionContextType(context, type); @@ -33,7 +33,7 @@ export function createConstructorDecorationStatement( }); const decoratorTable = lua.createTableExpression( - decoratorExpressions.map((expression) => lua.createTableFieldExpression(expression)) + decoratorExpressions.map(expression => lua.createTableFieldExpression(expression)) ); return lua.createAssignmentStatement( diff --git a/src/transformation/visitors/class/index.ts b/src/transformation/visitors/class/index.ts index c2c01a4fe..59ecc10b7 100644 --- a/src/transformation/visitors/class/index.ts +++ b/src/transformation/visitors/class/index.ts @@ -49,7 +49,7 @@ export const transformClassDeclaration: FunctionVisitor return statements; }; -export const transformThisExpression: FunctionVisitor = (node) => createSelfIdentifier(node); +export const transformThisExpression: FunctionVisitor = node => createSelfIdentifier(node); export function transformClassAsExpression( expression: ts.ClassLikeDeclaration, @@ -131,11 +131,11 @@ function transformClassLikeDeclaration( } // Get all properties with value - const properties = classDeclaration.members.filter(ts.isPropertyDeclaration).filter((member) => member.initializer); + const properties = classDeclaration.members.filter(ts.isPropertyDeclaration).filter(member => member.initializer); // Divide properties into static and non-static const staticFields = properties.filter(isStaticNode); - const instanceFields = properties.filter((prop) => !isStaticNode(prop)); + const instanceFields = properties.filter(prop => !isStaticNode(prop)); const result: lua.Statement[] = []; @@ -237,7 +237,7 @@ function transformClassLikeDeclaration( if (constructorResult) result.push(constructorResult); } else if ( instanceFields.length > 0 || - classDeclaration.members.some((m) => isGetAccessorOverride(context, m, classDeclaration)) + classDeclaration.members.some(m => isGetAccessorOverride(context, m, classDeclaration)) ) { // Generate a constructor if none was defined in a class with instance fields that need initialization // localClassName.prototype.____constructor = function(self, ...) @@ -286,7 +286,7 @@ function transformClassLikeDeclaration( result.push( ...classDeclaration.members .filter(ts.isMethodDeclaration) - .map((m) => transformMethodDeclaration(context, m, localClassName, isExtension || isMetaExtension)) + .map(m => transformMethodDeclaration(context, m, localClassName, isExtension || isMetaExtension)) .filter(isNonNull) ); diff --git a/src/transformation/visitors/class/members/accessors.ts b/src/transformation/visitors/class/members/accessors.ts index 508fc87f0..88a7f1545 100644 --- a/src/transformation/visitors/class/members/accessors.ts +++ b/src/transformation/visitors/class/members/accessors.ts @@ -80,7 +80,7 @@ export const hasMemberInClassOrAncestor = ( context: TransformationContext, classDeclaration: ts.ClassLikeDeclarationBase, callback: (m: ts.ClassElement) => boolean -) => [...classWithAncestors(context, classDeclaration)].some((c) => c.members.some(callback)); +) => [...classWithAncestors(context, classDeclaration)].some(c => c.members.some(callback)); function getPropertyName(propertyName: ts.PropertyName): string | number | undefined { if (ts.isIdentifier(propertyName) || ts.isStringLiteral(propertyName) || ts.isNumericLiteral(propertyName)) { @@ -108,6 +108,6 @@ export function isGetAccessorOverride( return hasMemberInClassOrAncestor( context, classDeclaration, - (m) => ts.isPropertyDeclaration(m) && m.initializer !== undefined && isSamePropertyName(m.name, element.name) + m => ts.isPropertyDeclaration(m) && m.initializer !== undefined && isSamePropertyName(m.name, element.name) ); } diff --git a/src/transformation/visitors/class/members/constructor.ts b/src/transformation/visitors/class/members/constructor.ts index ebbb289d1..fe25a21b2 100644 --- a/src/transformation/visitors/class/members/constructor.ts +++ b/src/transformation/visitors/class/members/constructor.ts @@ -40,7 +40,7 @@ export function transformConstructorDeclaration( const bodyWithFieldInitializers = transformFunctionBodyHeader(context, scope, statement.parameters, restParamName); // Check for field declarations in constructor - const constructorFieldsDeclarations = statement.parameters.filter((p) => p.modifiers !== undefined); + const constructorFieldsDeclarations = statement.parameters.filter(p => p.modifiers !== undefined); const classInstanceFields = transformClassInstanceFields(context, classDeclaration, instanceFields); diff --git a/src/transformation/visitors/class/utils.ts b/src/transformation/visitors/class/utils.ts index f383d3cc1..9ba263818 100644 --- a/src/transformation/visitors/class/utils.ts +++ b/src/transformation/visitors/class/utils.ts @@ -3,11 +3,11 @@ import { TransformationContext } from "../../context"; import { AnnotationKind, getTypeAnnotations } from "../../utils/annotations"; export function isStaticNode(node: ts.Node): boolean { - return (node.modifiers ?? []).some((m) => m.kind === ts.SyntaxKind.StaticKeyword); + return (node.modifiers ?? []).some(m => m.kind === ts.SyntaxKind.StaticKeyword); } export function getExtendsClause(node: ts.ClassLikeDeclarationBase): ts.HeritageClause | undefined { - return (node.heritageClauses ?? []).find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword); + return (node.heritageClauses ?? []).find(clause => clause.token === ts.SyntaxKind.ExtendsKeyword); } export function getExtendedNode( diff --git a/src/transformation/visitors/conditional.ts b/src/transformation/visitors/conditional.ts index ebecc32bd..2fab7494c 100644 --- a/src/transformation/visitors/conditional.ts +++ b/src/transformation/visitors/conditional.ts @@ -21,7 +21,7 @@ function canBeFalsy(context: TransformationContext, type: ts.Type): boolean { } else if (!strictNullChecks && !type.isLiteral()) { return true; } else if (type.isUnion()) { - return type.types.some((subType) => canBeFalsy(context, subType)); + return type.types.some(subType => canBeFalsy(context, subType)); } else { return false; } diff --git a/src/transformation/visitors/function.ts b/src/transformation/visitors/function.ts index f873e6f90..7c82a89be 100644 --- a/src/transformation/visitors/function.ts +++ b/src/transformation/visitors/function.ts @@ -48,7 +48,7 @@ function isRestParameterReferenced(context: TransformationContext, identifier: l return false; } // Ignore references to @vararg types in spread elements - return references.some((r) => !r.parent || !ts.isSpreadElement(r.parent) || !isVarargType(context, r)); + return references.some(r => !r.parent || !ts.isSpreadElement(r.parent) || !isVarargType(context, r)); } export function transformFunctionBodyStatements(context: TransformationContext, body: ts.Block): lua.Statement[] { @@ -215,7 +215,7 @@ export function transformFunctionLikeDeclaration( if (symbol) { // TODO: Not using symbol ids because of https://github.com/microsoft/TypeScript/issues/37131 const isReferenced = [...scope.referencedSymbols].some(([, nodes]) => - nodes.some((n) => context.checker.getSymbolAtLocation(n)?.valueDeclaration === symbol.valueDeclaration) + nodes.some(n => context.checker.getSymbolAtLocation(n)?.valueDeclaration === symbol.valueDeclaration) ); // Only wrap if the name is actually referenced inside the function diff --git a/src/transformation/visitors/literal.ts b/src/transformation/visitors/literal.ts index 1e48f12dd..6544367a2 100644 --- a/src/transformation/visitors/literal.ts +++ b/src/transformation/visitors/literal.ts @@ -51,7 +51,7 @@ export function createShorthandIdentifier( return identifier; } -const transformNumericLiteralExpression: FunctionVisitor = (expression) => { +const transformNumericLiteralExpression: FunctionVisitor = expression => { if (expression.text === "Infinity") { const math = lua.createIdentifier("math"); const huge = lua.createStringLiteral("huge"); @@ -129,21 +129,21 @@ const transformObjectLiteralExpression: FunctionVisitor = (expression, context) => { - const filteredElements = expression.elements.map((e) => + const filteredElements = expression.elements.map(e => ts.isOmittedExpression(e) ? ts.createIdentifier("undefined") : e ); - const values = flattenSpreadExpressions(context, filteredElements).map((e) => lua.createTableFieldExpression(e)); + const values = flattenSpreadExpressions(context, filteredElements).map(e => lua.createTableFieldExpression(e)); return lua.createTableExpression(values, expression); }; export const literalVisitors: Visitors = { - [ts.SyntaxKind.NullKeyword]: (node) => lua.createNilLiteral(node), - [ts.SyntaxKind.TrueKeyword]: (node) => lua.createBooleanLiteral(true, node), - [ts.SyntaxKind.FalseKeyword]: (node) => lua.createBooleanLiteral(false, node), + [ts.SyntaxKind.NullKeyword]: node => lua.createNilLiteral(node), + [ts.SyntaxKind.TrueKeyword]: node => lua.createBooleanLiteral(true, node), + [ts.SyntaxKind.FalseKeyword]: node => lua.createBooleanLiteral(false, node), [ts.SyntaxKind.NumericLiteral]: transformNumericLiteralExpression, - [ts.SyntaxKind.StringLiteral]: (node) => lua.createStringLiteral(node.text, node), - [ts.SyntaxKind.NoSubstitutionTemplateLiteral]: (node) => lua.createStringLiteral(node.text, node), + [ts.SyntaxKind.StringLiteral]: node => lua.createStringLiteral(node.text, node), + [ts.SyntaxKind.NoSubstitutionTemplateLiteral]: node => lua.createStringLiteral(node.text, node), [ts.SyntaxKind.ObjectLiteralExpression]: transformObjectLiteralExpression, [ts.SyntaxKind.ArrayLiteralExpression]: transformArrayLiteralExpression, }; diff --git a/src/transformation/visitors/loops/for-of.ts b/src/transformation/visitors/loops/for-of.ts index 6cb5aae14..44656088a 100644 --- a/src/transformation/visitors/loops/for-of.ts +++ b/src/transformation/visitors/loops/for-of.ts @@ -25,7 +25,7 @@ function transformForRangeStatement( ); } - if (statement.expression.arguments.some((a) => !isNumberType(context, context.checker.getTypeAtLocation(a)))) { + if (statement.expression.arguments.some(a => !isNumberType(context, context.checker.getTypeAtLocation(a)))) { context.diagnostics.push(invalidForRangeCall(statement.expression, "arguments must be numbers")); } @@ -81,7 +81,7 @@ function transformForOfLuaIteratorStatement( const binding = getVariableDeclarationBinding(context, statement.initializer); if (ts.isArrayBindingPattern(binding)) { - identifiers = binding.elements.map((e) => transformArrayBindingElement(context, e)); + identifiers = binding.elements.map(e => transformArrayBindingElement(context, e)); } else { context.diagnostics.push(luaIteratorForbiddenUsage(binding)); } @@ -94,7 +94,7 @@ function transformForOfLuaIteratorStatement( if (identifiers.length > 0) { block.statements.unshift( lua.createAssignmentStatement( - statement.initializer.elements.map((e) => + statement.initializer.elements.map(e => cast(context.transformExpression(e), lua.isAssignmentLeftHandSideExpression) ), identifiers diff --git a/src/transformation/visitors/loops/for.ts b/src/transformation/visitors/loops/for.ts index bc2375654..f81a62199 100644 --- a/src/transformation/visitors/loops/for.ts +++ b/src/transformation/visitors/loops/for.ts @@ -11,7 +11,7 @@ export const transformForStatement: FunctionVisitor = (statemen if (ts.isVariableDeclarationList(statement.initializer)) { checkVariableDeclarationList(context, statement.initializer); // local initializer = value - result.push(...statement.initializer.declarations.flatMap((d) => transformVariableDeclaration(context, d))); + result.push(...statement.initializer.declarations.flatMap(d => transformVariableDeclaration(context, d))); } else { result.push(...context.transformStatements(ts.createExpressionStatement(statement.initializer))); } diff --git a/src/transformation/visitors/modules/export.ts b/src/transformation/visitors/modules/export.ts index a7af1997f..5e12c6c5e 100644 --- a/src/transformation/visitors/modules/export.ts +++ b/src/transformation/visitors/modules/export.ts @@ -93,7 +93,7 @@ function transformExportSpecifiersFrom( // First transpile as import clause const importClause = ts.createImportClause( undefined, - ts.createNamedImports(exportSpecifiers.map((s) => ts.createImportSpecifier(s.propertyName, s.name))) + ts.createNamedImports(exportSpecifiers.map(s => ts.createImportSpecifier(s.propertyName, s.name))) ); const importDeclaration = ts.createImportDeclaration( @@ -122,7 +122,7 @@ function transformExportSpecifiersFrom( } export const getExported = (context: TransformationContext, exportSpecifiers: ts.NamedExports) => - exportSpecifiers.elements.filter((exportSpecifier) => context.resolver.isValueAliasDeclaration(exportSpecifier)); + exportSpecifiers.elements.filter(exportSpecifier => context.resolver.isValueAliasDeclaration(exportSpecifier)); export const transformExportDeclaration: FunctionVisitor = (node, context) => { if (!node.exportClause) { @@ -143,7 +143,7 @@ export const transformExportDeclaration: FunctionVisitor = // export { ... }; if (!node.moduleSpecifier) { - return exportSpecifiers.map((exportSpecifier) => transformExportSpecifier(context, exportSpecifier)); + return exportSpecifiers.map(exportSpecifier => transformExportSpecifier(context, exportSpecifier)); } // export { ... } from "..."; diff --git a/src/transformation/visitors/modules/import.ts b/src/transformation/visitors/modules/import.ts index 1214d0091..34fa216d6 100644 --- a/src/transformation/visitors/modules/import.ts +++ b/src/transformation/visitors/modules/import.ts @@ -156,8 +156,8 @@ export const transformImportDeclaration: FunctionVisitor = // local c = __module.c if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) { const assignmentStatements = statement.importClause.namedBindings.elements - .filter((importSpecifier) => shouldBeImported(context, importSpecifier)) - .map((importSpecifier) => transformImportSpecifier(context, importSpecifier, importUniqueName)); + .filter(importSpecifier => shouldBeImported(context, importSpecifier)) + .map(importSpecifier => transformImportSpecifier(context, importSpecifier, importUniqueName)); if (assignmentStatements.length > 0) { usingRequireStatement = true; diff --git a/src/transformation/visitors/namespace.ts b/src/transformation/visitors/namespace.ts index 97924a51c..35190705f 100644 --- a/src/transformation/visitors/namespace.ts +++ b/src/transformation/visitors/namespace.ts @@ -37,7 +37,7 @@ function moduleHasEmittedBody( if (node.body) { if (ts.isModuleBlock(node.body)) { // Ignore if body has no emitted statements - return node.body.statements.some((s) => !ts.isInterfaceDeclaration(s) && !ts.isTypeAliasDeclaration(s)); + return node.body.statements.some(s => !ts.isInterfaceDeclaration(s) && !ts.isTypeAliasDeclaration(s)); } else if (ts.isModuleDeclaration(node.body)) { return true; } @@ -74,7 +74,7 @@ export const transformModuleDeclaration: FunctionVisitor = // - declared as a class or function at all (TS requires these to be before module, unless module is empty) const isFirstDeclaration = symbol === undefined || - (!symbol.declarations.some((d) => ts.isClassLike(d) || ts.isFunctionDeclaration(d)) && + (!symbol.declarations.some(d => ts.isClassLike(d) || ts.isFunctionDeclaration(d)) && node === symbol.declarations.find(ts.isModuleDeclaration)); if (isNonModuleMergeable) { diff --git a/src/transformation/visitors/return.ts b/src/transformation/visitors/return.ts index 5bc4e23ab..970db6be0 100644 --- a/src/transformation/visitors/return.ts +++ b/src/transformation/visitors/return.ts @@ -33,7 +33,7 @@ export const transformReturnStatement: FunctionVisitor = (st // Parent function is a TupleReturn function if (ts.isArrayLiteralExpression(statement.expression)) { // If return expression is an array literal, leave out brackets. - results = statement.expression.elements.map((e) => context.transformExpression(e)); + results = statement.expression.elements.map(e => context.transformExpression(e)); } else if (!isTupleReturnCall(context, statement.expression) && isArrayType(context, expressionType)) { // If return expression is an array-type and not another TupleReturn call, unpack it results = [ diff --git a/src/transformation/visitors/template.ts b/src/transformation/visitors/template.ts index 004906ad0..784cf7e4e 100644 --- a/src/transformation/visitors/template.ts +++ b/src/transformation/visitors/template.ts @@ -48,9 +48,9 @@ export const transformTaggedTemplateExpression: FunctionVisitor span.literal.text)); - rawStrings.push(...expression.template.templateSpans.map((span) => getRawLiteral(span.literal))); - expressions.push(...expression.template.templateSpans.map((span) => span.expression)); + strings.push(...expression.template.templateSpans.map(span => span.literal.text)); + rawStrings.push(...expression.template.templateSpans.map(span => getRawLiteral(span.literal))); + expressions.push(...expression.template.templateSpans.map(span => span.expression)); } else { // No expressions are in the string. strings.push(expression.template.text); @@ -60,11 +60,11 @@ export const transformTaggedTemplateExpression: FunctionVisitor lua.createTableFieldExpression(lua.createStringLiteral(text))) + rawStrings.map(text => lua.createTableFieldExpression(lua.createStringLiteral(text))) ); const stringTableLiteral = lua.createTableExpression([ - ...strings.map((partialString) => lua.createTableFieldExpression(lua.createStringLiteral(partialString))), + ...strings.map(partialString => lua.createTableFieldExpression(lua.createStringLiteral(partialString))), lua.createTableFieldExpression(rawStringsTable, lua.createStringLiteral("raw")), ]); diff --git a/src/transformation/visitors/variable-declaration.ts b/src/transformation/visitors/variable-declaration.ts index 99a833fab..12ffeb763 100644 --- a/src/transformation/visitors/variable-declaration.ts +++ b/src/transformation/visitors/variable-declaration.ts @@ -75,7 +75,7 @@ export function transformBindingPattern( if (isObjectBindingPattern) { const elements = pattern.elements as ts.NodeArray; - const usedProperties = elements.map((e) => + const usedProperties = elements.map(e => lua.createTableFieldExpression( lua.createBooleanLiteral(true), lua.createStringLiteral( @@ -156,7 +156,7 @@ export function transformBindingVariableDeclaration( const vars = bindingPattern.elements.length > 0 - ? bindingPattern.elements.map((e) => transformArrayBindingElement(context, e)) + ? bindingPattern.elements.map(e => transformArrayBindingElement(context, e)) : lua.createAnonymousIdentifier(); if (initializer) { @@ -174,7 +174,7 @@ export function transformBindingVariableDeclaration( // Don't unpack array literals const values = initializer.elements.length > 0 - ? initializer.elements.map((e) => context.transformExpression(e)) + ? initializer.elements.map(e => context.transformExpression(e)) : lua.createNilLiteral(); statements.push(...createLocalOrExportedOrGlobalDeclaration(context, vars, values, initializer)); } else { @@ -245,7 +245,5 @@ export function checkVariableDeclarationList(context: TransformationContext, nod export const transformVariableStatement: FunctionVisitor = (node, context) => { checkVariableDeclarationList(context, node.declarationList); - return node.declarationList.declarations.flatMap((declaration) => - transformVariableDeclaration(context, declaration) - ); + return node.declarationList.declarations.flatMap(declaration => transformVariableDeclaration(context, declaration)); }; diff --git a/src/transpilation/bundle.ts b/src/transpilation/bundle.ts index b4fe8d26f..2acda7399 100644 --- a/src/transpilation/bundle.ts +++ b/src/transpilation/bundle.ts @@ -32,17 +32,17 @@ export function bundleTranspiledFiles( // Resolve source files relative to common source directory. const sourceRootDir = program.getCommonSourceDirectory(); - if (!transpiledFiles.some((f) => path.resolve(sourceRootDir, f.fileName) === resolvedEntryModule)) { + if (!transpiledFiles.some(f => path.resolve(sourceRootDir, f.fileName) === resolvedEntryModule)) { return [[diagnosticFactories.couldNotFindBundleEntryPoint(entryModule)], { fileName: bundleFile }]; } // For each file: [""] = function() end, - const moduleTableEntries: SourceChunk[] = transpiledFiles.map((f) => + const moduleTableEntries: SourceChunk[] = transpiledFiles.map(f => moduleSourceNode(f, createModulePath(sourceRootDir, f.fileName)) ); // If any of the modules contains a require for lualib_bundle, add it to the module table. - const lualibRequired = transpiledFiles.some((f) => f.lua?.includes('require("lualib_bundle")')); + const lualibRequired = transpiledFiles.some(f => f.lua?.includes('require("lualib_bundle")')); if (lualibRequired) { moduleTableEntries.push(`["lualib_bundle"] = function() ${getLuaLibBundle(emitHost)} end,\n`); } diff --git a/src/transpilation/emit.ts b/src/transpilation/emit.ts index 1229ff672..854f0cc7e 100644 --- a/src/transpilation/emit.ts +++ b/src/transpilation/emit.ts @@ -54,7 +54,7 @@ export function emitTranspiledFiles( luaLibImport === LuaLibImportKind.Require || luaLibImport === LuaLibImportKind.Always) ) { - const lualibRequired = files.some((f) => f.text?.includes('require("lualib_bundle")')); + const lualibRequired = files.some(f => f.text?.includes('require("lualib_bundle")')); if (lualibRequired) { let outPath = path.resolve(rootDir, "lualib_bundle.lua"); if (outDir !== rootDir) { diff --git a/src/transpilation/index.ts b/src/transpilation/index.ts index 363cce8fa..76c0e9634 100644 --- a/src/transpilation/index.ts +++ b/src/transpilation/index.ts @@ -43,7 +43,7 @@ const libCache: { [key: string]: ts.SourceFile } = {}; export function createVirtualProgram(input: Record, options: CompilerOptions = {}): ts.Program { const compilerHost: ts.CompilerHost = { fileExists: () => true, - getCanonicalFileName: (fileName) => fileName, + getCanonicalFileName: fileName => fileName, getCurrentDirectory: () => "", getDefaultLibFileName: ts.getDefaultLibFileName, readFile: () => "", diff --git a/src/transpilation/transformers.ts b/src/transpilation/transformers.ts index 54cad3f5c..cefb4dd90 100644 --- a/src/transpilation/transformers.ts +++ b/src/transpilation/transformers.ts @@ -5,8 +5,8 @@ import { CompilerOptions, TransformerImport } from "../CompilerOptions"; import * as diagnosticFactories from "./diagnostics"; import { getConfigDirectory, resolvePlugin } from "./utils"; -export const noImplicitSelfTransformer: ts.TransformerFactory = () => (node) => { - const transformSourceFile: ts.Transformer = (node) => { +export const noImplicitSelfTransformer: ts.TransformerFactory = () => node => { + const transformSourceFile: ts.Transformer = node => { const empty = ts.createNotEmittedStatement(undefined!); ts.addSyntheticLeadingComment(empty, ts.SyntaxKind.MultiLineCommentTrivia, "* @noSelfInFile ", true); return ts.updateSourceFileNode(node, [empty, ...node.statements], node.isDeclarationFile); @@ -23,7 +23,7 @@ export function getTransformers( customTransformers: ts.CustomTransformers, onSourceFile: (sourceFile: ts.SourceFile) => void ): ts.CustomTransformers { - const luaTransformer: ts.TransformerFactory = () => (sourceFile) => { + const luaTransformer: ts.TransformerFactory = () => sourceFile => { onSourceFile(sourceFile); return ts.createSourceFile(sourceFile.fileName, "", ts.ScriptTarget.ESNext); }; diff --git a/src/transpilation/transpile.ts b/src/transpilation/transpile.ts index 2f9e95f14..d024e8a09 100644 --- a/src/transpilation/transpile.ts +++ b/src/transpilation/transpile.ts @@ -51,7 +51,7 @@ export function transpile({ let transpiledFiles: TranspiledFile[] = []; const updateTranspiledFile = (fileName: string, update: Omit) => { - const file = transpiledFiles.find((f) => f.fileName === fileName); + const file = transpiledFiles.find(f => f.fileName === fileName); if (file) { Object.assign(file, update); } else { @@ -86,8 +86,8 @@ export function transpile({ } const plugins = getPlugins(program, diagnostics, customPlugins); - const visitorMap = createVisitorMap(plugins.map((p) => p.visitors).filter(isNonNull)); - const printer = createPrinter(plugins.map((p) => p.printer).filter(isNonNull)); + const visitorMap = createVisitorMap(plugins.map(p => p.visitors).filter(isNonNull)); + const printer = createPrinter(plugins.map(p => p.printer).filter(isNonNull)); const processSourceFile = (sourceFile: ts.SourceFile) => { const { luaAst, luaLibFeatures, diagnostics: transformDiagnostics } = transformSourceFile( program, diff --git a/src/tstl.ts b/src/tstl.ts index 9dc4665f0..aab3feff2 100644 --- a/src/tstl.ts +++ b/src/tstl.ts @@ -36,7 +36,7 @@ function executeCommandLine(args: string[]): void { // TODO: ParsedCommandLine.errors isn't meant to contain warnings. Once root-level options // support would be dropped it should be changed to `commandLine.errors.length > 0`. - if (commandLine.errors.some((e) => e.category === ts.DiagnosticCategory.Error)) { + if (commandLine.errors.some(e => e.category === ts.DiagnosticCategory.Error)) { commandLine.errors.forEach(reportDiagnostic); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } @@ -157,7 +157,7 @@ function updateWatchCompilationHost( let fullRecompile = true; const updateConfigFile = createConfigFileUpdater(optionsToExtend); - host.afterProgramCreate = (builderProgram) => { + host.afterProgramCreate = builderProgram => { const program = builderProgram.getProgram(); const options = builderProgram.getCompilerOptions() as tstl.CompilerOptions; const configFileParsingDiagnostics: ts.Diagnostic[] = updateConfigFile(options); @@ -193,7 +193,7 @@ function updateWatchCompilationHost( diagnostics.forEach(reportDiagnostic); - const errors = diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); + const errors = diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error); // do a full recompile after an error fullRecompile = errors.length > 0; diff --git a/test/cli/parse.spec.ts b/test/cli/parse.spec.ts index 9765a3148..3ce9b35ba 100644 --- a/test/cli/parse.spec.ts +++ b/test/cli/parse.spec.ts @@ -59,7 +59,7 @@ describe("command line", () => { }); describe("boolean options", () => { - test.each([true, false])("should parse booleans (%p)", (value) => { + test.each([true, false])("should parse booleans (%p)", value => { const result = tstl.parseCommandLine(["--noHeader", value.toString()]); expect(result.errors).not.toHaveDiagnostics(); @@ -188,7 +188,7 @@ describe("tsconfig", () => { }); describe("boolean options", () => { - test.each([true, false])("should parse booleans (%p)", (value) => { + test.each([true, false])("should parse booleans (%p)", value => { const result = parseConfigFileContent({ tstl: { noHeader: value } }); expect(result.errors).not.toHaveDiagnostics(); diff --git a/test/cli/run.ts b/test/cli/run.ts index 07fe95b02..cee7e19b2 100644 --- a/test/cli/run.ts +++ b/test/cli/run.ts @@ -25,7 +25,7 @@ export async function runCli(args: string[]): Promise { child.stdout!.on("data", (data: Buffer) => (output += data.toString())); child.stderr!.on("data", (data: Buffer) => (output += data.toString())); - return new Promise((resolve) => { - child.on("close", (exitCode) => resolve({ exitCode, output })); + return new Promise(resolve => { + child.on("close", exitCode => resolve({ exitCode, output })); }); } diff --git a/test/cli/watch.spec.ts b/test/cli/watch.spec.ts index 69ded3f84..35d2f2f59 100644 --- a/test/cli/watch.spec.ts +++ b/test/cli/watch.spec.ts @@ -4,12 +4,12 @@ import { forkCli } from "./run"; let testsCleanup: Array<() => void> = []; afterEach(() => { - testsCleanup.forEach((x) => x()); + testsCleanup.forEach(x => x()); testsCleanup = []; }); async function waitForFileExists(filePath: string): Promise { - return new Promise((resolve) => { + return new Promise(resolve => { const intervalTimerId = setInterval(() => { if (fs.existsSync(filePath)) { clearInterval(intervalTimerId); diff --git a/test/legacy-utils.ts b/test/legacy-utils.ts index a7de90b0e..685b90544 100644 --- a/test/legacy-utils.ts +++ b/test/legacy-utils.ts @@ -13,7 +13,7 @@ export function transpileString( const { diagnostics, file } = transpileStringResult(str, options); expect(file.lua).toBeDefined(); - const errors = diagnostics.filter((d) => !ignoreDiagnostics || d.source === "typescript-to-lua"); + const errors = diagnostics.filter(d => !ignoreDiagnostics || d.source === "typescript-to-lua"); expect(errors).not.toHaveDiagnostics(); return file.lua!.trim(); @@ -83,7 +83,7 @@ export function executeLua(luaStr: string, withLib = true): any { // Throw a JS error with the message, retrieved by reading a string from the stack. // Filter control characters out of string which are in there because ???? - throw new Error("LUA ERROR: " + to_jsstring(lua.lua_tostring(L, -1).filter((c) => c >= 20))); + throw new Error("LUA ERROR: " + to_jsstring(lua.lua_tostring(L, -1).filter(c => c >= 20))); } } @@ -117,14 +117,14 @@ export function transpileAndExecuteProjectReturningMainExport( exportName: string, options: tstl.CompilerOptions = {} ): [any, string] { - const mainFile = Object.keys(typeScriptFiles).find((typeScriptFileName) => typeScriptFileName === "main.ts"); + const mainFile = Object.keys(typeScriptFiles).find(typeScriptFileName => typeScriptFileName === "main.ts"); if (!mainFile) { throw new Error("An entry point file needs to be specified. This should be called main.ts"); } const joinedTranspiledFiles = Object.keys(typeScriptFiles) - .filter((typeScriptFileName) => typeScriptFileName !== "main.ts") - .map((typeScriptFileName) => { + .filter(typeScriptFileName => typeScriptFileName !== "main.ts") + .map(typeScriptFileName => { const modulePath = getExportPath(typeScriptFileName, options); const tsCode = typeScriptFiles[typeScriptFileName]; const luaCode = transpileString(tsCode, options); diff --git a/test/setup.ts b/test/setup.ts index f9b2e426b..6d92e3332 100644 --- a/test/setup.ts +++ b/test/setup.ts @@ -20,7 +20,7 @@ expect.extend({ const diagnosticMessages = ts.formatDiagnosticsWithColorAndContext( diagnostics.map(tstl.prepareDiagnosticForFormatting), - { getCurrentDirectory: () => "", getCanonicalFileName: (fileName) => fileName, getNewLine: () => "\n" } + { getCurrentDirectory: () => "", getCanonicalFileName: fileName => fileName, getNewLine: () => "\n" } ); if (this.isNot && expected !== undefined) { @@ -37,9 +37,7 @@ expect.extend({ const message = this.isNot ? diagnosticMessages : expected - ? `Expected:\n${expected.join("\n")}\nReceived:\n${diagnostics - .map((diag) => diag.code) - .join("\n")}\n` + ? `Expected:\n${expected.join("\n")}\nReceived:\n${diagnostics.map(diag => diag.code).join("\n")}\n` : `Received: ${this.utils.printReceived([])}\n`; return matcherHint + "\n\n" + message; diff --git a/test/translation/transformation.spec.ts b/test/translation/transformation.spec.ts index 4a6536bc3..7a5088fcb 100644 --- a/test/translation/transformation.spec.ts +++ b/test/translation/transformation.spec.ts @@ -6,9 +6,9 @@ import * as util from "../util"; const fixturesPath = path.join(__dirname, "./transformation"); const fixtures = fs .readdirSync(fixturesPath) - .filter((f) => path.extname(f) === ".ts") + .filter(f => path.extname(f) === ".ts") .sort() - .map((f) => [path.parse(f).name, fs.readFileSync(path.join(fixturesPath, f), "utf8")]); + .map(f => [path.parse(f).name, fs.readFileSync(path.join(fixturesPath, f), "utf8")]); test.each(fixtures)("Transformation (%s)", (_name, content) => { util.testModule(content) diff --git a/test/transpile/plugins/plugins.spec.ts b/test/transpile/plugins/plugins.spec.ts index d31896729..ce2ebc7a6 100644 --- a/test/transpile/plugins/plugins.spec.ts +++ b/test/transpile/plugins/plugins.spec.ts @@ -4,7 +4,7 @@ import * as util from "../../util"; test("printer", () => { util.testModule`` .setOptions({ luaPlugins: [{ name: path.join(__dirname, "printer.ts") }] }) - .tap((builder) => expect(builder.getMainLuaCodeChunk()).toMatch("Plugin")); + .tap(builder => expect(builder.getMainLuaCodeChunk()).toMatch("Plugin")); }); test("visitor", () => { diff --git a/test/transpile/run.ts b/test/transpile/run.ts index 52cb31a59..72afa7ca2 100644 --- a/test/transpile/run.ts +++ b/test/transpile/run.ts @@ -13,7 +13,7 @@ export function buildVirtualProject(rootNames: string[], options: tstl.CompilerO options.types = []; const { diagnostics, emitResult } = tstl.transpileFiles(rootNames, options); - const emittedFiles = emitResult.map((result) => path.relative(__dirname, result.name).replace(/\\/g, "/")).sort(); + const emittedFiles = emitResult.map(result => path.relative(__dirname, result.name).replace(/\\/g, "/")).sort(); return { diagnostics, emitResult, emittedFiles }; } diff --git a/test/transpile/transformers/fixtures.ts b/test/transpile/transformers/fixtures.ts index e2ece47f7..c998d6efc 100644 --- a/test/transpile/transformers/fixtures.ts +++ b/test/transpile/transformers/fixtures.ts @@ -6,33 +6,34 @@ import { visitAndReplace } from "./utils"; export const program = (program: ts.Program, options: { value: any }): ts.TransformerFactory => checker(program.getTypeChecker(), options); -export const config = ({ value }: { value: any }): ts.TransformerFactory => (context) => (file) => - visitAndReplace(context, file, (node) => { +export const config = ({ value }: { value: any }): ts.TransformerFactory => context => file => + visitAndReplace(context, file, node => { if (!ts.isReturnStatement(node)) return; return ts.updateReturn(node, ts.createLiteral(value)); }); -export const checker = (checker: ts.TypeChecker, { value }: { value: any }): ts.TransformerFactory => ( - context -) => (file) => - visitAndReplace(context, file, (node) => { +export const checker = ( + checker: ts.TypeChecker, + { value }: { value: any } +): ts.TransformerFactory => context => file => + visitAndReplace(context, file, node => { if (!ts.isReturnStatement(node) || !node.expression) return; const type = checker.getTypeAtLocation(node.expression); if ((type.flags & ts.TypeFlags.BooleanLiteral) === 0) return; return ts.updateReturn(node, ts.createLiteral(value)); }); -export const raw: ts.TransformerFactory = (context) => (file) => - visitAndReplace(context, file, (node) => { +export const raw: ts.TransformerFactory = context => file => + visitAndReplace(context, file, node => { if (!ts.isReturnStatement(node)) return; return ts.updateReturn(node, ts.createLiteral(true)); }); -export const compilerOptions = (options: tstl.CompilerOptions): ts.TransformerFactory => (context) => ( - file -) => { +export const compilerOptions = ( + options: tstl.CompilerOptions +): ts.TransformerFactory => context => file => { assert(options.plugins?.length === 1); - return visitAndReplace(context, file, (node) => { + return visitAndReplace(context, file, node => { if (!ts.isReturnStatement(node)) return; return ts.updateReturn(node, ts.createLiteral(true)); }); diff --git a/test/transpile/transformers/transformers.spec.ts b/test/transpile/transformers/transformers.spec.ts index 00f83da4d..e166198bd 100644 --- a/test/transpile/transformers/transformers.spec.ts +++ b/test/transpile/transformers/transformers.spec.ts @@ -24,7 +24,7 @@ test("transformer resolution error", () => { }); describe("factory types", () => { - test.each(["program", "config", "checker", "raw", "compilerOptions"] as const)("%s", (type) => { + test.each(["program", "config", "checker", "raw", "compilerOptions"] as const)("%s", type => { util.testFunction` return false; ` diff --git a/test/transpile/transformers/utils.ts b/test/transpile/transformers/utils.ts index 7cd54f2d7..3e1503ba0 100644 --- a/test/transpile/transformers/utils.ts +++ b/test/transpile/transformers/utils.ts @@ -1,6 +1,6 @@ import * as ts from "typescript"; export function visitAndReplace(context: ts.TransformationContext, node: T, visitor: ts.Visitor): T { - const visit: ts.Visitor = (node) => visitor(node) ?? ts.visitEachChild(node, visit, context); + const visit: ts.Visitor = node => visitor(node) ?? ts.visitEachChild(node, visit, context); return ts.visitNode(node, visit); } diff --git a/test/unit/annotations/compileMembersOnly.spec.ts b/test/unit/annotations/compileMembersOnly.spec.ts index aad3395e9..5db0fe974 100644 --- a/test/unit/annotations/compileMembersOnly.spec.ts +++ b/test/unit/annotations/compileMembersOnly.spec.ts @@ -12,7 +12,7 @@ test("@compileMembersOnly", () => { return { A: TestEnum.A, B: TestEnum.B, C: TestEnum.C, D: TestEnum.D }; ` - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("TestEnum")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("TestEnum")) .expectToMatchJsResult(); }); @@ -29,6 +29,6 @@ test("@compileMembersOnly in a namespace", () => { export const A = Test.TestEnum.A; ` .setReturnExport("A") - .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain("Test.A")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("Test.A")) .expectToEqual("A"); }); diff --git a/test/unit/annotations/extension.spec.ts b/test/unit/annotations/extension.spec.ts index 344be25a4..c8da1b81b 100644 --- a/test/unit/annotations/extension.spec.ts +++ b/test/unit/annotations/extension.spec.ts @@ -5,7 +5,7 @@ import { } from "../../../src/transformation/utils/diagnostics"; import * as util from "../../util"; -test.each(["extension", "metaExtension"])("Class extends extension (%p)", (extensionType) => { +test.each(["extension", "metaExtension"])("Class extends extension (%p)", extensionType => { util.testModule` declare class A {} /** @${extensionType} **/ @@ -14,7 +14,7 @@ test.each(["extension", "metaExtension"])("Class extends extension (%p)", (exten `.expectDiagnosticsToMatchSnapshot([extensionCannotExtend.code]); }); -test.each(["extension", "metaExtension"])("Class construct extension (%p)", (extensionType) => { +test.each(["extension", "metaExtension"])("Class construct extension (%p)", extensionType => { util.testModule` declare class A {} /** @${extensionType} **/ @@ -23,7 +23,7 @@ test.each(["extension", "metaExtension"])("Class construct extension (%p)", (ext `.expectDiagnosticsToMatchSnapshot([extensionCannotConstruct.code]); }); -test.each(["extension", "metaExtension"])("instanceof extension (%p)", (extensionType) => { +test.each(["extension", "metaExtension"])("instanceof extension (%p)", extensionType => { util.testModule` declare class A {} /** @${extensionType} **/ diff --git a/test/unit/annotations/forRange.spec.ts b/test/unit/annotations/forRange.spec.ts index 900166d52..661c45253 100644 --- a/test/unit/annotations/forRange.spec.ts +++ b/test/unit/annotations/forRange.spec.ts @@ -32,7 +32,7 @@ describe("invalid usage", () => { `.expectDiagnosticsToMatchSnapshot([invalidForRangeCall.code]); }); - test.each<[number[]]>([[[]], [[1]], [[1, 2, 3, 4]]])("argument count (%p)", (args) => { + test.each<[number[]]>([[[]], [[1]], [[1, 2, 3, 4]]])("argument count (%p)", args => { util.testModule` ${createForRangeDeclaration("...args: number[]")} for (const i of luaRange(${args})) {} @@ -74,7 +74,7 @@ describe("invalid usage", () => { "let array = [0, luaRange, 1];", "const call = undefined as any; call(luaRange);", "for (const i of [...luaRange(1, 10)]) {}", - ])("reference (%p)", (statement) => { + ])("reference (%p)", statement => { util.testModule` ${createForRangeDeclaration()} ${statement} diff --git a/test/unit/annotations/luaTable.spec.ts b/test/unit/annotations/luaTable.spec.ts index 342ce84f1..8829938bb 100644 --- a/test/unit/annotations/luaTable.spec.ts +++ b/test/unit/annotations/luaTable.spec.ts @@ -34,7 +34,7 @@ declare const Table: new (notAllowed?: any) => Table declare let tbl: Table; `; -test.each([tableLibClass])("LuaTables cannot be constructed with arguments", (tableLib) => { +test.each([tableLibClass])("LuaTables cannot be constructed with arguments", tableLib => { util.testModule(tableLib + "const table = new Table(true);").expectDiagnosticsToMatchSnapshot([ luaTableForbiddenUsage.code, ]); @@ -42,37 +42,37 @@ test.each([tableLibClass])("LuaTables cannot be constructed with arguments", (ta test.each([tableLibClass, tableLibInterface])( "LuaTable set() cannot be used in a LuaTable call expression", - (tableLib) => { + tableLib => { util.testModule(tableLib + 'const exp = tbl.set("value", 5)').expectDiagnosticsToMatchSnapshot([ unsupportedProperty.code, ]); } ); -test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", (tableLib) => { +test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", tableLib => { util.testModule(tableLib + "tbl.other()").expectDiagnosticsToMatchSnapshot([unsupportedProperty.code]); }); -test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", (tableLib) => { +test.each([tableLibClass, tableLibInterface])("LuaTables cannot have other members", tableLib => { util.testModule(tableLib + "let x = tbl.other()").expectDiagnosticsToMatchSnapshot([unsupportedProperty.code]); }); -test.each([tableLibClass])("LuaTable new", (tableLib) => { +test.each([tableLibClass])("LuaTable new", tableLib => { const content = tableLib + "tbl = new Table();"; expect(util.transpileString(content)).toEqual("tbl = {}"); }); -test.each([tableLibClass])("LuaTable length", (tableLib) => { +test.each([tableLibClass])("LuaTable length", tableLib => { const content = tableLib + "tbl = new Table();\nreturn tbl.length;"; const lua = util.transpileString(content); expect(util.executeLua(lua)).toEqual(0); }); -test.each([tableLibClass, tableLibInterface])("Cannot set LuaTable length", (tableLib) => { +test.each([tableLibClass, tableLibInterface])("Cannot set LuaTable length", tableLib => { util.testModule(tableLib + "tbl.length = 2;").expectDiagnosticsToMatchSnapshot([luaTableForbiddenUsage.code]); }); -test.each([tableLibClass, tableLibInterface])("Forbidden LuaTable use", (tableLib) => { +test.each([tableLibClass, tableLibInterface])("Forbidden LuaTable use", tableLib => { test.each([ "tbl.get()", 'tbl.get("field", "field2")', @@ -81,15 +81,15 @@ test.each([tableLibClass, tableLibInterface])("Forbidden LuaTable use", (tableLi 'tbl.set("field", 0, 1)', 'tbl.set(...(["field", 0] as const))', 'tbl.set("field", ...([0] as const))', - ])("Forbidden LuaTable use (%p)", (invalidCode) => { + ])("Forbidden LuaTable use (%p)", invalidCode => { util.testModule(tableLib + invalidCode).expectDiagnosticsToMatchSnapshot([luaTableForbiddenUsage.code]); }); }); -test.each([tableLibClass])("Cannot extend LuaTable class", (tableLib) => { +test.each([tableLibClass])("Cannot extend LuaTable class", tableLib => { test.each(["class Ext extends Table {}", "const c = class Ext extends Table {}"])( "Cannot extend LuaTable class (%p)", - (code) => { + code => { util.testModule(tableLib + code).expectDiagnosticsToMatchSnapshot([luaTableCannotBeExtended.code]); } ); @@ -99,20 +99,20 @@ test.each([ "/** @luaTable */ class Table {}", "/** @luaTable */ export class Table {}", "/** @luaTable */ const c = class Table {}", -])("LuaTable classes must be ambient (%p)", (code) => { +])("LuaTable classes must be ambient (%p)", code => { util.testModule(code).expectDiagnosticsToMatchSnapshot([luaTableMustBeAmbient.code]); }); -test.each([tableLibClass])("Cannot extend LuaTable class", (tableLib) => { - test.each(["tbl instanceof Table"])("Cannot use instanceof on a LuaTable class (%p)", (code) => { +test.each([tableLibClass])("Cannot extend LuaTable class", tableLib => { + test.each(["tbl instanceof Table"])("Cannot use instanceof on a LuaTable class (%p)", code => { util.testModule(tableLib + code).expectDiagnosticsToMatchSnapshot([luaTableInvalidInstanceOf.code]); }); }); -test.each([tableLibClass, tableLibInterface])("Cannot use ElementAccessExpression on a LuaTable", (tableLib) => { +test.each([tableLibClass, tableLibInterface])("Cannot use ElementAccessExpression on a LuaTable", tableLib => { test.each(['tbl["get"]("field")', 'tbl["set"]("field")', 'tbl["length"]'])( "Cannot use ElementAccessExpression on a LuaTable (%p)", - (code) => { + code => { util.testModule(tableLib + code).expectDiagnosticsToMatchSnapshot([ luaTableCannotBeAccessedDynamically.code, ]); @@ -120,15 +120,15 @@ test.each([tableLibClass, tableLibInterface])("Cannot use ElementAccessExpressio ); }); -test.each([tableLibClass, tableLibInterface])("Cannot isolate LuaTable methods", (tableLib) => { - test.each(["set", "get"])("Cannot isolate LuaTable method (%p)", (propertyName) => { +test.each([tableLibClass, tableLibInterface])("Cannot isolate LuaTable methods", tableLib => { + test.each(["set", "get"])("Cannot isolate LuaTable method (%p)", propertyName => { util.testModule(`${tableLib} let property = tbl.${propertyName}`).expectDiagnosticsToMatchSnapshot([ unsupportedProperty.code, ]); }); }); -test.each([tableLibClass])("LuaTable functional tests", (tableLib) => { +test.each([tableLibClass])("LuaTable functional tests", tableLib => { test.each<[string, any]>([ ['const t = new Table(); t.set("field", "value"); return t.get("field");', "value"], ['const t = new Table(); t.set("field", 0); return t.get("field");', 0], diff --git a/test/unit/annotations/tupleReturn.spec.ts b/test/unit/annotations/tupleReturn.spec.ts index 2a91c5a83..7c7c7ae9b 100644 --- a/test/unit/annotations/tupleReturn.spec.ts +++ b/test/unit/annotations/tupleReturn.spec.ts @@ -1,6 +1,6 @@ import * as util from "../../util"; -const expectNoUnpack: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack"); +const expectNoUnpack: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack"); test("Tuple Return Access", () => { util.testFunction` diff --git a/test/unit/annotations/vararg.spec.ts b/test/unit/annotations/vararg.spec.ts index ffa44fc4d..1635ef13a 100644 --- a/test/unit/annotations/vararg.spec.ts +++ b/test/unit/annotations/vararg.spec.ts @@ -17,8 +17,8 @@ test("@vararg", () => { } return bar("A", "B", "C", "D"); ` - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("b = ")) - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("b = ")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) .expectToMatchJsResult(); }); @@ -39,7 +39,7 @@ test("@vararg global", () => { declare const arg: LuaVararg; export const result = [...arg].join(""); ` - .setLuaFactory((code) => `return (function(...) ${code} end)("A", "B", "C", "D")`) - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) + .setLuaFactory(code => `return (function(...) ${code} end)("A", "B", "C", "D")`) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("unpack")) .expectToEqual({ result: "ABCD" }); }); diff --git a/test/unit/assignments.spec.ts b/test/unit/assignments.spec.ts index bb85eb1a2..178d72bab 100644 --- a/test/unit/assignments.spec.ts +++ b/test/unit/assignments.spec.ts @@ -1,7 +1,7 @@ import { unsupportedVarDeclaration } from "../../src/transformation/utils/diagnostics"; import * as util from "../util"; -test.each(["const", "let"])("%s declaration not top-level is not global", (declarationKind) => { +test.each(["const", "let"])("%s declaration not top-level is not global", declarationKind => { util.testModule` { ${declarationKind} foo = true; @@ -11,7 +11,7 @@ test.each(["const", "let"])("%s declaration not top-level is not global", (decla `.expectToEqual(false); }); -test.each(["const", "let"])("top-level %s declaration is global", (declarationKind) => { +test.each(["const", "let"])("top-level %s declaration is global", declarationKind => { // TODO [typescript@>=3.9]: Remove `@ts-ignore` comments before module imports util.testBundle` // @ts-ignore @@ -50,7 +50,7 @@ describe("var is disallowed", () => { test.each(["let result;", "const result = null;", "const result = undefined;"])( "Null assignments (%p)", - (declaration) => { + declaration => { util.testFunction` ${declaration} return result; @@ -58,7 +58,7 @@ test.each(["let result;", "const result = null;", "const result = undefined;"])( } ); -test.each(["x = y", "x += y"])("Assignment expressions (%p)", (expression) => { +test.each(["x = y", "x += y"])("Assignment expressions (%p)", expression => { util.testFunction` let x = "x"; let y = "y"; @@ -66,7 +66,7 @@ test.each(["x = y", "x += y"])("Assignment expressions (%p)", (expression) => { `.expectToMatchJsResult(); }); -test.each(["x = o.p", "x = a[0]", "x = y = o.p", "x = o.p"])("Assignment expressions using temp (%p)", (expression) => { +test.each(["x = o.p", "x = a[0]", "x = y = o.p", "x = o.p"])("Assignment expressions using temp (%p)", expression => { util.testFunction` let x = "x"; let y = "y"; @@ -78,7 +78,7 @@ test.each(["x = o.p", "x = a[0]", "x = y = o.p", "x = o.p"])("Assignment express test.each(["o.p = x", "a[0] = x", "o.p = a[0]", "o.p = a[0] = x"])( "Property assignment expressions (%p)", - (expression) => { + expression => { util.testFunction` let x = "x"; let o = {p: "o"}; @@ -95,7 +95,7 @@ test.each([ "[x[1], x[0]] = tr()", "x = [y[1], y[0]]", "[x[0], x[1]] = [y[1], y[0]]", -])("Tuple assignment expressions (%p)", (expression) => { +])("Tuple assignment expressions (%p)", expression => { util.testFunction` let x: [string, string] = ["x0", "x1"]; let y: [string, string] = ["y0", "y1"]; @@ -123,7 +123,7 @@ test.each([ "x ^= y", "x <<= y", "x >>>= y", -])("Operator assignment statements (%p)", (statement) => { +])("Operator assignment statements (%p)", statement => { util.testFunction` let x = 3; let y = 6; @@ -148,7 +148,7 @@ test.each([ "o.p ^= a[0]", "o.p <<= a[0]", "o.p >>>= a[0]", -])("Operator assignment to simple property statements (%p)", (statement) => { +])("Operator assignment to simple property statements (%p)", statement => { util.testFunction` let o = { p: 3 }; let a = [6]; @@ -173,7 +173,7 @@ test.each([ "o.p.d ^= a[0][0]", "o.p.d <<= a[0][0]", "o.p.d >>>= a[0][0]", -])("Operator assignment to deep property statements (%p)", (statement) => { +])("Operator assignment to deep property statements (%p)", statement => { util.testFunction` let o = { p: { d: 3 } }; let a = [[6,11], [7,13]]; @@ -198,7 +198,7 @@ test.each([ "of().p ^= af()[i()]", "of().p <<= af()[i()]", "of().p >>>= af()[i()]", -])("Operator assignment to complex property statements (%p)", (statement) => { +])("Operator assignment to complex property statements (%p)", statement => { util.testFunction` let o = { p: 3 }; let a = [6]; @@ -226,7 +226,7 @@ test.each([ "of().p.d ^= af()[i()][i()]", "of().p.d <<= af()[i()][i()]", "of().p.d >>>= af()[i()][i()]", -])("Operator assignment to complex deep property statements (%p)", (statement) => { +])("Operator assignment to complex deep property statements (%p)", statement => { util.testFunction` let o = { p: { d: 3 } }; let a = [[7, 6], [11, 13]]; @@ -258,7 +258,7 @@ test.each([ "x + (y += 7)", "x + (y += 7)", "x++ + (y += 7)", -])("Operator assignment expressions (%p)", (expression) => { +])("Operator assignment expressions (%p)", expression => { util.testFunction` let x = 3; let y = 6; @@ -286,7 +286,7 @@ test.each([ "o.p + (a[0] += 7)", "o.p += (a[0] += 7)", "o.p++ + (a[0] += 7)", -])("Operator assignment to simple property expressions (%p)", (expression) => { +])("Operator assignment to simple property expressions (%p)", expression => { util.testFunction` let o = { p: 3 }; let a = [6]; @@ -314,7 +314,7 @@ test.each([ "of().p + (af()[i()] += 7)", "of().p += (af()[i()] += 7)", "of().p++ + (af()[i()] += 7)", -])("Operator assignment to complex property expressions (%p)", (expression) => { +])("Operator assignment to complex property expressions (%p)", expression => { util.testFunction` let o = { p: 3 }; let a = [6]; diff --git a/test/unit/builtins/array.spec.ts b/test/unit/builtins/array.spec.ts index 7d6953018..35294be6d 100644 --- a/test/unit/builtins/array.spec.ts +++ b/test/unit/builtins/array.spec.ts @@ -156,11 +156,11 @@ describe("array.length", () => { `.expectToEqual(newLength); }); - test.each([0, 1, 7])("returns right-hand side value", (length) => { + test.each([0, 1, 7])("returns right-hand side value", length => { util.testExpression`[1, 2, 3].length = ${length}`.expectToEqual(length); }); - test.each([-1, -7, 0.1, NaN, Infinity, -Infinity])("throws on invalid values (%p)", (length) => { + test.each([-1, -7, 0.1, NaN, Infinity, -Infinity])("throws on invalid values (%p)", length => { util.testFunction` [1, 2, 3].length = ${length}; `.expectToEqual(new util.ExecutionError(`invalid array length: ${length}`)); @@ -538,7 +538,7 @@ test.each([ util.testExpressionTemplate`${array}.flatMap(${map})`.expectToMatchJsResult(); }); -describe.each(["reduce", "reduceRight"])("array.%s", (reduce) => { +describe.each(["reduce", "reduceRight"])("array.%s", reduce => { test.each<[[(total: number, currentItem: number, index: number, array: number[]) => number, number?]]>([ [[(total, currentItem) => total + currentItem]], [[(total, currentItem) => total * currentItem]], @@ -546,7 +546,7 @@ describe.each(["reduce", "reduceRight"])("array.%s", (reduce) => { [[(total, currentItem) => total * currentItem, 10]], [[(total, _, index, array) => total + array[index]]], [[(a, b) => a + b]], - ])("usage (%p)", (args) => { + ])("usage (%p)", args => { util.testExpression`[1, 3, 5, 7].${reduce}(${util.formatCode(...args)})`.expectToMatchJsResult(); }); @@ -576,7 +576,7 @@ const genericChecks = [ "function generic(array: T)", ]; -test.each(genericChecks)("array constrained generic foreach (%p)", (signature) => { +test.each(genericChecks)("array constrained generic foreach (%p)", signature => { const code = ` ${signature}: number { let sum = 0; @@ -592,7 +592,7 @@ test.each(genericChecks)("array constrained generic foreach (%p)", (signature) = expect(util.transpileAndExecute(code)).toBe(6); }); -test.each(genericChecks)("array constrained generic length (%p)", (signature) => { +test.each(genericChecks)("array constrained generic length (%p)", signature => { const code = ` ${signature}: number { return array.length; diff --git a/test/unit/builtins/console.spec.ts b/test/unit/builtins/console.spec.ts index 463d5e9d5..a68c1be5c 100644 --- a/test/unit/builtins/console.spec.ts +++ b/test/unit/builtins/console.spec.ts @@ -8,7 +8,7 @@ test.each([ 'console.log("Hello %s", "there")', 'console.log("Hello %%s", "there")', 'console.log("Hello", "There")', -])("console.log (%p)", (code) => { +])("console.log (%p)", code => { util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); @@ -18,7 +18,7 @@ test.each([ 'console.info("Hello %s", "there")', 'console.info("Hello %%s", "there")', 'console.info("Hello", "There")', -])("console.info (%p)", (code) => { +])("console.info (%p)", code => { util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); @@ -28,7 +28,7 @@ test.each([ 'console.error("Hello %s", "there")', 'console.error("Hello %%s", "there")', 'console.error("Hello", "There")', -])("console.error (%p)", (code) => { +])("console.error (%p)", code => { util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); @@ -38,7 +38,7 @@ test.each([ 'console.warn("Hello %s", "there")', 'console.warn("Hello %%s", "there")', 'console.warn("Hello", "There")', -])("console.warn (%p)", (code) => { +])("console.warn (%p)", code => { util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); @@ -48,7 +48,7 @@ test.each([ 'console.trace("Hello %s", "there")', 'console.trace("Hello %%s", "there")', 'console.trace("Hello", "there")', -])("console.trace (%p)", (code) => { +])("console.trace (%p)", code => { util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); @@ -58,7 +58,7 @@ test.each([ 'console.assert(false, "message %s", "info")', 'console.assert(false, "message %%s", "info")', 'console.assert(false, "message", "more")', -])("console.assert (%p)", (code) => { +])("console.assert (%p)", code => { util.testFunction(code).setOptions(compilerOptions).expectLuaToMatchSnapshot(); }); diff --git a/test/unit/builtins/loading.spec.ts b/test/unit/builtins/loading.spec.ts index 6ddcb89ec..fa213d03f 100644 --- a/test/unit/builtins/loading.spec.ts +++ b/test/unit/builtins/loading.spec.ts @@ -6,34 +6,34 @@ describe("luaLibImport", () => { test("inline", () => { util.testExpression`[0].push(1)` .setOptions({ luaLibImport: tstl.LuaLibImportKind.Inline }) - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain('require("lualib_bundle")')) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain('require("lualib_bundle")')) .expectToMatchJsResult(); }); test("require", () => { util.testExpression`[0].push(1)` .setOptions({ luaLibImport: tstl.LuaLibImportKind.Require }) - .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) + .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) .expectToMatchJsResult(); }); test("always", () => { util.testModule`` .setOptions({ luaLibImport: tstl.LuaLibImportKind.Always }) - .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) + .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain('require("lualib_bundle")')) .expectToEqual(undefined); }); }); test.each([tstl.LuaLibImportKind.Inline, tstl.LuaLibImportKind.None, tstl.LuaLibImportKind.Require])( "should not include lualib without code (%p)", - (luaLibImport) => { - util.testModule``.setOptions({ luaLibImport }).tap((builder) => expect(builder.getMainLuaCodeChunk()).toBe("")); + luaLibImport => { + util.testModule``.setOptions({ luaLibImport }).tap(builder => expect(builder.getMainLuaCodeChunk()).toBe("")); } ); test("lualib should not include tstl header", () => { - util.testExpression`[0].push(1)`.tap((builder) => + util.testExpression`[0].push(1)`.tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("Generated with") ); }); diff --git a/test/unit/builtins/map.spec.ts b/test/unit/builtins/map.spec.ts index 6e700bebe..e9edd2508 100644 --- a/test/unit/builtins/map.spec.ts +++ b/test/unit/builtins/map.spec.ts @@ -97,7 +97,7 @@ test.each([ '[["b", "c"], ["a", null]]', '[["a", null], ["b", "c"]]', '[["b", "c"], ["a", null], ["x", "y"]]', -])("map (%p) has null", (entries) => { +])("map (%p) has null", entries => { util.testFunction` let mymap = new Map(${entries}); return mymap.has("a"); @@ -109,7 +109,7 @@ test.each([ '[["b", "c"], ["a", undefined]]', '[["a", undefined], ["b", "c"]]', '[["b", "c"], ["a", undefined], ["x", "y"]]', -])("map (%p) has undefined", (entries) => { +])("map (%p) has undefined", entries => { util.testFunction` let mymap = new Map(${entries}); return mymap.has("a"); @@ -156,7 +156,7 @@ test("map size", () => { }); const iterationMethods = ["entries", "keys", "values"]; -describe.each(iterationMethods)("map.%s() preserves insertion order", (iterationMethod) => { +describe.each(iterationMethods)("map.%s() preserves insertion order", iterationMethod => { test("basic", () => { util.testFunction` const mymap = new Map(); diff --git a/test/unit/builtins/math.spec.ts b/test/unit/builtins/math.spec.ts index 383e742cd..2ef0544a6 100644 --- a/test/unit/builtins/math.spec.ts +++ b/test/unit/builtins/math.spec.ts @@ -12,25 +12,25 @@ test.each([ "Math.log1p(3)", "Math.round(3.3)", "Math.PI", -])("%s", (code) => { +])("%s", code => { // TODO: Remove? util.testFunction(code).disableSemanticCheck().expectLuaToMatchSnapshot(); }); -test.each(["E", "LN10", "LN2", "LOG10E", "LOG2E", "SQRT1_2", "SQRT2"])("Math.%s", (constant) => { - util.testExpression`Math.${constant}`.tap((builder) => { +test.each(["E", "LN10", "LN2", "LOG10E", "LOG2E", "SQRT1_2", "SQRT2"])("Math.%s", constant => { + util.testExpression`Math.${constant}`.tap(builder => { expect(builder.getLuaExecutionResult()).toBeCloseTo(builder.getJsExecutionResult()); }); }); -const expectMathAtan2: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toContain("math.atan2("); -const expectMathAtan: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toContain("math.atan("); +const expectMathAtan2: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toContain("math.atan2("); +const expectMathAtan: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toContain("math.atan("); util.testEachVersion("Math.atan2", () => util.testExpression`Math.atan2(4, 5)`, { - [tstl.LuaTarget.LuaJIT]: (builder) => builder.tap(expectMathAtan2), - [tstl.LuaTarget.Lua51]: (builder) => builder.tap(expectMathAtan2), - [tstl.LuaTarget.Lua52]: (builder) => builder.tap(expectMathAtan2), - [tstl.LuaTarget.Lua53]: (builder) => builder.tap(expectMathAtan), + [tstl.LuaTarget.LuaJIT]: builder => builder.tap(expectMathAtan2), + [tstl.LuaTarget.Lua51]: builder => builder.tap(expectMathAtan2), + [tstl.LuaTarget.Lua52]: builder => builder.tap(expectMathAtan2), + [tstl.LuaTarget.Lua53]: builder => builder.tap(expectMathAtan), }); test("Math.atan2(4, 5)", () => { diff --git a/test/unit/builtins/numbers.spec.ts b/test/unit/builtins/numbers.spec.ts index 6f8d5e3f7..2f52c1d7d 100644 --- a/test/unit/builtins/numbers.spec.ts +++ b/test/unit/builtins/numbers.spec.ts @@ -18,11 +18,11 @@ test.each([ "Infinity * -1", "Infinity + 1", "Infinity - 1", -])("%s", (code) => { +])("%s", code => { util.testExpression(code).expectToMatchJsResult(); }); -test.skip.each(["NaN", "Infinity"])("%s reassignment", (name) => { +test.skip.each(["NaN", "Infinity"])("%s reassignment", name => { util.testFunction` const ${name} = 1; return ${name}; @@ -35,36 +35,36 @@ const restCases = [true, false, "", " ", "\t", "\n", "foo", {}]; const cases = [...numberCases, ...stringCases, ...restCases]; describe("Number", () => { - test.each(cases)("constructor(%p)", (value) => { + test.each(cases)("constructor(%p)", value => { util.testExpressionTemplate`Number(${value})`.expectToMatchJsResult(); }); - test.each(cases)("isNaN(%p)", (value) => { + test.each(cases)("isNaN(%p)", value => { util.testExpressionTemplate`Number.isNaN(${value} as any)`.expectToMatchJsResult(); }); - test.each(cases)("isFinite(%p)", (value) => { + test.each(cases)("isFinite(%p)", value => { util.testExpressionTemplate`Number.isFinite(${value} as any)`.expectToMatchJsResult(); }); }); const toStringRadixes = [undefined, 10, 2, 8, 9, 16, 17, 36, 36.9]; const toStringValues = [-1, 0, 1, 1.5, 1024, 1.2]; -const toStringPairs = toStringValues.flatMap((value) => toStringRadixes.map((radix) => [value, radix] as const)); +const toStringPairs = toStringValues.flatMap(value => toStringRadixes.map(radix => [value, radix] as const)); test.each(toStringPairs)("(%p).toString(%p)", (value, radix) => { util.testExpressionTemplate`(${value}).toString(${radix})`.expectToMatchJsResult(); }); -test.each([NaN, Infinity, -Infinity])("%p.toString(2)", (value) => { +test.each([NaN, Infinity, -Infinity])("%p.toString(2)", value => { util.testExpressionTemplate`(${value}).toString(2)`.expectToMatchJsResult(); }); -test.each(cases)("isNaN(%p)", (value) => { +test.each(cases)("isNaN(%p)", value => { util.testExpressionTemplate`isNaN(${value} as any)`.expectToMatchJsResult(); }); -test.each(cases)("isFinite(%p)", (value) => { +test.each(cases)("isFinite(%p)", value => { util.testExpressionTemplate`isFinite(${value} as any)`.expectToMatchJsResult(); }); diff --git a/test/unit/builtins/object.spec.ts b/test/unit/builtins/object.spec.ts index 959027a0b..067da81f6 100644 --- a/test/unit/builtins/object.spec.ts +++ b/test/unit/builtins/object.spec.ts @@ -10,21 +10,21 @@ test.each([ util.testExpression`Object.assign(${util.formatCode(initial)}, ${argsString})`.expectToMatchJsResult(); }); -test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.entries (%p)", (obj) => { +test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.entries (%p)", obj => { util.testExpressionTemplate`Object.entries(${obj})`.expectToMatchJsResult(); }); -test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.keys (%p)", (obj) => { +test.each([{}, { abc: 3 }, { abc: 3, def: "xyz" }])("Object.keys (%p)", obj => { util.testExpressionTemplate`Object.keys(${obj})`.expectToMatchJsResult(); }); -test.each([{}, { abc: "def" }, { abc: 3, def: "xyz" }])("Object.values (%p)", (obj) => { +test.each([{}, { abc: "def" }, { abc: 3, def: "xyz" }])("Object.values (%p)", obj => { util.testExpressionTemplate`Object.values(${obj})`.expectToMatchJsResult(); }); test.each(["[]", '[["a", 1], ["b", 2]]', '[["a", 1], ["a", 2]]', 'new Map([["foo", "bar"]])'])( "Object.fromEntries(%s)", - (entries) => { + entries => { util.testExpression`Object.fromEntries(${entries})`.expectToMatchJsResult(); } ); diff --git a/test/unit/builtins/set.spec.ts b/test/unit/builtins/set.spec.ts index 440478597..8f81edfe8 100644 --- a/test/unit/builtins/set.spec.ts +++ b/test/unit/builtins/set.spec.ts @@ -129,12 +129,12 @@ test.each([ "let m = new Set([1, 2])", "let m = new Set([1, 2]); m.clear()", "let m = new Set([1, 2]); m.delete(2)", -])("set size (%p)", (code) => { +])("set size (%p)", code => { util.testFunction`${code}; return m.size`.expectToMatchJsResult(); }); const iterationMethods = ["entries", "keys", "values"]; -describe.each(iterationMethods)("set.%s() preserves insertion order", (iterationMethod) => { +describe.each(iterationMethods)("set.%s() preserves insertion order", iterationMethod => { test("basic", () => { util.testFunction` const myset = new Set(); diff --git a/test/unit/builtins/string.spec.ts b/test/unit/builtins/string.spec.ts index 30a24acf1..a9b6afba4 100644 --- a/test/unit/builtins/string.spec.ts +++ b/test/unit/builtins/string.spec.ts @@ -64,7 +64,7 @@ test.each([ ["hello", 42], [42, "hello"], ])("string.concat[+] (%p)", (...elements: any[]) => { - util.testExpression(elements.map((e) => util.formatCode(e)).join(" + ")).expectToMatchJsResult(); + util.testExpression(elements.map(e => util.formatCode(e)).join(" + ")).expectToMatchJsResult(); }); test.each([ @@ -148,15 +148,15 @@ test.each([ expect(result).toBe(inp.substr(start, end)); }); -test.each(["", "h", "hello"])("string.length (%p)", (input) => { +test.each(["", "h", "hello"])("string.length (%p)", input => { util.testExpressionTemplate`${input}.length`.expectToMatchJsResult(); }); -test.each(["hello TEST"])("string.toLowerCase (%p)", (inp) => { +test.each(["hello TEST"])("string.toLowerCase (%p)", inp => { util.testExpressionTemplate`${inp}.toLowerCase()`.expectToMatchJsResult(); }); -test.each(["hello test"])("string.toUpperCase (%p)", (inp) => { +test.each(["hello test"])("string.toUpperCase (%p)", inp => { util.testExpressionTemplate`${inp}.toUpperCase()`.expectToMatchJsResult(); }); @@ -249,7 +249,7 @@ test.each(padCases)("string.padEnd (%p)", ({ inp, args }) => { test.each([ "function generic(string: T)", "type StringType = string; function generic(string: T)", -])("string constrained generic foreach (%p)", (signature) => { +])("string constrained generic foreach (%p)", signature => { const code = ` ${signature}: number { return string.length; @@ -275,8 +275,8 @@ const trimTestCases = [ "\r\nfoo\n\r\n", "\r\nfoo\nbar\n\r\n", ]; -describe.each(["trim", "trimEnd", "trimRight", "trimStart", "trimLeft"])("string.%s", (trim) => { - test.each(trimTestCases)("matches JS result (%p)", (testString) => { +describe.each(["trim", "trimEnd", "trimRight", "trimStart", "trimLeft"])("string.%s", trim => { + test.each(trimTestCases)("matches JS result (%p)", testString => { util.testExpression`${util.formatCode(testString)}.${trim}()`.expectToMatchJsResult(); }); }); diff --git a/test/unit/builtins/symbol.spec.ts b/test/unit/builtins/symbol.spec.ts index d8ceeeeaf..3d6b35d8a 100644 --- a/test/unit/builtins/symbol.spec.ts +++ b/test/unit/builtins/symbol.spec.ts @@ -1,10 +1,10 @@ import * as util from "../../util"; -test.each([undefined, 1, "name"])("symbol.toString() (%p)", (description) => { +test.each([undefined, 1, "name"])("symbol.toString() (%p)", description => { util.testExpression`Symbol(${util.formatCode(description)}).toString()`.expectToMatchJsResult(); }); -test.each([undefined, 1, "name"])("symbol.description (%p)", (description) => { +test.each([undefined, 1, "name"])("symbol.description (%p)", description => { // TODO: Supported since node 11 util.testExpression`Symbol(${util.formatCode(description)}).description`.expectToEqual(description); }); diff --git a/test/unit/builtins/weakMap.spec.ts b/test/unit/builtins/weakMap.spec.ts index d5f1c0c34..ab3ba12fb 100644 --- a/test/unit/builtins/weakMap.spec.ts +++ b/test/unit/builtins/weakMap.spec.ts @@ -116,7 +116,7 @@ test("weakMap has no map features (size)", () => { test.each(["clear()", "keys()", "values()", "entries()", "forEach(() => {})"])( "weakMap has no map features (%p)", - (call) => { + call => { expect(() => util.transpileAndExecute(`(new WeakMap() as any).${call}`)).toThrow(); } ); diff --git a/test/unit/builtins/weakSet.spec.ts b/test/unit/builtins/weakSet.spec.ts index 59654576a..fe6accf45 100644 --- a/test/unit/builtins/weakSet.spec.ts +++ b/test/unit/builtins/weakSet.spec.ts @@ -73,7 +73,7 @@ test("weakSet has no set features (size)", () => { test.each(["clear()", "keys()", "values()", "entries()", "forEach(() => {})"])( "weakSet has no set features (%p)", - (call) => { + call => { expect(() => util.transpileAndExecute(`(new WeakSet() as any).${call}`)).toThrow(); } ); diff --git a/test/unit/classes/classes.spec.ts b/test/unit/classes/classes.spec.ts index 11ddad9b7..6bf2fc85f 100644 --- a/test/unit/classes/classes.spec.ts +++ b/test/unit/classes/classes.spec.ts @@ -666,7 +666,7 @@ test("Exported class super call", () => { .expectToMatchJsResult(); }); -test.each(["(new Foo())", "Foo"])("Class method name collision (%p)", (input) => { +test.each(["(new Foo())", "Foo"])("Class method name collision (%p)", input => { util.testFunction` class Foo { public method() { return "foo"; } diff --git a/test/unit/conditionals.spec.ts b/test/unit/conditionals.spec.ts index 4c07c5222..890c6dc71 100644 --- a/test/unit/conditionals.spec.ts +++ b/test/unit/conditionals.spec.ts @@ -2,7 +2,7 @@ import * as tstl from "../../src"; import { unsupportedForTarget } from "../../src/transformation/utils/diagnostics"; import * as util from "../util"; -test.each([0, 1])("if (%p)", (inp) => { +test.each([0, 1])("if (%p)", inp => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -12,7 +12,7 @@ test.each([0, 1])("if (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1])("ifelse (%p)", (inp) => { +test.each([0, 1])("ifelse (%p)", inp => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -23,7 +23,7 @@ test.each([0, 1])("ifelse (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("ifelseif (%p)", (inp) => { +test.each([0, 1, 2, 3])("ifelseif (%p)", inp => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -37,7 +37,7 @@ test.each([0, 1, 2, 3])("ifelseif (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("ifelseifelse (%p)", (inp) => { +test.each([0, 1, 2, 3])("ifelseifelse (%p)", inp => { util.testFunction` let input: number = ${inp}; if (input === 0) { @@ -52,7 +52,7 @@ test.each([0, 1, 2, 3])("ifelseifelse (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switch (%p)", (inp) => { +test.each([0, 1, 2, 3])("switch (%p)", inp => { util.testFunction` let result: number = -1; @@ -71,7 +71,7 @@ test.each([0, 1, 2, 3])("switch (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchdefault (%p)", (inp) => { +test.each([0, 1, 2, 3])("switchdefault (%p)", inp => { util.testFunction` let result: number = -1; @@ -93,7 +93,7 @@ test.each([0, 1, 2, 3])("switchdefault (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 0, 2, 3, 4, 5, 7])("switchfallthrough (%p)", (inp) => { +test.each([0, 0, 2, 3, 4, 5, 7])("switchfallthrough (%p)", inp => { util.testFunction` let result: number = -1; @@ -125,7 +125,7 @@ test.each([0, 0, 2, 3, 4, 5, 7])("switchfallthrough (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("nestedSwitch (%p)", (inp) => { +test.each([0, 1, 2, 3])("nestedSwitch (%p)", inp => { util.testFunction` let result: number = -1; @@ -196,7 +196,7 @@ test("switch using variable re-declared in cases", () => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2])("switch with block statement scope (%p)", (inp) => { +test.each([0, 1, 2])("switch with block statement scope (%p)", inp => { util.testFunction` let result: number = -1; @@ -220,7 +220,7 @@ test.each([0, 1, 2])("switch with block statement scope (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchReturn (%p)", (inp) => { +test.each([0, 1, 2, 3])("switchReturn (%p)", inp => { util.testFunction` switch (${inp}) { case 0: @@ -237,7 +237,7 @@ test.each([0, 1, 2, 3])("switchReturn (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchWithBrackets (%p)", (inp) => { +test.each([0, 1, 2, 3])("switchWithBrackets (%p)", inp => { util.testFunction` let result: number = -1; @@ -259,7 +259,7 @@ test.each([0, 1, 2, 3])("switchWithBrackets (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchWithBracketsBreakInConditional (%p)", (inp) => { +test.each([0, 1, 2, 3])("switchWithBracketsBreakInConditional (%p)", inp => { util.testFunction` let result: number = -1; @@ -282,7 +282,7 @@ test.each([0, 1, 2, 3])("switchWithBracketsBreakInConditional (%p)", (inp) => { `.expectToMatchJsResult(); }); -test.each([0, 1, 2, 3])("switchWithBracketsBreakInInternalLoop (%p)", (inp) => { +test.each([0, 1, 2, 3])("switchWithBracketsBreakInInternalLoop (%p)", inp => { util.testFunction` let result: number = -1; @@ -391,7 +391,7 @@ test.each([ util.testExpressionTemplate`${condition} ? ${lhs} : ${rhs}`.expectToMatchJsResult(); }); -test.each(["true", "false", "a < 4", "a == 8"])("Ternary Conditional Delayed (%p)", (condition) => { +test.each(["true", "false", "a < 4", "a == 8"])("Ternary Conditional Delayed (%p)", condition => { util.testFunction` let a = 3; let delay = () => ${condition} ? a + 3 : a + 5; diff --git a/test/unit/destructuring.spec.ts b/test/unit/destructuring.spec.ts index 830caad97..761930ec2 100644 --- a/test/unit/destructuring.spec.ts +++ b/test/unit/destructuring.spec.ts @@ -88,7 +88,7 @@ test.each(assignmentTestCases)("in assignment expression (%p)", ({ binding, valu `.expectToMatchJsResult(); }); -test.each(["[]", "{}"])("empty binding pattern", (bindingPattern) => { +test.each(["[]", "{}"])("empty binding pattern", bindingPattern => { util.testFunction` let i = 1; const ${bindingPattern} = [i++]; @@ -133,7 +133,7 @@ describe("array destructuring optimization", () => { const [a, b, c] = array; return { a, b, c }; ` - .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) .expectToMatchJsResult(); }); @@ -142,7 +142,7 @@ describe("array destructuring optimization", () => { const [a, b, c] = [3, 5, 1]; return { a, b, c }; ` - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) .expectToMatchJsResult(); }); @@ -153,7 +153,7 @@ describe("array destructuring optimization", () => { const [head] = ["foo", set()]; return { head, called }; ` - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("unpack")) .expectToMatchJsResult(); }); @@ -164,7 +164,7 @@ describe("array destructuring optimization", () => { [x] = array; return x; ` - .tap((builder) => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("unpack")) .expectToMatchJsResult(); }); }); diff --git a/test/unit/enum.spec.ts b/test/unit/enum.spec.ts index 325a03ccc..8da16355c 100644 --- a/test/unit/enum.spec.ts +++ b/test/unit/enum.spec.ts @@ -95,10 +95,10 @@ describe("initializers", () => { }); describe("const enum", () => { - const expectToBeConst: util.TapCallback = (builder) => + const expectToBeConst: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).not.toContain("TestEnum"); - test.each(["", "declare "])("%swithout initializer", (modifier) => { + test.each(["", "declare "])("%swithout initializer", modifier => { util.testModule` ${modifier} const enum TestEnum { A, diff --git a/test/unit/error.spec.ts b/test/unit/error.spec.ts index bb4c09c9c..27e0ce839 100644 --- a/test/unit/error.spec.ts +++ b/test/unit/error.spec.ts @@ -6,7 +6,7 @@ test("throwString", () => { `.expectToEqual(new util.ExecutionError("Some Error")); }); -test.skip.each([0, 1, 2])("re-throw (%p)", (i) => { +test.skip.each([0, 1, 2])("re-throw (%p)", i => { util.testFunction` const i: number = ${i}; function foo() { @@ -295,7 +295,7 @@ test.each([ "undefined", '{ x: "error object" }', '() => "error function"', -])("throw and catch %s", (error) => { +])("throw and catch %s", error => { util.testFunction` try { throw ${error}; @@ -311,14 +311,14 @@ test.each([ const builtinErrors = ["Error", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError"]; -test.each([...builtinErrors, ...builtinErrors.map((type) => `new ${type}`)])("%s properties", (errorType) => { +test.each([...builtinErrors, ...builtinErrors.map(type => `new ${type}`)])("%s properties", errorType => { util.testFunction` const error = ${errorType}(); return { name: error.name, message: error.message, string: error.toString() }; `.expectToMatchJsResult(); }); -test.each([...builtinErrors, "CustomError"])("get stack from %s", (errorType) => { +test.each([...builtinErrors, "CustomError"])("get stack from %s", errorType => { const stack = util.testFunction` class CustomError extends Error { public name = "CustomError"; diff --git a/test/unit/expressions.spec.ts b/test/unit/expressions.spec.ts index 620fd2e29..6720fe8fb 100644 --- a/test/unit/expressions.spec.ts +++ b/test/unit/expressions.spec.ts @@ -14,22 +14,22 @@ test.each([ "delete tbl['test']", "let a = delete tbl.test", "delete tbl.test", -])("Unary expressions basic (%p)", (input) => { +])("Unary expressions basic (%p)", input => { util.testFunction(input).disableSemanticCheck().expectLuaToMatchSnapshot(); }); -test.each(["3+4", "5-2", "6*3", "6**3", "20/5", "15/10", "15%3"])("Binary expressions basic numeric (%p)", (input) => { +test.each(["3+4", "5-2", "6*3", "6**3", "20/5", "15/10", "15%3"])("Binary expressions basic numeric (%p)", input => { util.testExpression(input).expectToMatchJsResult(); }); test.each(["1==1", "1===1", "1!=1", "1!==1", "1>1", "1>=1", "1<1", "1<=1", "1&&1", "1||1"])( "Binary expressions basic boolean (%p)", - (input) => { + input => { util.testExpression(input).expectToMatchJsResult(); } ); -test.each(["'key' in obj", "'existingKey' in obj", "0 in obj", "9 in obj"])("Binary expression in (%p)", (input) => { +test.each(["'key' in obj", "'existingKey' in obj", "0 in obj", "9 in obj"])("Binary expression in (%p)", input => { const tsHeader = "declare var obj: any;"; const tsSource = `return ${input}`; const luaHeader = "obj = { existingKey = 1 }"; @@ -38,22 +38,19 @@ test.each(["'key' in obj", "'existingKey' in obj", "0 in obj", "9 in obj"])("Bin expect(result).toBe(eval(`let obj = { existingKey: 1 }; ${input}`)); }); -test.each(["a+=b", "a-=b", "a*=b", "a/=b", "a%=b", "a**=b"])( - "Binary expressions overridden operators (%p)", - (input) => { - util.testFunction` +test.each(["a+=b", "a-=b", "a*=b", "a/=b", "a%=b", "a**=b"])("Binary expressions overridden operators (%p)", input => { + util.testFunction` let a = 5; let b = 3; ${input}; return a; `.expectToMatchJsResult(); - } -); +}); const supportedInAll = ["~a", "a&b", "a&=b", "a|b", "a|=b", "a^b", "a^=b", "a<>>b", "a>>>=b"]; const unsupportedIn53 = ["a>>b", "a>>=b"]; const allBinaryOperators = [...supportedInAll, ...unsupportedIn53]; -test.each(allBinaryOperators)("Bitop [5.1] (%p)", (input) => { +test.each(allBinaryOperators)("Bitop [5.1] (%p)", input => { // Bit operations not supported in 5.1, expect an exception util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua51, luaLibImport: tstl.LuaLibImportKind.None }) @@ -61,28 +58,28 @@ test.each(allBinaryOperators)("Bitop [5.1] (%p)", (input) => { .expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]); }); -test.each(allBinaryOperators)("Bitop [JIT] (%p)", (input) => { +test.each(allBinaryOperators)("Bitop [JIT] (%p)", input => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.LuaJIT, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(allBinaryOperators)("Bitop [5.2] (%p)", (input) => { +test.each(allBinaryOperators)("Bitop [5.2] (%p)", input => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua52, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(supportedInAll)("Bitop [5.3] (%p)", (input) => { +test.each(supportedInAll)("Bitop [5.3] (%p)", input => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua53, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() .expectLuaToMatchSnapshot(); }); -test.each(unsupportedIn53)("Unsupported bitop 5.3 (%p)", (input) => { +test.each(unsupportedIn53)("Unsupported bitop 5.3 (%p)", input => { util.testExpression(input) .setOptions({ luaTarget: tstl.LuaTarget.Lua53, luaLibImport: tstl.LuaLibImportKind.None }) .disableSemanticCheck() @@ -91,7 +88,7 @@ test.each(unsupportedIn53)("Unsupported bitop 5.3 (%p)", (input) => { test.each(["1+1", "-1+1", "1*30+4", "1*(3+4)", "1*(3+4*2)", "10-(4+5)"])( "Binary expressions ordering parentheses (%p)", - (input) => { + input => { util.testExpression(input).expectLuaToMatchSnapshot(); } ); @@ -104,7 +101,7 @@ test("Assignment order of operations is preserved", () => { `.expectToMatchJsResult(); }); -test.each(["bar(),foo()", "foo(),bar()", "foo(),bar(),baz()"])("Binary Comma (%p)", (input) => { +test.each(["bar(),foo()", "foo(),bar()", "foo(),bar(),baz()"])("Binary Comma (%p)", input => { util.testFunction` function foo() { return 1; } function bar() { return 2; }; @@ -129,7 +126,7 @@ test("Undefined Expression", () => { expect(util.transpileString("undefined")).toBe("local ____ = nil"); }); -test.each(["i++", "i--", "++i", "--i"])("Incrementor value (%p)", (expression) => { +test.each(["i++", "i--", "++i", "--i"])("Incrementor value (%p)", expression => { util.testFunction` let i = 10; return ${expression}; @@ -160,7 +157,7 @@ test.each([ "Math.log2(2)", "Math.log10(2)", '"".indexOf("")', -])("Expression statements (%p)", (input) => { +])("Expression statements (%p)", input => { util.testFunction` function foo() { return 17; } const bar = { foo }; diff --git a/test/unit/functions/functions.spec.ts b/test/unit/functions/functions.spec.ts index 9384c3dec..2f2f3b212 100644 --- a/test/unit/functions/functions.spec.ts +++ b/test/unit/functions/functions.spec.ts @@ -14,7 +14,7 @@ test("Returning arrow function from arrow function", () => { `.expectToMatchJsResult(); }); -test.each(["i++", "i--", "++i", "--i"])("Arrow function unary expression (%p)", (lambda) => { +test.each(["i++", "i--", "++i", "--i"])("Arrow function unary expression (%p)", lambda => { util.testFunction` let i = 10; [1,2,3,4,5].forEach(() => ${lambda}); @@ -24,7 +24,7 @@ test.each(["i++", "i--", "++i", "--i"])("Arrow function unary expression (%p)", test.each(["b => a = b", "b => a += b", "b => a -= b", "b => a *= b", "b => a /= b", "b => a **= b", "b => a %= b"])( "Arrow function assignment (%p)", - (lambda) => { + lambda => { util.testFunction` let a = 10; let lambda = ${lambda}; @@ -351,7 +351,7 @@ test("Complex element access call statement", () => { `.expectToMatchJsResult(); }); -test.each([1, 2])("Generator functions value (%p)", (iterations) => { +test.each([1, 2])("Generator functions value (%p)", iterations => { util.testFunction` function* seq(value: number) { let a = yield value + 1; @@ -366,7 +366,7 @@ test.each([1, 2])("Generator functions value (%p)", (iterations) => { `.expectToMatchJsResult(); }); -test.each([1, 2])("Generator functions done (%p)", (iterations) => { +test.each([1, 2])("Generator functions done (%p)", iterations => { util.testFunction` function* seq(value: number) { let a = yield value + 1; @@ -473,7 +473,7 @@ test("Function rest parameter (unreferenced)", () => { } return foo("A", "B", "C", "D"); ` - .tap((builder) => expect(builder.getMainLuaCodeChunk()).not.toMatch("{...}")) + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("{...}")) .expectToMatchJsResult(); }); diff --git a/test/unit/functions/noImplicitSelfOption.spec.ts b/test/unit/functions/noImplicitSelfOption.spec.ts index eba51eaae..f61e37cb2 100644 --- a/test/unit/functions/noImplicitSelfOption.spec.ts +++ b/test/unit/functions/noImplicitSelfOption.spec.ts @@ -28,7 +28,7 @@ test("generates declaration files with @noSelfInFile", () => { .setOptions({ declaration: true, noImplicitSelf: true }) .expectToHaveNoDiagnostics(); - const fooDeclaration = fooBuilder.getLuaResult().transpiledFiles.find((f) => f.declaration)?.declaration; + const fooDeclaration = fooBuilder.getLuaResult().transpiledFiles.find(f => f.declaration)?.declaration; util.assert(fooDeclaration !== undefined); util.testModule` diff --git a/test/unit/functions/noSelfAnnotation.spec.ts b/test/unit/functions/noSelfAnnotation.spec.ts index 96abcb1ed..ab77ec03e 100644 --- a/test/unit/functions/noSelfAnnotation.spec.ts +++ b/test/unit/functions/noSelfAnnotation.spec.ts @@ -10,7 +10,7 @@ test("@noSelf on declared function removes context argument", () => { `.expectLuaToMatchSnapshot(); }); -test.each(methodHolders)("@noSelf on method inside %s declaration removes context argument", (holderType) => { +test.each(methodHolders)("@noSelf on method inside %s declaration removes context argument", holderType => { util.testModule` declare ${holderType} MethodHolder { /** @noSelf */ @@ -21,7 +21,7 @@ test.each(methodHolders)("@noSelf on method inside %s declaration removes contex `.expectLuaToMatchSnapshot(); }); -test.each(methodHolders)("@noSelf on parent %s declaration removes context argument", (holderType) => { +test.each(methodHolders)("@noSelf on parent %s declaration removes context argument", holderType => { util.testModule` /** @noSelf */ declare ${holderType} MethodHolder { diff --git a/test/unit/functions/validation/functionExpressionTypeInference.spec.ts b/test/unit/functions/validation/functionExpressionTypeInference.spec.ts index a1eba6a70..e475f2216 100644 --- a/test/unit/functions/validation/functionExpressionTypeInference.spec.ts +++ b/test/unit/functions/validation/functionExpressionTypeInference.spec.ts @@ -1,6 +1,6 @@ import * as util from "../../../util"; -test.each(["noSelf", "noSelfInFile"])("noSelf function method argument (%p)", (noSelfTag) => { +test.each(["noSelf", "noSelfInFile"])("noSelf function method argument (%p)", noSelfTag => { const header = ` /** @${noSelfTag} */ namespace NS { export class C { @@ -29,7 +29,7 @@ test("noSelfInFile works when first statement has other annotations", () => { test.each(["(this: void, s: string) => string", "(this: any, s: string) => string", "(s: string) => string"])( "Function expression type inference in binary operator (%p)", - (funcType) => { + funcType => { const header = `declare const undefinedFunc: ${funcType};`; const code = ` let func: ${funcType} = s => s; @@ -42,7 +42,7 @@ test.each(["(this: void, s: string) => string", "(this: any, s: string) => strin test.each(["s => s", "(s => s)", "function(s) { return s; }", "(function(s) { return s; })"])( "Function expression type inference in class (%p)", - (funcExp) => { + funcExp => { const code = ` class Foo { func: (this: void, s: string) => string = ${funcExp}; diff --git a/test/unit/functions/validation/invalidFunctionAssignments.spec.ts b/test/unit/functions/validation/invalidFunctionAssignments.spec.ts index 4a039dd64..7d678496b 100644 --- a/test/unit/functions/validation/invalidFunctionAssignments.spec.ts +++ b/test/unit/functions/validation/invalidFunctionAssignments.spec.ts @@ -155,7 +155,7 @@ test.each([ "(this: void, s1: string, s2: string) => string", "{(this: void, s: string): string}", "{(this: any, s1: string, s2: string): string}", -])("Invalid function overload assignment (%p)", (assignType) => { +])("Invalid function overload assignment (%p)", assignType => { util.testModule` interface O { (this: any, s1: string, s2: string): string; diff --git a/test/unit/functions/validation/validFunctionAssignments.spec.ts b/test/unit/functions/validation/validFunctionAssignments.spec.ts index 70947b027..a491ccd7b 100644 --- a/test/unit/functions/validation/validFunctionAssignments.spec.ts +++ b/test/unit/functions/validation/validFunctionAssignments.spec.ts @@ -180,7 +180,7 @@ test.each([ } const o: O = (s1: string, s2?: string) => s1 + (s2 || "bar"); let f: ${assignType} = o; - return f(${args.map((a) => '"' + a + '"').join(", ")});`; + return f(${args.map(a => '"' + a + '"').join(", ")});`; const result = util.transpileAndExecute(code); expect(result).toBe(expectResult); }); diff --git a/test/unit/hoisting.spec.ts b/test/unit/hoisting.spec.ts index 17a192b29..997c53f73 100644 --- a/test/unit/hoisting.spec.ts +++ b/test/unit/hoisting.spec.ts @@ -1,7 +1,7 @@ import * as ts from "typescript"; import * as util from "../util"; -test.each(["let", "const"])("Let/Const Hoisting (%p)", (varType) => { +test.each(["let", "const"])("Let/Const Hoisting (%p)", varType => { const code = ` let bar: string; function setBar() { bar = foo; } @@ -13,7 +13,7 @@ test.each(["let", "const"])("Let/Const Hoisting (%p)", (varType) => { expect(result).toBe("foo"); }); -test.each(["let", "const"])("Exported Let/Const Hoisting (%p)", (varType) => { +test.each(["let", "const"])("Exported Let/Const Hoisting (%p)", varType => { const code = ` let bar: string; function setBar() { bar = foo; } @@ -115,7 +115,7 @@ test("Hoisting with synthetic source file node", () => { ` .setCustomTransformers({ before: [ - () => (sourceFile) => + () => sourceFile => ts.updateSourceFileNode( sourceFile, [ts.createNotEmittedStatement(undefined!), ...sourceFile.statements], diff --git a/test/unit/identifiers.spec.ts b/test/unit/identifiers.spec.ts index 4622d9467..27046c81b 100644 --- a/test/unit/identifiers.spec.ts +++ b/test/unit/identifiers.spec.ts @@ -19,35 +19,35 @@ const validTsInvalidLuaKeywordNames = [ const invalidLuaNames = [...invalidLuaCharNames, ...luaKeywords]; const validTsInvalidLuaNames = [...invalidLuaCharNames, ...validTsInvalidLuaKeywordNames]; -test.each(validTsInvalidLuaNames)("invalid lua identifier name (%p)", (name) => { +test.each(validTsInvalidLuaNames)("invalid lua identifier name (%p)", name => { util.testFunction` const ${name} = "foobar"; return ${name}; `.expectToMatchJsResult(); }); -test.each([...luaKeywords.values()])("lua keyword as property name (%p)", (keyword) => { +test.each([...luaKeywords.values()])("lua keyword as property name (%p)", keyword => { util.testFunction` const x = { ${keyword}: "foobar" }; return x.${keyword}; `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaKeywordNames)("destructuring lua keyword (%p)", (keyword) => { +test.each(validTsInvalidLuaKeywordNames)("destructuring lua keyword (%p)", keyword => { util.testFunction` const { foo: ${keyword} } = { foo: "foobar" }; return ${keyword}; `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaKeywordNames)("destructuring shorthand lua keyword (%p)", (keyword) => { +test.each(validTsInvalidLuaKeywordNames)("destructuring shorthand lua keyword (%p)", keyword => { util.testFunction` const { ${keyword} } = { ${keyword}: "foobar" }; return ${keyword}; `.expectToMatchJsResult(); }); -test.each(invalidLuaNames)("lua keyword or invalid identifier as method call (%p)", (name) => { +test.each(invalidLuaNames)("lua keyword or invalid identifier as method call (%p)", name => { util.testFunction` const foo = { ${name}(arg: string) { return "foo" + arg; } @@ -56,7 +56,7 @@ test.each(invalidLuaNames)("lua keyword or invalid identifier as method call (%p `.expectToMatchJsResult(); }); -test.each(invalidLuaNames)("lua keyword or invalid identifier as complex method call (%p)", (name) => { +test.each(invalidLuaNames)("lua keyword or invalid identifier as complex method call (%p)", name => { util.testFunction` const foo = { ${name}(arg: string) { return "foo" + arg; } @@ -76,7 +76,7 @@ test.each([ "module local { export const bar: any; }", "enum local {}", "function local() {}", -])("ambient identifier cannot be a lua keyword (%p)", (statement) => { +])("ambient identifier cannot be a lua keyword (%p)", statement => { util.testModule` declare ${statement} local; @@ -95,7 +95,7 @@ test.each([ "module $$$ { export const bar: any; }", "enum $$$ {}", "function $$$();", -])("ambient identifier must be a valid lua identifier (%p)", (statement) => { +])("ambient identifier must be a valid lua identifier (%p)", statement => { util.testModule` declare ${statement} $$$; @@ -104,7 +104,7 @@ test.each([ test.each(validTsInvalidLuaNames)( "ambient identifier must be a valid lua identifier (object literal shorthand) (%p)", - (name) => { + name => { util.testModule` declare var ${name}: any; const foo = { ${name} }; @@ -112,7 +112,7 @@ test.each(validTsInvalidLuaNames)( } ); -test.each(validTsInvalidLuaNames)("undeclared identifier must be a valid lua identifier (%p)", (name) => { +test.each(validTsInvalidLuaNames)("undeclared identifier must be a valid lua identifier (%p)", name => { util.testModule` const foo = ${name}; ` @@ -122,7 +122,7 @@ test.each(validTsInvalidLuaNames)("undeclared identifier must be a valid lua ide test.each(validTsInvalidLuaNames)( "undeclared identifier must be a valid lua identifier (object literal shorthand) (%p)", - (name) => { + name => { util.testModule` const foo = { ${name} }; ` @@ -131,7 +131,7 @@ test.each(validTsInvalidLuaNames)( } ); -test.each(validTsInvalidLuaNames)("exported values with invalid lua identifier names (%p)", (name) => { +test.each(validTsInvalidLuaNames)("exported values with invalid lua identifier names (%p)", name => { const code = `export const ${name} = "foobar";`; const lua = util.transpileString(code); expect(lua.indexOf(`"${name}"`)).toBeGreaterThanOrEqual(0); @@ -174,7 +174,7 @@ test("exported identifiers referenced in nested scope (%p)", () => { test.each(validTsInvalidLuaNames)( "exported values with invalid lua identifier names referenced in different scope (%p)", - (name) => { + name => { const code = ` export const ${name} = "foobar"; namespace NS { @@ -185,14 +185,14 @@ test.each(validTsInvalidLuaNames)( } ); -test.each(validTsInvalidLuaNames)("class with invalid lua name has correct name property", (name) => { +test.each(validTsInvalidLuaNames)("class with invalid lua name has correct name property", name => { util.testFunction` class ${name} {} return ${name}.name; `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaNames)("decorated class with invalid lua name", (name) => { +test.each(validTsInvalidLuaNames)("decorated class with invalid lua name", name => { util.testFunction` function decorator(c: T): T { c.bar = "foobar"; @@ -205,7 +205,7 @@ test.each(validTsInvalidLuaNames)("decorated class with invalid lua name", (name `.expectToMatchJsResult(); }); -test.each(validTsInvalidLuaNames)("exported decorated class with invalid lua name", (name) => { +test.each(validTsInvalidLuaNames)("exported decorated class with invalid lua name", name => { const code = ` function decorator(c: T): T { c.bar = "foobar"; @@ -573,7 +573,7 @@ describe("lua keyword as identifier doesn't interfere with lua's value", () => { expect(util.transpileAndExecute(code)).toBe("foobar|string"); }); - test.each(["type", "type as type"])("imported variable (%p)", (importName) => { + test.each(["type", "type as type"])("imported variable (%p)", importName => { const luaHeader = ` package.loaded.someModule = {type = "foobar"}`; @@ -602,7 +602,7 @@ describe("lua keyword as identifier doesn't interfere with lua's value", () => { expect(util.transpileExecuteAndReturnExport(code, returnExport)).toBe(expectResult); }); - test.each(["type", "type as type"])("re-exported variable with lua keyword as name (%p)", (importName) => { + test.each(["type", "type as type"])("re-exported variable with lua keyword as name (%p)", importName => { const code = ` export { ${importName} } from "someModule"`; diff --git a/test/unit/json.spec.ts b/test/unit/json.spec.ts index d8061eca4..2f4b0d6a5 100644 --- a/test/unit/json.spec.ts +++ b/test/unit/json.spec.ts @@ -1,6 +1,6 @@ import * as util from "../util"; -test.each([0, "", [], [1, "2", []], { a: "b" }, { a: { b: "c" } }])("JSON (%p)", (json) => { +test.each([0, "", [], [1, "2", []], { a: "b" }, { a: { b: "c" } }])("JSON (%p)", json => { util.testModule(JSON.stringify(json)).setMainFileName("main.json").expectToEqual(json); }); diff --git a/test/unit/loops.spec.ts b/test/unit/loops.spec.ts index c01f92afa..172150c47 100644 --- a/test/unit/loops.spec.ts +++ b/test/unit/loops.spec.ts @@ -526,11 +526,11 @@ for (const testCase of [ "for (const a in {}) { continue; }", "for (const a of []) { continue; }", ]) { - const expectContinueGotoLabel: util.TapCallback = (builder) => + const expectContinueGotoLabel: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toMatch("::__continue2::"); util.testEachVersion(`loop continue (${testCase})`, () => util.testModule(testCase), { - [tstl.LuaTarget.Lua51]: (builder) => builder.expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]), + [tstl.LuaTarget.Lua51]: builder => builder.expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]), [tstl.LuaTarget.Lua52]: expectContinueGotoLabel, [tstl.LuaTarget.Lua53]: expectContinueGotoLabel, [tstl.LuaTarget.LuaJIT]: expectContinueGotoLabel, diff --git a/test/unit/modules/modules.spec.ts b/test/unit/modules/modules.spec.ts index 8c973bb69..885f24541 100644 --- a/test/unit/modules/modules.spec.ts +++ b/test/unit/modules/modules.spec.ts @@ -9,7 +9,7 @@ describe("module import/export elision", () => { } `; - const expectToElideImport: util.TapCallback = (builder) => { + const expectToElideImport: util.TapCallback = builder => { builder.addExtraFile("module.d.ts", moduleDeclaration).setOptions({ module: ts.ModuleKind.CommonJS }); expect(builder.getLuaExecutionResult()).not.toBeInstanceOf(util.ExecutionError); }; @@ -53,7 +53,7 @@ describe("module import/export elision", () => { test.each(["ke-bab", "dollar$", "singlequote'", "hash#", "s p a c e", "ɥɣɎɌͼƛಠ", "_̀ः٠‿"])( "Import module names with invalid lua identifier characters (%p)", - (name) => { + name => { util.testModule` import { foo } from "./${name}"; export { foo }; @@ -65,7 +65,7 @@ test.each(["ke-bab", "dollar$", "singlequote'", "hash#", "s p a c e", "ɥɣɎɌ } ); -test.each(["export default value;", "export { value as default };"])("Export Default From (%p)", (exportStatement) => { +test.each(["export default value;", "export { value as default };"])("Export Default From (%p)", exportStatement => { const [result] = util.transpileAndExecuteProjectReturningMainExport( { "main.ts": ` @@ -203,7 +203,7 @@ const reassignmentTestCases = [ "({ x = 1 } = { x: undefined })", ]; -test.each(reassignmentTestCases)("export specifier with reassignment afterwards (%p)", (reassignment) => { +test.each(reassignmentTestCases)("export specifier with reassignment afterwards (%p)", reassignment => { util.testModule` let x = 0; export { x }; @@ -211,7 +211,7 @@ test.each(reassignmentTestCases)("export specifier with reassignment afterwards `.expectToMatchJsResult(); }); -test.each(reassignmentTestCases)("export specifier fork (%p)", (reassignment) => { +test.each(reassignmentTestCases)("export specifier fork (%p)", reassignment => { util.testModule` let x = 0; export { x as a }; diff --git a/test/unit/modules/resolution.spec.ts b/test/unit/modules/resolution.spec.ts index 5ebf569f1..541c28c56 100644 --- a/test/unit/modules/resolution.spec.ts +++ b/test/unit/modules/resolution.spec.ts @@ -3,7 +3,7 @@ import { unresolvableRequirePath } from "../../../src/transformation/utils/diagn import * as util from "../../util"; const requireRegex = /require\("(.*?)"\)/; -const expectToRequire = (expected: string): util.TapCallback => (builder) => { +const expectToRequire = (expected: string): util.TapCallback => builder => { const [, requiredPath] = builder.getMainLuaCodeChunk().match(requireRegex) ?? []; expect(requiredPath).toBe(expected); }; diff --git a/test/unit/nullishCoalescing.spec.ts b/test/unit/nullishCoalescing.spec.ts index 0064e856b..67dbc1cec 100644 --- a/test/unit/nullishCoalescing.spec.ts +++ b/test/unit/nullishCoalescing.spec.ts @@ -1,14 +1,14 @@ import * as util from "../util"; -test.each(["null", "undefined"])("nullish-coalesing operator returns rhs", (nullishValue) => { +test.each(["null", "undefined"])("nullish-coalesing operator returns rhs", nullishValue => { util.testExpression`${nullishValue} ?? "Hello, World!"`.expectToMatchJsResult(); }); -test.each([3, "foo", {}, [], true, false])("nullish-coalesing operator returns lhs", (value) => { +test.each([3, "foo", {}, [], true, false])("nullish-coalesing operator returns lhs", value => { util.testExpression`${util.formatCode(value)} ?? "Hello, World!"`.expectToMatchJsResult(); }); -test.each(["any", "unknown"])("nullish-coalesing operator with any/unknown type", (type) => { +test.each(["any", "unknown"])("nullish-coalesing operator with any/unknown type", type => { util.testFunction` const unknownType = false as ${type}; return unknownType ?? "This should not be returned!"; @@ -17,7 +17,7 @@ test.each(["any", "unknown"])("nullish-coalesing operator with any/unknown type" test.each(["boolean | string", "number | false", "undefined | true"])( "nullish-coalesing operator with union type", - (unionType) => { + unionType => { util.testFunction` const unknownType = false as ${unionType}; return unknownType ?? "This should not be returned!"; diff --git a/test/unit/objectLiteral.spec.ts b/test/unit/objectLiteral.spec.ts index 42c9545b9..819143e1f 100644 --- a/test/unit/objectLiteral.spec.ts +++ b/test/unit/objectLiteral.spec.ts @@ -2,7 +2,7 @@ import * as util from "../util"; test.each(['{ a: 3, b: "4" }', '{ "a": 3, b: "4" }', '{ ["a"]: 3, b: "4" }', '{ ["a" + 123]: 3, b: "4" }'])( "Object Literal (%p)", - (inp) => { + inp => { util.testExpression(inp).expectToMatchJsResult(); } ); @@ -30,7 +30,7 @@ describe("property shorthand", () => { `.expectToMatchJsResult(); }); - test.each([NaN, Infinity])("should support %p shorthand", (identifier) => { + test.each([NaN, Infinity])("should support %p shorthand", identifier => { util.testExpression`({ ${identifier} }).${identifier}`.expectToMatchJsResult(); }); @@ -59,7 +59,7 @@ test("undefined as object key", () => { test.each(['{x: "foobar"}.x', '{x: "foobar"}["x"]', '{x: () => "foobar"}.x()', '{x: () => "foobar"}["x"]()'])( "object literal property access (%p)", - (expression) => { + expression => { util.testExpression(expression).expectToMatchJsResult(); } ); diff --git a/test/unit/printer/parenthesis.spec.ts b/test/unit/printer/parenthesis.spec.ts index d791d73e4..ef08a6e3d 100644 --- a/test/unit/printer/parenthesis.spec.ts +++ b/test/unit/printer/parenthesis.spec.ts @@ -19,7 +19,7 @@ test.each([ "(x as any).foo;", "((x as unknown) as any).foo;", "((x) as any).foo;", -])("'as' type assertion should strip parenthesis (%p)", (expression) => { +])("'as' type assertion should strip parenthesis (%p)", expression => { const code = ` declare let x: unknown; declare let y: { x: unknown; z(this: void): unknown; }; @@ -44,7 +44,7 @@ test.each([ "((!x as unknown) as any).foo;", "(!x as any).foo;", "((!x) as any).foo;", -])("'as' type assertion should not strip parenthesis (%p)", (expression) => { +])("'as' type assertion should not strip parenthesis (%p)", expression => { const code = ` declare let x: number; declare let y: {}; diff --git a/test/unit/printer/semicolons.spec.ts b/test/unit/printer/semicolons.spec.ts index a3dc7e017..addb66e53 100644 --- a/test/unit/printer/semicolons.spec.ts +++ b/test/unit/printer/semicolons.spec.ts @@ -2,7 +2,7 @@ import * as util from "../../util"; test.each(["const a = 1; const b = a;", "const a = 1; let b: number; b = a;", "{}", "function bar() {} bar();"])( "semicolon insertion (%p)", - (leadingStatement) => { + leadingStatement => { util.testFunction` let result = ""; function foo() { result = "foo"; } diff --git a/test/unit/printer/sourcemaps.spec.ts b/test/unit/printer/sourcemaps.spec.ts index db14745a9..96ffec05f 100644 --- a/test/unit/printer/sourcemaps.spec.ts +++ b/test/unit/printer/sourcemaps.spec.ts @@ -230,7 +230,7 @@ test.each([ const consumer = await new SourceMapConsumer(file.sourceMap); const typescriptPosition = lineAndColumnOf(code, name); let mappedName: string | undefined; - consumer.eachMapping((mapping) => { + consumer.eachMapping(mapping => { if (mapping.originalLine === typescriptPosition.line && mapping.originalColumn === typescriptPosition.column) { mappedName = mapping.name; } @@ -307,7 +307,7 @@ function lineAndColumnOf(text: string, pattern: string): Position { return { line: -1, column: -1 }; } - const lineLengths = text.split("\n").map((s) => s.length); + const lineLengths = text.split("\n").map(s => s.length); let totalPos = 0; for (let line = 1; line <= lineLengths.length; line++) { diff --git a/test/unit/spread.spec.ts b/test/unit/spread.spec.ts index 405a1a826..dec923d83 100644 --- a/test/unit/spread.spec.ts +++ b/test/unit/spread.spec.ts @@ -3,9 +3,8 @@ import * as util from "../util"; import { formatCode } from "../util"; // TODO: Make some utils for testing other targets -const expectUnpack: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toMatch(/[^.]unpack\(/); -const expectTableUnpack: util.TapCallback = (builder) => - expect(builder.getMainLuaCodeChunk()).toContain("table.unpack"); +const expectUnpack: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toMatch(/[^.]unpack\(/); +const expectTableUnpack: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toContain("table.unpack"); const arrayLiteralCases = [ "1, 2, ...[3, 4, 5]", @@ -15,14 +14,14 @@ const arrayLiteralCases = [ "1, 2, ...[3, 4], ...[5, 6]", ]; -describe.each(["function call", "array literal"] as const)("in %s", (kind) => { +describe.each(["function call", "array literal"] as const)("in %s", kind => { const factory = (code: string) => (kind === "function call" ? `((...args: any[]) => args)(${code})` : `[${code}]`); - test.each(arrayLiteralCases)("of array literal (%p)", (expression) => { + test.each(arrayLiteralCases)("of array literal (%p)", expression => { util.testExpression(factory(expression)).expectToMatchJsResult(); }); - test.each(arrayLiteralCases)("of tuple return call (%p)", (expression) => { + test.each(arrayLiteralCases)("of tuple return call (%p)", expression => { util.testFunction` /** @tupleReturn */ function tuple(...args: any[]) { @@ -37,7 +36,7 @@ describe.each(["function call", "array literal"] as const)("in %s", (kind) => { util.testExpression(factory('..."spread", ..."string"')).expectToMatchJsResult(); }); - test.each(["", "string", "string with spaces", "string 1 2 3"])("of string literal (%p)", (str) => { + test.each(["", "string", "string with spaces", "string 1 2 3"])("of string literal (%p)", str => { util.testExpression(factory(`...${formatCode(str)}`)).expectToMatchJsResult(); }); @@ -73,20 +72,20 @@ describe("in function call", () => { return foo(...array); `, { - [tstl.LuaTarget.LuaJIT]: (builder) => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua51]: (builder) => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua52]: (builder) => builder.tap(expectTableUnpack), - [tstl.LuaTarget.Lua53]: (builder) => builder.tap(expectTableUnpack).expectToMatchJsResult(), + [tstl.LuaTarget.LuaJIT]: builder => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua51]: builder => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua52]: builder => builder.tap(expectTableUnpack), + [tstl.LuaTarget.Lua53]: builder => builder.tap(expectTableUnpack).expectToMatchJsResult(), } ); }); describe("in array literal", () => { util.testEachVersion(undefined, () => util.testExpression`[...[0, 1, 2]]`, { - [tstl.LuaTarget.LuaJIT]: (builder) => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua51]: (builder) => builder.tap(expectUnpack), - [tstl.LuaTarget.Lua52]: (builder) => builder.tap(expectTableUnpack), - [tstl.LuaTarget.Lua53]: (builder) => builder.tap(expectTableUnpack).expectToMatchJsResult(), + [tstl.LuaTarget.LuaJIT]: builder => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua51]: builder => builder.tap(expectUnpack), + [tstl.LuaTarget.Lua52]: builder => builder.tap(expectTableUnpack), + [tstl.LuaTarget.Lua53]: builder => builder.tap(expectTableUnpack).expectToMatchJsResult(), }); test("of array literal /w OmittedExpression", () => { @@ -104,7 +103,7 @@ describe("in object literal", () => { "{ ...{ x: true }, ...{ y: true, z: true } }", "{ ...{ x: false }, x: true }", "{ ...{ x: false }, x: false, ...{ x: true } }", - ])("of object literal (%p)", (expression) => { + ])("of object literal (%p)", expression => { util.testExpression(expression).expectToMatchJsResult(); }); diff --git a/test/unit/templateLiterals.spec.ts b/test/unit/templateLiterals.spec.ts index 6a5aa5777..7db192a88 100644 --- a/test/unit/templateLiterals.spec.ts +++ b/test/unit/templateLiterals.spec.ts @@ -11,19 +11,16 @@ test.each([ util.testExpressionTemplate`\`\${${a}} \${${b}} test \${${c}}\``.expectToMatchJsResult(); }); -test.each(["a++", "a--", "--a", "++a"])("template literal with expression (%p)", (expression) => { +test.each(["a++", "a--", "--a", "++a"])("template literal with expression (%p)", expression => { util.testFunction` let a = 3; return \`value\${${expression}}\`; `.expectToMatchJsResult(); }); -test.each(["`foo${'bar'}`.length", "`foo${'bar'}`.repeat(2)"])( - "template literal property access (%p)", - (expression) => { - util.testExpression(expression).expectToMatchJsResult(); - } -); +test.each(["`foo${'bar'}`.length", "`foo${'bar'}`.repeat(2)"])("template literal property access (%p)", expression => { + util.testExpression(expression).expectToMatchJsResult(); +}); test.each([ "func``", @@ -39,7 +36,7 @@ test.each([ "func`hello \\``", "obj.func`hello ${'propertyAccessExpression'}`", "obj['func']`hello ${'elementAccessExpression'}`", -])("tagged template literal (%p)", (expression) => { +])("tagged template literal (%p)", expression => { util.testFunction` function func(strings: TemplateStringsArray, ...expressions: any[]) { return { strings: [...strings], raw: strings.raw, expressions }; @@ -52,7 +49,7 @@ test.each([ test.each(["func`noSelfParameter`", "obj.func`noSelfParameter`", "obj[`func`]`noSelfParameter`"])( "tagged template literal function context (%p)", - (expression) => { + expression => { util.testFunction` function func(this: void, strings: TemplateStringsArray) { return [...strings]; diff --git a/test/unit/typeof.spec.ts b/test/unit/typeof.spec.ts index 28bbbce1e..f8a063c1c 100644 --- a/test/unit/typeof.spec.ts +++ b/test/unit/typeof.spec.ts @@ -1,18 +1,18 @@ import * as util from "../util"; -test.each(["0", "30", "30_000", "30.00"])("typeof number (%p)", (inp) => { +test.each(["0", "30", "30_000", "30.00"])("typeof number (%p)", inp => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); -test.each(['"abc"', "`abc`"])("typeof string (%p)", (inp) => { +test.each(['"abc"', "`abc`"])("typeof string (%p)", inp => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); -test.each(["false", "true"])("typeof boolean (%p)", (inp) => { +test.each(["false", "true"])("typeof boolean (%p)", inp => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); -test.each(["{}", "[]"])("typeof object literal (%p)", (inp) => { +test.each(["{}", "[]"])("typeof object literal (%p)", inp => { util.testExpression`typeof ${inp}`.expectToMatchJsResult(); }); @@ -34,7 +34,7 @@ test("typeof function", () => { util.testExpression`typeof (() => 3)`.expectToMatchJsResult(); }); -test.each(["null", "undefined"])("typeof %s", (inp) => { +test.each(["null", "undefined"])("typeof %s", inp => { util.testExpression`typeof ${inp}`.expectToEqual("undefined"); }); @@ -63,8 +63,8 @@ const relationalComparisonCases: ComparisonCase[] = [ { expression: "undefined", operator: ">", compareTo: "object" }, ]; -const expectTypeOfHelper: util.TapCallback = (builder) => expect(builder.getMainLuaCodeChunk()).toMatch("__TS__TypeOf"); -const expectNoTypeOfHelper: util.TapCallback = (builder) => +const expectTypeOfHelper: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).toMatch("__TS__TypeOf"); +const expectNoTypeOfHelper: util.TapCallback = builder => expect(builder.getMainLuaCodeChunk()).not.toMatch("__TS__TypeOf"); test.each(equalityComparisonCases)("typeof literal equality comparison (%p)", ({ expression, operator, compareTo }) => { diff --git a/test/util.ts b/test/util.ts index b1d993b08..aadf50079 100644 --- a/test/util.ts +++ b/test/util.ts @@ -18,7 +18,7 @@ export function assert(value: any, message?: string | Error): asserts value { nativeAssert(value, message); } -export const formatCode = (...values: unknown[]) => values.map((e) => stringify(e)).join(", "); +export const formatCode = (...values: unknown[]) => values.map(e => stringify(e)).join(", "); export function testEachVersion( name: string | undefined, @@ -54,7 +54,7 @@ interface TranspileJsResult { function transpileJs(program: ts.Program): TranspileJsResult { const transpiledFiles: TranspiledJsFile[] = []; const updateTranspiledFile = (fileName: string, update: Omit) => { - const file = transpiledFiles.find((f) => f.fileName === fileName); + const file = transpiledFiles.find(f => f.fileName === fileName); if (file) { Object.assign(file, update); } else { @@ -92,7 +92,7 @@ function executeLua(code: string): any { } } else { // Filter out control characters appearing on some systems - const luaStackString = lua.lua_tostring(L, -1).filter((c) => c >= 20); + const luaStackString = lua.lua_tostring(L, -1).filter(c => c >= 20); const message = to_jsstring(luaStackString).replace(/^\[string "--\.\.\."\]:\d+: /, ""); return new ExecutionError(message); } @@ -279,7 +279,7 @@ export abstract class TestBuilder { const { transpiledFiles } = this.getLuaResult(); const mainFile = this.options.luaBundle ? transpiledFiles[0] - : transpiledFiles.find((x) => x.fileName === this.mainFileName); + : transpiledFiles.find(x => x.fileName === this.mainFileName); expect(mainFile).toMatchObject({ lua: expect.any(String), sourceMap: expect.any(String) }); return mainFile as ExecutableTranspiledFile; } @@ -305,7 +305,7 @@ export abstract class TestBuilder { @memoize protected getMainJsCodeChunk(): string { const { transpiledFiles } = this.getJsResult(); - const code = transpiledFiles.find((x) => x.fileName === this.mainFileName)?.js; + const code = transpiledFiles.find(x => x.fileName === this.mainFileName)?.js; assert(code !== undefined); const header = this.jsHeader ? `${this.jsHeader.trimRight()}\n` : ""; @@ -323,7 +323,7 @@ export abstract class TestBuilder { private getLuaDiagnostics(): ts.Diagnostic[] { const { diagnostics } = this.getLuaResult(); - return diagnostics.filter((d) => this.semanticCheck || d.source === "typescript-to-lua"); + return diagnostics.filter(d => this.semanticCheck || d.source === "typescript-to-lua"); } // Actions @@ -391,7 +391,7 @@ export abstract class TestBuilder { const diagnosticMessages = ts.formatDiagnostics( this.getLuaDiagnostics().map(tstl.prepareDiagnosticForFormatting), - { getCurrentDirectory: () => "", getCanonicalFileName: (fileName) => fileName, getNewLine: () => "\n" } + { getCurrentDirectory: () => "", getCanonicalFileName: fileName => fileName, getNewLine: () => "\n" } ); expect(diagnosticMessages.trim()).toMatchSnapshot("diagnostics"); @@ -463,7 +463,7 @@ const createTestBuilderFactory = ( } else { let [raw, ...substitutions] = args; if (serializeSubstitutions) { - substitutions = substitutions.map((s) => formatCode(s)); + substitutions = substitutions.map(s => formatCode(s)); } tsCode = String.raw(Object.assign([], { raw }), ...substitutions);