From 32de69830339fc7b9fa698b2e0ec3d48baeee675 Mon Sep 17 00:00:00 2001 From: Perryvw Date: Thu, 10 Jan 2019 22:49:14 +0100 Subject: [PATCH 1/3] Restored max line length and no trailing whitespace rule --- .clang-format | 2 +- src/CommandLineParser.ts | 14 ++++- src/Compiler.ts | 8 ++- src/LuaAST.ts | 131 ++++++++++++++++++++++++++++++++------- src/LuaPrinter.ts | 2 +- src/LuaTranspiler.ts | 10 ++- src/TSHelper.ts | 61 +++++++++++++----- src/TSTLErrors.ts | 12 ++-- tslint.json | 2 + 9 files changed, 191 insertions(+), 51 deletions(-) diff --git a/.clang-format b/.clang-format index a5523b43a..86f293429 100644 --- a/.clang-format +++ b/.clang-format @@ -19,7 +19,7 @@ BreakBeforeBraces: Attach BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: true -ColumnLimit: 140 +ColumnLimit: 120 ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 diff --git a/src/CommandLineParser.ts b/src/CommandLineParser.ts index 79541325f..e50f90f0e 100644 --- a/src/CommandLineParser.ts +++ b/src/CommandLineParser.ts @@ -92,7 +92,12 @@ export function parseCommandLine(args: string[]): ParsedCommandLine { const configPath = commandLine.options.project; const configContents = fs.readFileSync(configPath).toString(); const configJson = ts.parseConfigFileTextToJson(configPath, configContents); - commandLine = ts.parseJsonConfigFileContent(configJson.config, ts.sys, path.dirname(configPath), commandLine.options); + commandLine = ts.parseJsonConfigFileContent( + configJson.config, + ts.sys, + path.dirname(configPath), + commandLine.options + ); } // Add TSTL options from tsconfig @@ -119,7 +124,12 @@ export function parseCommandLine(args: string[]): ParsedCommandLine { return commandLine as ParsedCommandLine; } -function addTSTLOptions(commandLine: ts.ParsedCommandLine, additionalArgs?: yargs.Arguments, forceOverride?: boolean): void { +function addTSTLOptions( + commandLine: ts.ParsedCommandLine, + additionalArgs?: yargs.Arguments, + forceOverride?: boolean +): void +{ additionalArgs = additionalArgs ? additionalArgs : commandLine.raw; // Add compiler options that are ignored by TS parsers if (additionalArgs) { diff --git a/src/Compiler.ts b/src/Compiler.ts index 57a4675ea..2ac8afe84 100644 --- a/src/Compiler.ts +++ b/src/Compiler.ts @@ -48,9 +48,13 @@ export function watchWithOptions(fileNames: string[], options: CompilerOptions): }; if (config) { - ts.createWatchProgram(host as ts.WatchCompilerHostOfConfigFile); + ts.createWatchProgram( + host as ts.WatchCompilerHostOfConfigFile + ); } else { - ts.createWatchProgram(host as ts.WatchCompilerHostOfFilesAndCompilerOptions); + ts.createWatchProgram( + host as ts.WatchCompilerHostOfFilesAndCompilerOptions + ); } } diff --git a/src/LuaAST.ts b/src/LuaAST.ts index 5085b2865..05a2c5a94 100644 --- a/src/LuaAST.ts +++ b/src/LuaAST.ts @@ -76,15 +76,20 @@ export enum SyntaxKind { } // TODO maybe name this PrefixUnary? not sure it makes sense to do so, because all unary ops in Lua are prefix -export type UnaryOperator = SyntaxKind.NegationOperator | SyntaxKind.LengthOperator | SyntaxKind.NotOperator | SyntaxKind.BitwiseNotOperator; +export type UnaryOperator = SyntaxKind.NegationOperator + | SyntaxKind.LengthOperator + | SyntaxKind.NotOperator + | SyntaxKind.BitwiseNotOperator; export type BinaryOperator = - SyntaxKind.AdditionOperator | SyntaxKind.SubractionOperator | SyntaxKind.MultiplicationOperator | SyntaxKind.DivisionOperator | - SyntaxKind.FloorDivisionOperator | SyntaxKind.ModuloOperator | SyntaxKind.PowerOperator | SyntaxKind.ConcatOperator | - SyntaxKind.EqualityOperator | SyntaxKind.InequalityOperator | SyntaxKind.LessThanOperator | SyntaxKind.LessEqualOperator | - SyntaxKind.GreaterThanOperator | SyntaxKind.GreaterEqualOperator | SyntaxKind.AndOperator | SyntaxKind.OrOperator | - SyntaxKind.BitwiseAndOperator | SyntaxKind.BitwiseOrOperator | SyntaxKind.BitwiseExclusiveOrOperator | - SyntaxKind.BitwiseRightShiftOperator | SyntaxKind.BitwiseLeftShiftOperator | SyntaxKind.BitwiseNotOperator; + SyntaxKind.AdditionOperator | SyntaxKind.SubractionOperator | SyntaxKind.MultiplicationOperator + | SyntaxKind.DivisionOperator | SyntaxKind.FloorDivisionOperator | SyntaxKind.ModuloOperator + | SyntaxKind.PowerOperator | SyntaxKind.ConcatOperator | SyntaxKind.EqualityOperator + | SyntaxKind.InequalityOperator | SyntaxKind.LessThanOperator | SyntaxKind.LessEqualOperator + | SyntaxKind.GreaterThanOperator | SyntaxKind.GreaterEqualOperator | SyntaxKind.AndOperator + | SyntaxKind.OrOperator | SyntaxKind.BitwiseAndOperator | SyntaxKind.BitwiseOrOperator + | SyntaxKind.BitwiseExclusiveOrOperator | SyntaxKind.BitwiseRightShiftOperator | SyntaxKind.BitwiseLeftShiftOperator + | SyntaxKind.BitwiseNotOperator; export type Operator = UnaryOperator | BinaryOperator; @@ -192,7 +197,11 @@ export function createVariableDeclarationStatement( right?: Expression | Expression[], parent?: Node, tsOriginal?: ts.Node): VariableDeclarationStatement { - const statement = createNode(SyntaxKind.VariableDeclarationStatement, parent, tsOriginal) as VariableDeclarationStatement; + const statement = createNode( + SyntaxKind.VariableDeclarationStatement, + parent, + tsOriginal + ) as VariableDeclarationStatement; setParent(left, statement); if (Array.isArray(left)) { statement.left = left; @@ -252,7 +261,13 @@ export function isIfStatement(node: Node): node is IfStatement { } export function createIfStatement( - condtion: Expression, ifBlock: Block, elseBlock?: Block | IfStatement, parent?: Node, tsOriginal?: ts.Node): IfStatement { + condtion: Expression, + ifBlock: Block, + elseBlock?: Block | IfStatement, + parent?: Node, + tsOriginal?: ts.Node +): IfStatement +{ const statement = createNode(SyntaxKind.IfStatement, parent, tsOriginal) as IfStatement; setParent(condtion, statement); statement.condtion = condtion; @@ -268,8 +283,8 @@ export interface IterationStatement extends Statement { } export function isIterationStatement(node: Node): node is WhileStatement { - return node.kind === SyntaxKind.WhileStatement || node.kind === SyntaxKind.RepeatStatement || node.kind === SyntaxKind.ForStatement || - node.kind === SyntaxKind.ForInStatement; + return node.kind === SyntaxKind.WhileStatement || node.kind === SyntaxKind.RepeatStatement + || node.kind === SyntaxKind.ForStatement || node.kind === SyntaxKind.ForInStatement; } export interface WhileStatement extends IterationStatement { @@ -281,7 +296,13 @@ export function isWhileStatement(node: Node): node is WhileStatement { return node.kind === SyntaxKind.WhileStatement; } -export function createWhileStatement(body: Block, condtion: Expression, parent?: Node, tsOriginal?: ts.Node): WhileStatement { +export function createWhileStatement( + body: Block, + condtion: Expression, + parent?: Node, + tsOriginal?: ts.Node +): WhileStatement +{ const statement = createNode(SyntaxKind.WhileStatement, parent, tsOriginal) as WhileStatement; setParent(body, statement); statement.body = body; @@ -299,7 +320,13 @@ export function isRepeatStatement(node: Node): node is RepeatStatement { return node.kind === SyntaxKind.RepeatStatement; } -export function createRepeatStatement(body: Block, condtion: Expression, parent?: Node, tsOriginal?: ts.Node): RepeatStatement { +export function createRepeatStatement( + body: Block, + condtion: Expression, + parent?: Node, + tsOriginal?: ts.Node +): RepeatStatement +{ const statement = createNode(SyntaxKind.RepeatStatement, parent, tsOriginal) as RepeatStatement; setParent(body, statement); statement.body = body; @@ -404,7 +431,12 @@ export function isReturnStatement(node: Node): node is ReturnStatement { return node.kind === SyntaxKind.ReturnStatement; } -export function createReturnStatement(expressions?: Expression[], parent?: Node, tsOriginal?: ts.Node): ReturnStatement { +export function createReturnStatement( + expressions?: Expression[], + parent?: Node, + tsOriginal?: ts.Node +): ReturnStatement +{ const statement = createNode(SyntaxKind.ReturnStatement, parent, tsOriginal) as ReturnStatement; setParent(expressions, statement); statement.expressions = expressions; @@ -432,7 +464,12 @@ export function isExpressionStatement(node: Node): node is ExpressionStatement { return node.kind === SyntaxKind.ExpressionStatement; } -export function createExpressionStatement(expressions: Expression, parent?: Node, tsOriginal?: ts.Node): ExpressionStatement { +export function createExpressionStatement( + expressions: Expression, + parent?: Node, + tsOriginal?: ts.Node +): ExpressionStatement +{ const statement = createNode(SyntaxKind.ExpressionStatement, parent, tsOriginal) as ExpressionStatement; setParent(expressions, statement); statement.expression = expressions; @@ -542,8 +579,14 @@ export function isFunctionExpression(node: Node): node is FunctionExpression { } export function createFunctionExpression( - body: Block, params?: Identifier[], dots?: DotsLiteral, restParamName?: Identifier, parent?: Node, tsOriginal?: ts.Node): - FunctionExpression { + body: Block, + params?: Identifier[], + dots?: DotsLiteral, + restParamName?: Identifier, + parent?: Node, + tsOriginal?: ts.Node +): FunctionExpression +{ const expression = createNode(SyntaxKind.FunctionExpression, parent, tsOriginal) as FunctionExpression; setParent(body, expression); expression.body = body; @@ -566,7 +609,13 @@ export function isTableFieldExpression(node: Node): node is TableFieldExpression return node.kind === SyntaxKind.TableFieldExpression; } -export function createTableFieldExpression(value: Expression, key?: Expression, parent?: Node, tsOriginal?: ts.Node): TableFieldExpression { +export function createTableFieldExpression( + value: Expression, + key?: Expression, + parent?: Node, + tsOriginal?: ts.Node +): TableFieldExpression +{ const expression = createNode(SyntaxKind.TableExpression, parent, tsOriginal) as TableFieldExpression; setParent(value, expression); expression.value = value; @@ -584,7 +633,12 @@ export function isTableExpression(node: Node): node is TableExpression { return node.kind === SyntaxKind.TableExpression; } -export function createTableExpression(fields?: TableFieldExpression[], parent?: Node, tsOriginal?: ts.Node): TableExpression { +export function createTableExpression( + fields?: TableFieldExpression[], + parent?: Node, + tsOriginal?: ts.Node +): TableExpression +{ const expression = createNode(SyntaxKind.TableExpression, parent, tsOriginal) as TableExpression; setParent(fields, expression); expression.fields = fields; @@ -601,7 +655,13 @@ export function isUnaryExpression(node: Node): node is UnaryExpression { return node.kind === SyntaxKind.UnaryExpression; } -export function createUnaryExpression(operand: Expression, operator: UnaryOperator, parent?: Node, tsOriginal?: ts.Node): UnaryExpression { +export function createUnaryExpression( + operand: Expression, + operator: UnaryOperator, + parent?: Node, + tsOriginal?: ts.Node +): UnaryExpression +{ const expression = createNode(SyntaxKind.UnaryExpression, parent, tsOriginal) as UnaryExpression; setParent(operand, expression); expression.operand = operand; @@ -621,7 +681,13 @@ export function isBinaryExpression(node: Node): node is BinaryExpression { } export function createBinaryExpression( - left: Expression, right: Expression, operator: BinaryOperator, parent?: Node, tsOriginal?: ts.Node): BinaryExpression { + left: Expression, + right: Expression, + operator: BinaryOperator, + parent?: Node, + tsOriginal?: ts.Node +): BinaryExpression +{ const expression = createNode(SyntaxKind.BinaryExpression, parent, tsOriginal) as BinaryExpression; setParent(left, expression); expression.left = left; @@ -640,7 +706,12 @@ export function isParenthesizedExpression(node: Node): node is ParenthesizedExpr return node.kind === SyntaxKind.ParenthesizedExpression; } -export function createParenthesizedExpression(innerExpression: Expression, parent?: Node, tsOriginal?: ts.Node): ParenthesizedExpression { +export function createParenthesizedExpression( + innerExpression: Expression, + parent?: Node, + tsOriginal?: ts.Node +): ParenthesizedExpression +{ const expression = createNode(SyntaxKind.ParenthesizedExpression, parent, tsOriginal) as ParenthesizedExpression; setParent(innerExpression, expression); expression.innerEpxression = innerExpression; @@ -657,7 +728,13 @@ export function isCallExpression(node: Node): node is CallExpression { return node.kind === SyntaxKind.CallExpression; } -export function createCallExpression(expression: Expression, params?: Expression[], parent?: Node, tsOriginal?: ts.Node): CallExpression { +export function createCallExpression( + expression: Expression, + params?: Expression[], + parent?: Node, + tsOriginal?: ts.Node +): CallExpression +{ const callExpression = createNode(SyntaxKind.CallExpression, parent, tsOriginal) as CallExpression; setParent(expression, callExpression); callExpression.expression = expression; @@ -678,7 +755,13 @@ export function isMethodCallExpression(node: Node): node is MethodCallExpression } export function createMethodCallExpression( - prefixExpression: Expression, name: Identifier, params?: Expression[], parent?: Node, tsOriginal?: ts.Node): MethodCallExpression { + prefixExpression: Expression, + name: Identifier, + params?: Expression[], + parent?: Node, + tsOriginal?: ts.Node +): MethodCallExpression +{ const callExpression = createNode(SyntaxKind.MethodCallExpression, parent, tsOriginal) as MethodCallExpression; setParent(prefixExpression, callExpression); callExpression.prefixExpression = prefixExpression; diff --git a/src/LuaPrinter.ts b/src/LuaPrinter.ts index 5e7734828..bdfcc7fe3 100644 --- a/src/LuaPrinter.ts +++ b/src/LuaPrinter.ts @@ -57,7 +57,7 @@ export class LuaPrinter { || this.options.luaLibImport === LuaLibImportKind.Always) { header += `require("lualib_bundle");\n`; - } + } // Inline lualib features else if (this.options.luaLibImport === LuaLibImportKind.Inline && luaLibFeatures.size > 0) { diff --git a/src/LuaTranspiler.ts b/src/LuaTranspiler.ts index 8f3f44c88..fbbac826f 100644 --- a/src/LuaTranspiler.ts +++ b/src/LuaTranspiler.ts @@ -49,9 +49,13 @@ export class LuaTranspiler { this.program.getSourceFiles().forEach(sourceFile => this.emitSourceFile(sourceFile)); // Copy lualib to target dir - if (this.options.luaLibImport === LuaLibImportKind.Require || this.options.luaLibImport === LuaLibImportKind.Always) { + if (this.options.luaLibImport === LuaLibImportKind.Require + || this.options.luaLibImport === LuaLibImportKind.Always + ) { fs.copyFileSync( - path.resolve(__dirname, "../dist/lualib/lualib_bundle.lua"), path.join(this.options.outDir, "lualib_bundle.lua")); + path.resolve(__dirname, "../dist/lualib/lualib_bundle.lua"), + path.join(this.options.outDir, "lualib_bundle.lua") + ); } return 0; @@ -91,7 +95,7 @@ export class LuaTranspiler { const pos = ts.getLineAndCharacterOfPosition(sourceFile, exception.node.pos); // Graciously handle transpilation errors console.error("Encountered error parsing file: " + exception.message); - console.error(sourceFile.fileName + " line: " + (1 + pos.line) + " column: " + pos.character + "\n" + exception.stack); + console.error(`${sourceFile.fileName} (${1 + pos.line},${pos.character})\n${exception.stack}`); process.exit(1); } else { throw exception; diff --git a/src/TSHelper.ts b/src/TSHelper.ts index 6c1922f70..fe615dacd 100644 --- a/src/TSHelper.ts +++ b/src/TSHelper.ts @@ -77,14 +77,20 @@ export class TSHelper { // export statement, we only check for export statements // TODO will break in 3.x return sourceFile.statements.some( - statement => (ts.getCombinedModifierFlags(statement) & ts.ModifierFlags.Export) !== 0 || - statement.kind === ts.SyntaxKind.ExportAssignment || statement.kind === ts.SyntaxKind.ExportDeclaration); + statement => (ts.getCombinedModifierFlags(statement) & ts.ModifierFlags.Export) !== 0 + || statement.kind === ts.SyntaxKind.ExportAssignment + || statement.kind === ts.SyntaxKind.ExportDeclaration + ); } return false; } - public static isIdentifierExported(identifier: ts.Identifier, scope: ts.ModuleDeclaration | ts.SourceFile, checker: ts.TypeChecker): - boolean { + public static isIdentifierExported( + identifier: ts.Identifier, + scope: ts.ModuleDeclaration | ts.SourceFile, + checker: ts.TypeChecker + ): boolean + { const identifierSymbol = checker.getTypeAtLocation(scope).getSymbol(); if (identifierSymbol.exports)  { @@ -100,7 +106,12 @@ export class TSHelper { } // iterate over a type and its bases until the callback returns true. - public static forTypeOrAnySupertype(type: ts.Type, checker: ts.TypeChecker, predicate: (type: ts.Type) => boolean): boolean { + public static forTypeOrAnySupertype( + type: ts.Type, + checker: ts.TypeChecker, + predicate: (type: ts.Type) => boolean + ): boolean + { if (predicate(type)) { return true; } @@ -163,7 +174,10 @@ export class TSHelper { } public static isInTupleReturnFunction(node: ts.Node, checker: ts.TypeChecker): boolean { - const declaration = this.findFirstNodeAbove(node, (n): n is ts.Node => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n)); + const declaration = this.findFirstNodeAbove( + node, + (n): n is ts.Node => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) + ); if (declaration) { const decorators = this.getCustomDecorators(checker.getTypeAtLocation(declaration), checker); return decorators.has(DecoratorKind.TupleReturn) @@ -183,7 +197,12 @@ export class TSHelper { return undefined; } - public static collectCustomDecorators(symbol: ts.Symbol, checker: ts.TypeChecker, decMap: Map): void { + public static collectCustomDecorators( + symbol: ts.Symbol, + checker: ts.TypeChecker, + decMap: Map + ): void + { const comments = symbol.getDocumentationComment(checker); const decorators = comments.filter(comment => comment.kind === "text") .map(comment => comment.text.split("\n")) @@ -305,7 +324,10 @@ export class TSHelper { node.operator !== ts.SyntaxKind.PlusToken && node.operator !== ts.SyntaxKind.TildeToken; } - public static getUnaryCompoundAssignmentOperator(node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression): ts.BinaryOperator { + public static getUnaryCompoundAssignmentOperator( + node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression + ): ts.BinaryOperator + { switch (node.operator) { case ts.SyntaxKind.PlusPlusToken: return ts.SyntaxKind.PlusToken; @@ -342,7 +364,8 @@ export class TSHelper { public static isAccessExpressionWithEvaluationEffects(node: ts.Expression, checker: ts.TypeChecker): [boolean, ts.Expression, ts.Expression] { if (ts.isElementAccessExpression(node) && - (this.isExpressionWithEvaluationEffect(node.expression) || this.isExpressionWithEvaluationEffect(node.argumentExpression))) { + (this.isExpressionWithEvaluationEffect(node.expression) + || this.isExpressionWithEvaluationEffect(node.argumentExpression))) { const type = checker.getTypeAtLocation(node.expression); if (this.isArrayType(type, checker)) { // Offset arrays by one @@ -368,12 +391,16 @@ export class TSHelper { param => ts.isIdentifier(param.name) && param.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword); } - public static getSignatureDeclarations(signatures: ts.Signature[], checker: ts.TypeChecker): ts.SignatureDeclaration[] { + public static getSignatureDeclarations( + signatures: ts.Signature[], + checker: ts.TypeChecker + ): ts.SignatureDeclaration[] + { const signatureDeclarations: ts.SignatureDeclaration[] = []; for (const signature of signatures) { const signatureDeclaration = signature.getDeclaration(); - if ((ts.isFunctionExpression(signatureDeclaration) || ts.isArrowFunction(signatureDeclaration)) && - !this.getExplicitThisParameter(signatureDeclaration)) { + if ((ts.isFunctionExpression(signatureDeclaration) || ts.isArrowFunction(signatureDeclaration)) + && !this.getExplicitThisParameter(signatureDeclaration)) { // Function expressions: get signatures of type being assigned to, unless 'this' was explicit let declType: ts.Type; if (ts.isCallExpression(signatureDeclaration.parent)) { @@ -405,11 +432,17 @@ export class TSHelper { return signatureDeclarations; } - public static getDeclarationContextType(signatureDeclaration: ts.SignatureDeclaration, checker: ts.TypeChecker): ContextType { + public static getDeclarationContextType( + signatureDeclaration: ts.SignatureDeclaration, + checker: ts.TypeChecker + ): ContextType + { const thisParameter = this.getExplicitThisParameter(signatureDeclaration); if (thisParameter) { // Explicit 'this' - return thisParameter.type && thisParameter.type.kind === ts.SyntaxKind.VoidKeyword ? ContextType.Void : ContextType.NonVoid; + return thisParameter.type && thisParameter.type.kind === ts.SyntaxKind.VoidKeyword + ? ContextType.Void + : ContextType.NonVoid; } if (ts.isMethodDeclaration(signatureDeclaration) || ts.isMethodSignature(signatureDeclaration)) { // Method diff --git a/src/TSTLErrors.ts b/src/TSTLErrors.ts index 6c2d1554d..316760af4 100644 --- a/src/TSTLErrors.ts +++ b/src/TSTLErrors.ts @@ -7,16 +7,19 @@ export class TSTLErrors { public static DefaultImportsNotSupported = (node: ts.Node) => new TranspileError(`Default Imports are not supported, please use named imports instead!`, node); - public static ForbiddenEllipsisDestruction = (node: ts.Node) => new TranspileError(`Ellipsis destruction is not allowed.`, node); + public static ForbiddenEllipsisDestruction = + (node: ts.Node) => new TranspileError(`Ellipsis destruction is not allowed.`, node); - public static ForbiddenForIn = (node: ts.Node) => new TranspileError(`Iterating over arrays with 'for ... in' is not allowed.`, node); + public static ForbiddenForIn = + (node: ts.Node) => new TranspileError(`Iterating over arrays with 'for ... in' is not allowed.`, node); public static HeterogeneousEnum = (node: ts.Node) => new TranspileError( `Invalid heterogeneous enum. Enums should either specify no member values, ` + `or specify values (of the same type) for all members.`, node); - public static InvalidEnumMember = (node: ts.Node) => new TranspileError(`Only numeric or string initializers allowed for enums.`, node); + public static InvalidEnumMember = + (node: ts.Node) => new TranspileError(`Only numeric or string initializers allowed for enums.`, node); public static InvalidDecoratorArgumentNumber = (name: string, got: number, expected: number, node: ts.Node) => new TranspileError(`${name} expects ${expected} argument(s) but got ${got}.`, node); @@ -39,7 +42,8 @@ export class TSTLErrors { public static KeywordIdentifier = (node: ts.Identifier) => new TranspileError(`Cannot use Lua keyword ${node.escapedText} as identifier.`, node); - public static MissingClassName = (node: ts.Node) => new TranspileError(`Class declarations must have a name.`, node); + public static MissingClassName = + (node: ts.Node) => new TranspileError(`Class declarations must have a name.`, node); public static MissingMetaExtension = (node: ts.Node) => new TranspileError(`!MetaExtension requires the extension of the metatable class.`, node); diff --git a/tslint.json b/tslint.json index 02d094c1a..601befe6c 100644 --- a/tslint.json +++ b/tslint.json @@ -27,6 +27,7 @@ "jsdoc-format": true, "label-position": true, "max-classes-per-file": [true, 1], + "max-line-length": [true, 120], "member-access": true, "new-parens": true, "no-angle-bracket-type-assertion": true, @@ -42,6 +43,7 @@ "no-null-keyword": true, "no-reference": true, "no-string-throw": true, + "no-trailing-whitespace": true, "no-unused-expression": true, "no-var-keyword": true, "object-literal-shorthand": true, From 7b2733ef3f57758e45e0ea0678ed9e664d2a8f29 Mon Sep 17 00:00:00 2001 From: Perryvw Date: Fri, 11 Jan 2019 20:33:23 +0100 Subject: [PATCH 2/3] Fixed lines exceeding max length --- src/LuaTransformer.ts | 543 +++++++++++++++++++++++++++++++++--------- 1 file changed, 426 insertions(+), 117 deletions(-) diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index 269c8142b..cf3198f45 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -206,14 +206,22 @@ export class LuaTransformer { const nameIdentifier = this.transformIdentifier(importSpecifier.name); const name = tstl.createStringLiteral(nameIdentifier.text); const namedImport = tstl.createVariableDeclarationStatement( - nameIdentifier, tstl.createTableIndexExpression(importUniqueName, name), undefined, importSpecifier); + nameIdentifier, + tstl.createTableIndexExpression(importUniqueName, name), + undefined, + importSpecifier + ); result.push(namedImport); } }); return result; } else if (ts.isNamespaceImport(imports)) { - const requireStatement = - tstl.createVariableDeclarationStatement(this.transformIdentifier(imports.name), requireCall, undefined, statement); + const requireStatement = tstl.createVariableDeclarationStatement( + this.transformIdentifier(imports.name), + requireCall, + undefined, + statement + ); result.push(requireStatement); return result; } else { @@ -265,7 +273,12 @@ export class LuaTransformer { className, tstl.createTableIndexExpression( tstl.createCallExpression( - tstl.createTableIndexExpression(tstl.createIdentifier("debug"), tstl.createStringLiteral("getregistry")), []), + tstl.createTableIndexExpression( + tstl.createIdentifier("debug"), + tstl.createStringLiteral("getregistry") + ), + [] + ), extendsName), undefined, statement); @@ -283,7 +296,12 @@ export class LuaTransformer { } if (!isExtension && !isMetaExtension) { - const classCreationMethods = this.createClassCreationMethods(statement, className, instanceFields, extendsType); + const classCreationMethods = this.createClassCreationMethods( + statement, + className, + instanceFields, + extendsType + ); result.push(...classCreationMethods); } else { for (const f of instanceFields) { @@ -306,19 +324,26 @@ export class LuaTransformer { const fieldName = this.transformPropertyName(field.name); const value = this.transformExpression(field.initializer); - const fieldAssign = tstl.createAssignmentStatement(tstl.createTableIndexExpression(className, fieldName), value); + const fieldAssign = tstl.createAssignmentStatement( + tstl.createTableIndexExpression(className, fieldName), + value + ); result.push(fieldAssign); } // Find first constructor with body - const constructor = statement.members.filter(n => ts.isConstructorDeclaration(n) && n.body)[0] as ts.ConstructorDeclaration; + const constructor = statement.members + .filter(n => ts.isConstructorDeclaration(n) && n.body)[0] as ts.ConstructorDeclaration; if (constructor) { // Add constructor plus initialization of instance fields result.push(this.transformConstructor(constructor, className)); } else if (!isExtension && !extendsType) { // Generate a constructor if none was defined - result.push(this.transformConstructor(ts.createConstructor([], [], [], ts.createBlock([], true)), className)); + result.push(this.transformConstructor( + ts.createConstructor([], [], [], ts.createBlock([], true)), + className + )); } // Transform get accessors @@ -412,7 +437,11 @@ export class LuaTransformer { // local self = setmetatable({}, className) const assignSelf = tstl.createVariableDeclarationStatement( this.selfIdentifier, - tstl.createCallExpression(tstl.createIdentifier("setmetatable"), [tstl.createTableExpression(), className])); + tstl.createCallExpression( + tstl.createIdentifier("setmetatable"), + [tstl.createTableExpression(), className] + ) + ); newFuncStatements.push(assignSelf); @@ -470,7 +499,11 @@ export class LuaTransformer { return result; } - public transformConstructor(statement: ts.ConstructorDeclaration, className: tstl.Identifier): tstl.AssignmentStatement { + public transformConstructor( + statement: ts.ConstructorDeclaration, + className: tstl.Identifier + ): tstl.AssignmentStatement + { // Don't transform methods without body (overload declarations) if (!statement.body) { return undefined; @@ -490,21 +523,34 @@ export class LuaTransformer { if (declaration.initializer) { // self.declarationName = declarationName or initializer const assignement = tstl.createAssignmentStatement( - tstl.createTableIndexExpression(this.selfIdentifier, tstl.createStringLiteral(declarationName.text)), + tstl.createTableIndexExpression( + this.selfIdentifier, tstl.createStringLiteral(declarationName.text) + ), tstl.createBinaryExpression( - declarationName, this.transformExpression(declaration.initializer), tstl.SyntaxKind.OrOperator)); + declarationName, + this.transformExpression(declaration.initializer), tstl.SyntaxKind.OrOperator + ) + ); bodyStatements.push(assignement); } else { // self.declarationName = declarationName const assignement = tstl.createAssignmentStatement( - tstl.createTableIndexExpression(this.selfIdentifier, tstl.createStringLiteral(declarationName.text)), declarationName); + tstl.createTableIndexExpression( + this.selfIdentifier, + tstl.createStringLiteral(declarationName.text) + ), + declarationName + ); bodyStatements.push(assignement); } } // function className.constructor(params) ... end - const [params, dotsLiteral, restParamName] = this.transformParameters(statement.parameters, this.selfIdentifier); + const [params, dotsLiteral, restParamName] = this.transformParameters( + statement.parameters, + this.selfIdentifier + ); bodyStatements.push(...this.transformFunctionBody(statement.parameters, statement.body, restParamName)); @@ -521,29 +567,51 @@ export class LuaTransformer { return result; } - public transformGetAccessorDeclaration(getAccessor: ts.GetAccessorDeclaration, className: tstl.Identifier): tstl.AssignmentStatement { + public transformGetAccessorDeclaration( + getAccessor: ts.GetAccessorDeclaration, + className: tstl.Identifier + ): tstl.AssignmentStatement + { const name = this.transformIdentifier(getAccessor.name as ts.Identifier); const accessorFunction = tstl.createFunctionExpression( - tstl.createBlock(this.transformFunctionBody(getAccessor.parameters, getAccessor.body)), [this.selfIdentifier]); + tstl.createBlock(this.transformFunctionBody(getAccessor.parameters, getAccessor.body)), + [this.selfIdentifier] + ); return tstl.createAssignmentStatement( - tstl.createTableIndexExpression(className, tstl.createStringLiteral("get__" + name.text)), accessorFunction); + tstl.createTableIndexExpression(className, tstl.createStringLiteral("get__" + name.text)), + accessorFunction + ); } - public transformSetAccessorDeclaration(setAccessor: ts.SetAccessorDeclaration, className: tstl.Identifier): tstl.AssignmentStatement { + public transformSetAccessorDeclaration( + setAccessor: ts.SetAccessorDeclaration, + className: tstl.Identifier + ): tstl.AssignmentStatement + { const name = this.transformIdentifier(setAccessor.name as ts.Identifier); const [params, dot, restParam] = this.transformParameters(setAccessor.parameters, this.selfIdentifier); const accessorFunction = tstl.createFunctionExpression( - tstl.createBlock(this.transformFunctionBody(setAccessor.parameters, setAccessor.body, restParam)), params, dot, restParam); + tstl.createBlock(this.transformFunctionBody(setAccessor.parameters, setAccessor.body, restParam)), + params, + dot, + restParam + ); return tstl.createAssignmentStatement( - tstl.createTableIndexExpression(className, tstl.createStringLiteral("set__" + name.text)), accessorFunction); + tstl.createTableIndexExpression(className, tstl.createStringLiteral("set__" + name.text)), + accessorFunction + ); } - public transformMethodDeclaration(node: ts.MethodDeclaration, className: tstl.Identifier): tstl.AssignmentStatement { + public transformMethodDeclaration( + node: ts.MethodDeclaration, + className: tstl.Identifier + ): tstl.AssignmentStatement + { // Don't transform methods without body (overload declarations) if (!node.body) { return undefined; @@ -555,13 +623,24 @@ export class LuaTransformer { } const type = this.checker.getTypeAtLocation(node); - const context = tsHelper.getFunctionContextType(type, this.checker) !== ContextType.Void ? this.selfIdentifier : undefined; + const context = tsHelper.getFunctionContextType(type, this.checker) !== ContextType.Void + ? this.selfIdentifier + : undefined; const [paramNames, dots, restParamName] = this.transformParameters(node.parameters, context); const functionExpression = tstl.createFunctionExpression( - tstl.createBlock(this.transformFunctionBody(node.parameters, node.body, restParamName)), paramNames, dots, restParamName); + tstl.createBlock(this.transformFunctionBody(node.parameters, node.body, restParamName)), + paramNames, + dots, + restParamName + ); - return tstl.createAssignmentStatement(tstl.createTableIndexExpression(className, methodName), functionExpression); + return tstl.createAssignmentStatement( + tstl.createTableIndexExpression(className, methodName), + functionExpression, + undefined, + node + ); } public transformParameters(parameters: ts.NodeArray, context?: tstl.Identifier): @@ -595,8 +674,12 @@ export class LuaTransformer { return [paramNames, dotsLiteral, restParamName]; } - public transformFunctionBody(parameters: ts.NodeArray, body: ts.Block, spreadIdentifier?: tstl.Identifier): - tstl.Statement[] { + public transformFunctionBody( + parameters: ts.NodeArray, + body: ts.Block, + spreadIdentifier?: tstl.Identifier + ): tstl.Statement[] + { this.pushScope(ScopeType.Function); const headerStatements = []; @@ -626,7 +709,11 @@ export class LuaTransformer { const parameterValue = this.transformExpression(declaration.initializer); const assignment = tstl.createAssignmentStatement(parameterName, parameterValue); - const nilCondition = tstl.createBinaryExpression(parameterName, tstl.createNilLiteral(), tstl.SyntaxKind.EqualityOperator); + const nilCondition = tstl.createBinaryExpression( + parameterName, + tstl.createNilLiteral(), + tstl.SyntaxKind.EqualityOperator + ); const ifBlock = tstl.createBlock([assignment]); @@ -669,7 +756,9 @@ export class LuaTransformer { // exports.NS = exports.NS or {} const namespaceDeclaration = tstl.createAssignmentStatement( tstl.createTableIndexExpression( - this.transformIdentifier(ts.createIdentifier("exports")), this.transformIdentifier(statement.name as ts.Identifier)), + this.transformIdentifier(ts.createIdentifier("exports")), + this.transformIdentifier(statement.name as ts.Identifier) + ), tstl.createBinaryExpression( tstl.createTableIndexExpression( this.transformIdentifier(ts.createIdentifier("exports")), @@ -691,7 +780,12 @@ export class LuaTransformer { // local NS = NS or {} const localDeclaration = tstl.createVariableDeclarationStatement( this.transformIdentifier(statement.name as ts.Identifier), - tstl.createBinaryExpression(tstl.createIdentifier("NS"), tstl.createTableExpression(), tstl.SyntaxKind.OrOperator)); + tstl.createBinaryExpression( + tstl.createIdentifier("NS"), + tstl.createTableExpression(), + tstl.SyntaxKind.OrOperator + ) + ); result.push(localDeclaration); } @@ -733,13 +827,19 @@ export class LuaTransformer { const memberName = this.transformPropertyName(enumMember.name); if (membersOnly) { if (tstl.isIdentifier(memberName)) { - result.push(this.createLocalOrGlobalDeclaration(memberName, enumMember.value, undefined, enumDeclaration)); + result.push(this.createLocalOrGlobalDeclaration( + memberName, + enumMember.value, + undefined, + enumDeclaration + )); } else { result.push(this.createLocalOrGlobalDeclaration( tstl.createIdentifier(enumMember.name.getText(), undefined, enumMember.name), enumMember.value, undefined, - enumDeclaration)); + enumDeclaration + )); } } else { const table = this.transformIdentifier(enumDeclaration.name); @@ -793,11 +893,15 @@ export class LuaTransformer { } const type = this.checker.getTypeAtLocation(functionDeclaration); - const context = tsHelper.getFunctionContextType(type, this.checker) !== ContextType.Void ? this.selfIdentifier : undefined; + const context = tsHelper.getFunctionContextType(type, this.checker) !== ContextType.Void + ? this.selfIdentifier + : undefined; const [params, dotsLiteral, restParamName] = this.transformParameters(functionDeclaration.parameters, context); const name = this.transformIdentifier(functionDeclaration.name); - const body = tstl.createBlock(this.transformFunctionBody(functionDeclaration.parameters, functionDeclaration.body, restParamName)); + const body = tstl.createBlock( + this.transformFunctionBody(functionDeclaration.parameters, functionDeclaration.body, restParamName) + ); const functionExpression = tstl.createFunctionExpression(body, params, dotsLiteral, restParamName); return this.createLocalOrGlobalDeclaration(name, functionExpression, undefined, functionDeclaration); @@ -812,7 +916,8 @@ export class LuaTransformer { } public transformVariableDeclaration(statement: ts.VariableDeclaration) - : [tstl.VariableDeclarationStatement] | [tstl.VariableDeclarationStatement, tstl.AssignmentStatement] { + : [tstl.VariableDeclarationStatement] | [tstl.VariableDeclarationStatement, tstl.AssignmentStatement] + { if (statement.initializer) { // Validate assignment const initializerType = this.checker.getTypeAtLocation(statement.initializer); @@ -829,7 +934,8 @@ export class LuaTransformer { // Separate declaration and assignment for functions to allow recursion // local identifierName; identifierName = value; - return [tstl.createVariableDeclarationStatement(identifierName), tstl.createAssignmentStatement(identifierName, value)]; + return [tstl.createVariableDeclarationStatement(identifierName), + tstl.createAssignmentStatement(identifierName, value)]; } else { // local identifierName = value; return [tstl.createVariableDeclarationStatement(identifierName, value)]; @@ -852,7 +958,10 @@ export class LuaTransformer { if (statement.initializer) { if (tsHelper.isTupleReturnCall(statement.initializer, this.checker)) { // local vars = initializer; - return [tstl.createVariableDeclarationStatement(vars, this.transformExpression(statement.initializer))]; + return [tstl.createVariableDeclarationStatement( + vars, + this.transformExpression(statement.initializer) + )]; } else { // local vars = this.transpileDestructingAssignmentValue(node.initializer); const initializer = this.createUnpackCall(this.transformExpression(statement.initializer)); @@ -868,7 +977,8 @@ export class LuaTransformer { public transformVariableStatement(statement: ts.VariableStatement): tstl.Statement[] { const result: tstl.Statement[] = []; - statement.declarationList.declarations.forEach(declaration => result.push(...this.transformVariableDeclaration(declaration))); + statement.declarationList.declarations + .forEach(declaration => result.push(...this.transformVariableDeclaration(declaration))); return result; } @@ -878,7 +988,11 @@ export class LuaTransformer { const [isCompound, replacementOperator] = tsHelper.isBinaryAssignmentToken(expression.operatorToken.kind); if (isCompound) { // +=, -=, etc... - return this.transformCompoundAssignmentStatement(expression.left, expression.right, replacementOperator); + return this.transformCompoundAssignmentStatement( + expression.left, + expression.right, + replacementOperator + ); } else if (expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) { // = assignment @@ -887,18 +1001,31 @@ export class LuaTransformer { } else if ( ts.isPrefixUnaryExpression(expression) && - (expression.operator === ts.SyntaxKind.PlusPlusToken || expression.operator === ts.SyntaxKind.MinusMinusToken)) { + (expression.operator === ts.SyntaxKind.PlusPlusToken + || expression.operator === ts.SyntaxKind.MinusMinusToken)) { // ++i, --i - const replacementOperator = - expression.operator === ts.SyntaxKind.PlusPlusToken ? tstl.SyntaxKind.AdditionOperator : tstl.SyntaxKind.SubractionOperator; - return this.transformCompoundAssignmentStatement(expression.operand, ts.createLiteral(1), replacementOperator); + const replacementOperator = expression.operator === ts.SyntaxKind.PlusPlusToken + ? tstl.SyntaxKind.AdditionOperator + : tstl.SyntaxKind.SubractionOperator; + + return this.transformCompoundAssignmentStatement( + expression.operand, + ts.createLiteral(1), + replacementOperator + ); } else if (ts.isPostfixUnaryExpression(expression)) { // i++, i-- - const replacementOperator = - expression.operator === ts.SyntaxKind.PlusPlusToken ? tstl.SyntaxKind.AdditionOperator : tstl.SyntaxKind.SubractionOperator; - return this.transformCompoundAssignmentStatement(expression.operand, ts.createLiteral(1), replacementOperator); + const replacementOperator = expression.operator === ts.SyntaxKind.PlusPlusToken + ? tstl.SyntaxKind.AdditionOperator + : tstl.SyntaxKind.SubractionOperator; + + return this.transformCompoundAssignmentStatement( + expression.operand, + ts.createLiteral(1), + replacementOperator + ); } return tstl.createExpressionStatement(this.transformExpression(expression)); @@ -915,7 +1042,8 @@ export class LuaTransformer { // Parent function is a TupleReturn function if (ts.isArrayLiteralExpression(statement.expression)) { // If return expression is an array literal, leave out brackets. - return tstl.createReturnStatement(statement.expression.elements.map(elem => this.transformExpression(elem))); + return tstl.createReturnStatement(statement.expression.elements + .map(elem => this.transformExpression(elem))); } else if (!tsHelper.isTupleReturnCall(statement.expression, this.checker)) { // If return expression is not another TupleReturn call, unpack it const expression = this.createUnpackCall(this.transformExpression(statement.expression)); @@ -971,7 +1099,9 @@ export class LuaTransformer { } } - const condition = statement.condition ? this.transformExpression(statement.condition) : tstl.createBooleanLiteral(true); + const condition = statement.condition + ? this.transformExpression(statement.condition) + : tstl.createBooleanLiteral(true); // Add body const body: tstl.Statement[] = this.transformLoopBody(statement); @@ -1000,7 +1130,8 @@ export class LuaTransformer { let variables: tstl.IdentifierOrTableIndexExpression | tstl.IdentifierOrTableIndexExpression[]; if (ts.isArrayLiteralExpression(initializer)) { expression = this.createUnpackCall(expression); - variables = initializer.elements.map(e => this.transformExpression(e)) as tstl.IdentifierOrTableIndexExpression[]; + variables = initializer.elements + .map(e => this.transformExpression(e)) as tstl.IdentifierOrTableIndexExpression[]; } else { variables = this.transformExpression(initializer) as tstl.IdentifierOrTableIndexExpression; } @@ -1086,9 +1217,11 @@ export class LuaTransformer { // for ____TS_value0 in ${iterable} do // ${initializer} = ____TS_value0 if (ts.isArrayLiteralExpression(statement.initializer)) { - const tmps = statement.initializer.elements.map((_, i) => tstl.createIdentifier(`____TS_value${i}`)); + const tmps = statement.initializer.elements + .map((_, i) => tstl.createIdentifier(`____TS_value${i}`)); const assign = tstl.createAssignmentStatement( - statement.initializer.elements.map(e => this.transformExpression(e)) as tstl.IdentifierOrTableIndexExpression[], + statement.initializer.elements + .map(e => this.transformExpression(e)) as tstl.IdentifierOrTableIndexExpression[], tmps ); block.statements.splice(0, 0, assign); @@ -1102,7 +1235,8 @@ export class LuaTransformer { } else { // LuaIterator (no TupleReturn) - if (ts.isVariableDeclarationList(statement.initializer) && ts.isIdentifier(statement.initializer.declarations[0].name)) { + if (ts.isVariableDeclarationList(statement.initializer) + && ts.isIdentifier(statement.initializer.declarations[0].name)) { // Single variable declared in for loop // for ${initializer} in ${iterator} do return tstl.createForInStatement( @@ -1129,7 +1263,8 @@ export class LuaTransformer { public transformForOfIteratorStatement(statement: ts.ForOfStatement, block: tstl.Block): StatementVisitResult { const iterable = this.transformExpression(statement.expression); - if (ts.isVariableDeclarationList(statement.initializer) && ts.isIdentifier(statement.initializer.declarations[0].name)) { + if (ts.isVariableDeclarationList(statement.initializer) + && ts.isIdentifier(statement.initializer.declarations[0].name)) { // Single variable declared in for loop // for ${initializer} in __TS__iterator(${iterator}) do return tstl.createForInStatement( @@ -1173,7 +1308,7 @@ export class LuaTransformer { public transformForInStatement(statement: ts.ForInStatement): StatementVisitResult { // Get variable identifier - const variable = (statement.initializer as ts.VariableDeclarationList).declarations[0] as ts.VariableDeclaration; + const variable = (statement.initializer as ts.VariableDeclarationList).declarations[0]; const identifier = variable.name as ts.Identifier; // Transpile expression @@ -1274,10 +1409,18 @@ export class LuaTransformer { case ts.SyntaxKind.ParenthesizedExpression: // TODO move to extra function (consistency) return tstl.createParenthesizedExpression( - this.transformExpression((expression as ts.ParenthesizedExpression).expression), undefined, expression); + this.transformExpression((expression as ts.ParenthesizedExpression).expression), + undefined, + expression + ); case ts.SyntaxKind.SuperKeyword: // TODO move to extra function (consistency) - return tstl.createTableIndexExpression(this.selfIdentifier, tstl.createStringLiteral("__base"), undefined, expression); + return tstl.createTableIndexExpression( + this.selfIdentifier, + tstl.createStringLiteral("__base"), + undefined, + expression + ); case ts.SyntaxKind.TypeAssertionExpression: case ts.SyntaxKind.AsExpression: return this.transformAssertionExpression(expression as ts.AssertionExpression); @@ -1302,7 +1445,12 @@ export class LuaTransformer { const [isCompound, replacementOperator] = tsHelper.isBinaryAssignmentToken(expression.operatorToken.kind); if (isCompound) { - return this.transformCompoundAssignmentExpression(expression.left, expression.right, replacementOperator, false); + return this.transformCompoundAssignmentExpression( + expression.left, + expression.right, + replacementOperator, + false + ); } const lhs = this.transformExpression(expression.left); @@ -1361,7 +1509,11 @@ export class LuaTransformer { return tstl.createBinaryExpression(lhs, rhs, tstl.SyntaxKind.InequalityOperator); case ts.SyntaxKind.InKeyword: const indexExpression = tstl.createTableIndexExpression(rhs, lhs); - return tstl.createBinaryExpression(indexExpression, tstl.createNilLiteral(), tstl.SyntaxKind.InequalityOperator); + return tstl.createBinaryExpression( + indexExpression, + tstl.createNilLiteral(), + tstl.SyntaxKind.InequalityOperator + ); case ts.SyntaxKind.InstanceOfKeyword: return this.transformLuaLibFunction(LuaLibFeature.InstanceOf, lhs, rhs); default: @@ -1373,7 +1525,10 @@ export class LuaTransformer { if (ts.isPropertyAccessExpression(lhs) && tsHelper.hasSetAccessor(lhs, this.checker)) { return tstl.createExpressionStatement(this.transformSetAccessor(lhs, right)); } else { - return tstl.createAssignmentStatement(this.transformExpression(lhs) as tstl.IdentifierOrTableIndexExpression, right); + return tstl.createAssignmentStatement( + this.transformExpression(lhs) as tstl.IdentifierOrTableIndexExpression, + right + ); } } @@ -1406,7 +1561,9 @@ export class LuaTransformer { } } - public transformAssignmentExpression(expression: ts.BinaryExpression): tstl.CallExpression | tstl.MethodCallExpression { + public transformAssignmentExpression(expression: ts.BinaryExpression) + : tstl.CallExpression | tstl.MethodCallExpression + { // Validate assignment const rightType = this.checker.getTypeAtLocation(expression.right); const leftType = this.checker.getTypeAtLocation(expression.left); @@ -1444,7 +1601,10 @@ export class LuaTransformer { tstl.createAssignmentStatement(indexStatement, valueParameter), tstl.createReturnStatement([valueParameter]), ]; - const iife = tstl.createFunctionExpression(tstl.createBlock(statements), [objParameter, indexParameter, valueParameter]); + const iife = tstl.createFunctionExpression( + tstl.createBlock(statements), + [objParameter, indexParameter, valueParameter] + ); const objExpression = this.transformExpression(expression.left.expression); let indexExpression: tstl.Expression; if (ts.isPropertyAccessExpression(expression.left)) { @@ -1467,7 +1627,10 @@ export class LuaTransformer { // (function() ${left} = ${right}; return ${left} end)() const left = this.transformExpression(expression.left); const right = this.transformExpression(expression.right); - return this.createImmediatelyInvokedFunctionExpression([this.transformAssignment(expression.left, right)], left); + return this.createImmediatelyInvokedFunctionExpression( + [this.transformAssignment(expression.left, right)], + left + ); } } @@ -1488,7 +1651,10 @@ export class LuaTransformer { const left = this.transformExpression(lhs) as tstl.IdentifierOrTableIndexExpression; let right = this.transformExpression(rhs); - const [hasEffects, objExpression, indexExpression] = tsHelper.isAccessExpressionWithEvaluationEffects(lhs, this.checker); + const [hasEffects, objExpression, indexExpression] = tsHelper.isAccessExpressionWithEvaluationEffects( + lhs, + this.checker + ); if (hasEffects) { // Complex property/element accesses need to cache object/index expressions to avoid repeating side-effects // local __TS_obj, __TS_index = ${objExpression}, ${indexExpression}; @@ -1516,7 +1682,10 @@ export class LuaTransformer { assignStatement = tstl.createAssignmentStatement(accessExpression, tmp); } // return ____TS_tmp - return this.createImmediatelyInvokedFunctionExpression([objAndIndexDeclaration, tmpDeclaration, assignStatement], tmp); + return this.createImmediatelyInvokedFunctionExpression( + [objAndIndexDeclaration, tmpDeclaration, assignStatement], + tmp + ); } else if (isPostfix) { // Postfix expressions need to cache original value in temp @@ -1549,8 +1718,12 @@ export class LuaTransformer { } } - public transformCompoundAssignmentStatement(lhs: ts.Expression, rhs: ts.Expression, replacementOperator: tstl.BinaryOperator): - tstl.Statement { + public transformCompoundAssignmentStatement( + lhs: ts.Expression, + rhs: ts.Expression, + replacementOperator: tstl.BinaryOperator + ): tstl.Statement + { if (replacementOperator === tstl.SyntaxKind.AdditionOperator) { // Check is we need to use string concat operator const typeLeft = this.checker.getTypeAtLocation(lhs); @@ -1563,7 +1736,10 @@ export class LuaTransformer { const left = this.transformExpression(lhs) as tstl.IdentifierOrTableIndexExpression; const right = this.transformExpression(rhs); - const [hasEffects, objExpression, indexExpression] = tsHelper.isAccessExpressionWithEvaluationEffects(lhs, this.checker); + const [hasEffects, objExpression, indexExpression] = tsHelper.isAccessExpressionWithEvaluationEffects( + lhs, + this.checker + ); if (hasEffects) { // Complex property/element accesses need to cache object/index expressions to avoid repeating side-effects // local __TS_obj, __TS_index = ${objExpression}, ${indexExpression}; @@ -1574,7 +1750,11 @@ export class LuaTransformer { [obj, index], [this.transformExpression(objExpression), this.transformExpression(indexExpression)]); const accessExpression = tstl.createTableIndexExpression(obj, index); const operatorExpression = - tstl.createBinaryExpression(accessExpression, tstl.createParenthesizedExpression(right), replacementOperator); + tstl.createBinaryExpression( + accessExpression, + tstl.createParenthesizedExpression(right), + replacementOperator + ); const assignStatement = tstl.createAssignmentStatement(accessExpression, operatorExpression); return tstl.createDoStatement([objAndIndexDeclaration, assignStatement]); @@ -1586,7 +1766,12 @@ export class LuaTransformer { } } - public transformBitOperation(node: ts.BinaryExpression, lhs: tstl.Expression, rhs: tstl.Expression): ExpressionVisitResult { + public transformBitOperation( + node: ts.BinaryExpression, + lhs: tstl.Expression, + rhs: tstl.Expression + ): ExpressionVisitResult + { throw TSTLErrors.UnsupportedForTarget("Bitwise operations", this.options.luaTarget, node); } @@ -1595,13 +1780,25 @@ export class LuaTransformer { const val1 = this.transformExpression(node.whenTrue); const val2 = this.transformExpression(node.whenFalse); - return this.transformLuaLibFunction(LuaLibFeature.Ternary, condition, this.wrapInFunctionCall(val1), this.wrapInFunctionCall(val2)); + return this.transformLuaLibFunction( + LuaLibFeature.Ternary, + condition, + this.wrapInFunctionCall(val1), + this.wrapInFunctionCall(val2) + ); } public transformPostfixUnaryExpression(expression: ts.PostfixUnaryExpression): tstl.Expression { - const replacementOperator = - expression.operator === ts.SyntaxKind.PlusPlusToken ? tstl.SyntaxKind.AdditionOperator : tstl.SyntaxKind.SubractionOperator; - return this.transformCompoundAssignmentExpression(expression.operand, ts.createLiteral(1), replacementOperator, true); + const replacementOperator = expression.operator === ts.SyntaxKind.PlusPlusToken + ? tstl.SyntaxKind.AdditionOperator + : tstl.SyntaxKind.SubractionOperator; + + return this.transformCompoundAssignmentExpression( + expression.operand, + ts.createLiteral(1), + replacementOperator, + true + ); } public transformPrefixUnaryExpression(expression: ts.PrefixUnaryExpression): tstl.Expression { @@ -1618,13 +1815,22 @@ export class LuaTransformer { return this.transformExpression(expression.operand); case ts.SyntaxKind.MinusToken: - return tstl.createUnaryExpression(this.transformExpression(expression.operand), tstl.SyntaxKind.NegationOperator); + return tstl.createUnaryExpression( + this.transformExpression(expression.operand), + tstl.SyntaxKind.NegationOperator + ); case ts.SyntaxKind.ExclamationToken: - return tstl.createUnaryExpression(this.transformExpression(expression.operand), tstl.SyntaxKind.NotOperator); + return tstl.createUnaryExpression( + this.transformExpression(expression.operand), + tstl.SyntaxKind.NotOperator + ); case ts.SyntaxKind.TildeToken: - return tstl.createUnaryExpression(this.transformExpression(expression.operand), tstl.SyntaxKind.BitwiseNotOperator); + return tstl.createUnaryExpression( + this.transformExpression(expression.operand), + tstl.SyntaxKind.BitwiseNotOperator + ); } } @@ -1660,22 +1866,38 @@ export class LuaTransformer { return tstl.createTableExpression(properties, undefined, node); } - public transformFunctionExpression(node: ts.FunctionLikeDeclaration, context: tstl.Identifier | undefined): ExpressionVisitResult { + public transformFunctionExpression( + node: ts.FunctionLikeDeclaration, + context: tstl.Identifier | undefined + ): ExpressionVisitResult + { const type = this.checker.getTypeAtLocation(node); const hasContext = tsHelper.getFunctionContextType(type, this.checker) !== ContextType.Void; // Build parameter string - const [paramNames, dotsLiteral, spreadIdentifier] = this.transformParameters(node.parameters, hasContext ? context : undefined); + const [paramNames, dotsLiteral, spreadIdentifier] = this.transformParameters( + node.parameters, + hasContext ? context : undefined + ); const body = ts.isBlock(node.body) ? node.body : ts.createBlock([ts.createReturn(node.body)]); const transformedBody = this.transformFunctionBody(node.parameters, body, spreadIdentifier); - return tstl.createFunctionExpression(tstl.createBlock(transformedBody), paramNames, dotsLiteral, spreadIdentifier, undefined, node); + return tstl.createFunctionExpression( + tstl.createBlock(transformedBody), + paramNames, + dotsLiteral, + spreadIdentifier, + undefined, + node + ); } public transformNewExpression(node: ts.NewExpression): tstl.CallExpression { const name = this.transformExpression(node.expression); const sig = this.checker.getResolvedSignature(node); - const params = node.arguments ? this.transformArguments(node.arguments, sig, ts.createTrue()) : [tstl.createBooleanLiteral(true)]; + const params = node.arguments + ? this.transformArguments(node.arguments, sig, ts.createTrue()) + : [tstl.createBooleanLiteral(true)]; const type = this.checker.getTypeAtLocation(node); const classDecorators = tsHelper.getCustomDecorators(type, this.checker); @@ -1692,10 +1914,17 @@ export class LuaTransformer { throw TSTLErrors.InvalidDecoratorArgumentNumber("!CustomConstructor", 0, 1, node); } return tstl.createCallExpression( - tstl.createIdentifier(customDecorator.args[0]), this.transformArguments(node.arguments), undefined, node); + tstl.createIdentifier(customDecorator.args[0]), + this.transformArguments(node.arguments), undefined, node + ); } - return tstl.createCallExpression(tstl.createTableIndexExpression(name, tstl.createStringLiteral("new")), params, undefined, node); + return tstl.createCallExpression( + tstl.createTableIndexExpression(name, tstl.createStringLiteral("new")), + params, + undefined, + node + ); } public transformCallExpression(node: ts.CallExpression): tstl.Expression { @@ -1708,7 +1937,8 @@ export class LuaTransformer { node.parent && ts.isReturnStatement(node.parent) && tsHelper.isInTupleReturnFunction(node, this.checker); const isInDestructingAssignment = tsHelper.isInDestructingAssignment(node); const returnValueIsUsed = node.parent && !ts.isExpressionStatement(node.parent); - const wrapResult = isTupleReturn && !isTupleReturnForward && !isInDestructingAssignment && returnValueIsUsed && !isLuaIterator; + const wrapResult = isTupleReturn && !isTupleReturnForward&& !isInDestructingAssignment + && returnValueIsUsed && !isLuaIterator; if (ts.isPropertyAccessExpression(node.expression)) { const result = this.transformPropertyCall(node); @@ -1730,14 +1960,21 @@ export class LuaTransformer { const constructorIdentifier = tstl.createStringLiteral("constructor"); return tstl.createCallExpression( - tstl.createTableIndexExpression(tstl.createTableIndexExpression(classIdentifier, baseIdentifier), constructorIdentifier), - parameters); + tstl.createTableIndexExpression( + tstl.createTableIndexExpression(classIdentifier, baseIdentifier), + constructorIdentifier + ), + parameters + ); } const callPath = this.transformExpression(node.expression); const signatureDeclaration = signature.getDeclaration(); - if (signatureDeclaration && tsHelper.getDeclarationContextType(signatureDeclaration, this.checker) === ContextType.NonVoid && - !ts.isPropertyAccessExpression(node.expression) && !ts.isElementAccessExpression(node.expression)) { + if (signatureDeclaration + && !ts.isPropertyAccessExpression(node.expression) + && tsHelper.getDeclarationContextType(signatureDeclaration, this.checker) === ContextType.NonVoid + && !ts.isElementAccessExpression(node.expression)) + { const context = this.isStrict ? ts.createNull() : ts.createIdentifier("_G"); parameters = this.transformArguments(node.arguments, signature, context); } else { @@ -1761,12 +1998,22 @@ export class LuaTransformer { if (ownerType.symbol && ownerType.symbol.escapedName === "Math") { parameters = this.transformArguments(node.arguments); - return tstl.createCallExpression(this.transformMathExpression(node.expression.name), parameters, undefined, node); + return tstl.createCallExpression( + this.transformMathExpression(node.expression.name), + parameters, + undefined, + node + ); } if (ownerType.symbol && ownerType.symbol.escapedName === "StringConstructor") { parameters = this.transformArguments(node.arguments); - return tstl.createCallExpression(this.transformStringExpression(node.expression.name), parameters, undefined, node); + return tstl.createCallExpression( + this.transformStringExpression(node.expression.name), + parameters, + undefined, + node + ); } switch (ownerType.flags) { @@ -1815,10 +2062,17 @@ export class LuaTransformer { const parameters = this.transformArguments(node.arguments, signature); const table = this.transformExpression(node.expression.expression); const signatureDeclaration = signature.getDeclaration(); - if (!signatureDeclaration || tsHelper.getDeclarationContextType(signatureDeclaration, this.checker) !== ContextType.Void) { + if (!signatureDeclaration + || tsHelper.getDeclarationContextType(signatureDeclaration, this.checker) !== ContextType.Void) + { // table:name() - return tstl.createMethodCallExpression(table, tstl.createIdentifier(name), parameters, undefined, node); - + return tstl.createMethodCallExpression( + table, + tstl.createIdentifier(name), + parameters, + undefined, + node + ); } else { // table.name() const callPath = tstl.createTableIndexExpression(table, tstl.createStringLiteral(name)); @@ -1837,7 +2091,8 @@ export class LuaTransformer { let parameters = this.transformArguments(node.arguments, signature); const signatureDeclaration = signature.getDeclaration(); - if (!signatureDeclaration || tsHelper.getDeclarationContextType(signatureDeclaration, this.checker) !== ContextType.Void) { + if (!signatureDeclaration + || tsHelper.getDeclarationContextType(signatureDeclaration, this.checker) !== ContextType.Void) { // Pass left-side as context const context = this.transformExpression(node.expression.expression); @@ -1866,8 +2121,11 @@ export class LuaTransformer { } } - public transformArguments(params: ts.NodeArray, sig?: ts.Signature, context?: T): - tstl.Expression[] { + public transformArguments( + params: ts.NodeArray, + sig?: ts.Signature, context?: T + ): tstl.Expression[] + { const parameters: tstl.Expression[] = []; // Add context as first param if present @@ -1906,10 +2164,13 @@ export class LuaTransformer { case ts.TypeFlags.StringLiteral: return this.transformStringProperty(node); case ts.TypeFlags.Object: - if (tsHelper.isExplicitArrayType(type, this.checker)) { + if (tsHelper.isExplicitArrayType(type, this.checker)) + { return this.transformArrayProperty(node); } - if (tsHelper.isArrayType(type, this.checker) && tsHelper.isDefaultArrayPropertyName(node.name.escapedText as string)) { + else if (tsHelper.isArrayType(type, this.checker) + && tsHelper.isDefaultArrayPropertyName(node.name.escapedText as string)) + { return this.transformArrayProperty(node); } } @@ -2057,10 +2318,17 @@ export class LuaTransformer { node.arguments.length === 1 ? this.createStringCall("find", node, caller, params[0]) : this.createStringCall( - "find", node, caller, params[0], this.expressionPlusOne(params[1]), tstl.createBooleanLiteral(true)); + "find", node, caller, params[0], + this.expressionPlusOne(params[1]), + tstl.createBooleanLiteral(true) + ); return tstl.createBinaryExpression( - tstl.createBinaryExpression(stringExpression, tstl.createNumericLiteral(0), tstl.SyntaxKind.OrOperator), + tstl.createBinaryExpression( + stringExpression, + tstl.createNumericLiteral(0), + tstl.SyntaxKind.OrOperator + ), tstl.createNumericLiteral(1), tstl.SyntaxKind.SubractionOperator, undefined, @@ -2098,10 +2366,19 @@ export class LuaTransformer { } } - public createStringCall(methodName: string, tsOriginal: ts.Node, ...params: tstl.Expression[]): tstl.CallExpression { + public createStringCall( + methodName: string, + tsOriginal: ts.Node, + ...params: tstl.Expression[] + ): tstl.CallExpression + { const stringIdentifier = tstl.createIdentifier("string"); return tstl.createCallExpression( - tstl.createTableIndexExpression(stringIdentifier, tstl.createStringLiteral(methodName)), params, undefined, tsOriginal); + tstl.createTableIndexExpression(stringIdentifier, tstl.createStringLiteral(methodName)), + params, + undefined, + tsOriginal + ); } // Transpile a String._ property @@ -2110,9 +2387,16 @@ export class LuaTransformer { switch (identifierString) { case "fromCharCode": - return tstl.createTableIndexExpression(tstl.createIdentifier("string"), tstl.createStringLiteral("char")); + return tstl.createTableIndexExpression( + tstl.createIdentifier("string"), + tstl.createStringLiteral("char") + ); default: - throw TSTLErrors.UnsupportedForTarget(`string property ${identifierString}`, this.options.luaTarget, identifier); + throw TSTLErrors.UnsupportedForTarget( + `string property ${identifierString}`, + this.options.luaTarget, + identifier + ); } } @@ -2157,7 +2441,9 @@ export class LuaTransformer { case "splice": return this.transformLuaLibFunction(LuaLibFeature.ArraySplice, caller, ...params); case "join": - const parameters = node.arguments.length === 0 ? [caller, tstl.createStringLiteral(",")] : [caller].concat(params); + const parameters = node.arguments.length === 0 + ? [caller, tstl.createStringLiteral(",")] + : [caller].concat(params); return tstl.createCallExpression( tstl.createTableIndexExpression(tstl.createIdentifier("table"), tstl.createStringLiteral("concat")), @@ -2203,7 +2489,11 @@ export class LuaTransformer { } public transformAssertionExpression(node: ts.AssertionExpression): tstl.Expression { - this.validateFunctionAssignment(node, this.checker.getTypeAtLocation(node.expression), this.checker.getTypeAtLocation(node.type)); + this.validateFunctionAssignment( + node, + this.checker.getTypeAtLocation(node.expression), + this.checker.getTypeAtLocation(node.type) + ); return this.transformExpression(node.expression); } @@ -2238,10 +2528,16 @@ export class LuaTransformer { // tostring(expr).."text" parts.push(tstl.createBinaryExpression( - tstl.createCallExpression(tstl.createIdentifier("tostring"), [expr]), text, tstl.SyntaxKind.ConcatOperator)); + tstl.createCallExpression(tstl.createIdentifier("tostring"), [expr]), + text, + tstl.SyntaxKind.ConcatOperator) + ); }); - return parts.reduce((prev, current) => tstl.createBinaryExpression(prev, current, tstl.SyntaxKind.ConcatOperator)) as - tstl.BinaryExpression; + return parts.reduce((prev, current) => tstl.createBinaryExpression( + prev, + current, + tstl.SyntaxKind.ConcatOperator) + ) as tstl.BinaryExpression; } public transformPropertyName(propertyName: ts.PropertyName): tstl.Expression { @@ -2259,9 +2555,10 @@ export class LuaTransformer { public transformIdentifier(epxression: ts.Identifier, parent?: tstl.Node): tstl.Identifier { if (epxression.originalKeywordKind === ts.SyntaxKind.UndefinedKeyword) { - return tstl.createIdentifier("nil"); // TODO this is a hack that allows use to keep Identifier as return time - // as changing that would break a lot of stuff. - // But this should be changed to retunr tstl.createNilLiteral() at somepoint + return tstl.createIdentifier("nil"); // TODO this is a hack that allows use to keep Identifier + // as return time as changing that would break a lot of stuff. + // But this should be changed to retun tstl.createNilLiteral() + // at some point. } let escapedText = epxression.escapedText as string; const underScoreCharCode = "_".charCodeAt(0); @@ -2329,8 +2626,11 @@ export class LuaTransformer { this.luaLibFeatureSet.add(feature); } - public createImmediatelyInvokedFunctionExpression(statements: tstl.Statement[], result: tstl.Expression | tstl.Expression[]): - tstl.CallExpression { + public createImmediatelyInvokedFunctionExpression( + statements: tstl.Statement[], + result: tstl.Expression | tstl.Expression[] + ): tstl.CallExpression + { const body = statements ? statements.slice(0) : []; body.push(tstl.createReturnStatement(Array.isArray(result) ? result : [result])); const iife = tstl.createFunctionExpression(tstl.createBlock(body)); @@ -2354,7 +2654,9 @@ export class LuaTransformer { if (this.options.rootDir) { // Calculate path relative to project root // and replace path.sep with dots (lua doesn't know paths) - const relativePathToRoot = this.pathToLuaRequirePath(absolutePathToImport.replace(this.options.rootDir, "").slice(1)); + const relativePathToRoot = this.pathToLuaRequirePath( + absolutePathToImport.replace(this.options.rootDir, "").slice(1) + ); return relativePathToRoot; } @@ -2365,8 +2667,13 @@ export class LuaTransformer { return filePath.replace(new RegExp("\\\\|\/", "g"), "."); } - private createLocalOrGlobalDeclaration(lhs: tstl.Identifier, rhs: tstl.Expression, parent?: tstl.Node, tsOriginal?: ts.Node): - tstl.Statement { + private createLocalOrGlobalDeclaration( + lhs: tstl.Identifier, + rhs: tstl.Expression, + parent?: tstl.Node, + tsOriginal?: ts.Node + ): tstl.Statement + { if (this.isModule || this.currentNamespace) { return tstl.createVariableDeclarationStatement(lhs, rhs, parent, tsOriginal); } else { @@ -2429,8 +2736,10 @@ export class LuaTransformer { } } - if ((toType.flags & ts.TypeFlags.Object) !== 0 && ((toType as ts.ObjectType).objectFlags & ts.ObjectFlags.ClassOrInterface) !== 0 && - toType.symbol && toType.symbol.members && fromType.symbol && fromType.symbol.members) { + if ((toType.flags & ts.TypeFlags.Object) !== 0 + && ((toType as ts.ObjectType).objectFlags & ts.ObjectFlags.ClassOrInterface) !== 0 + && toType.symbol && toType.symbol.members && fromType.symbol && fromType.symbol.members) + { // Recurse into interfaces toType.symbol.members.forEach((toMember, memberName) => { const fromMember = fromType.symbol.members.get(memberName); From 8a4d5c9f243e4fa3be4cf2aeadeb9078894e7451 Mon Sep 17 00:00:00 2001 From: Perryvw Date: Fri, 11 Jan 2019 20:45:50 +0100 Subject: [PATCH 3/3] Fixed header showing up in tests --- test/src/util.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/test/src/util.ts b/test/src/util.ts index 8089b4514..b2b1f5832 100644 --- a/test/src/util.ts +++ b/test/src/util.ts @@ -13,10 +13,18 @@ import * as fs from "fs"; import { LuaTransformer } from "../../src/LuaTransformer"; export function transpileString(str: string, options?: CompilerOptions): string { - if (options && options.addHeader === undefined) { - options.addHeader = false; + if (options) { + if (options.addHeader === undefined) { + options.addHeader = false; + } + return compilerTranspileString(str, options); + } else { + return compilerTranspileString(str, { + luaLibImport: LuaLibImportKind.Require, + luaTarget: LuaTarget.Lua53, + addHeader: false, + }); } - return compilerTranspileString(str, options); } export function executeLua(luaStr: string, withLib = true): any {