From 0d0e17aa563f4dbdec8cad254f56cf00e813fa77 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 8 Jul 2019 23:19:03 +0500 Subject: [PATCH 01/14] Remove duplication in decorator name finding --- src/Decorator.ts | 40 ++++------------------------------------ 1 file changed, 4 insertions(+), 36 deletions(-) diff --git a/src/Decorator.ts b/src/Decorator.ts index 799f792c4..330685202 100644 --- a/src/Decorator.ts +++ b/src/Decorator.ts @@ -4,51 +4,19 @@ export class Decorator { } public static getDecoratorKind(decoratorKindString: string): DecoratorKind | undefined { - switch (decoratorKindString.toLowerCase()) { - case "extension": - return DecoratorKind.Extension; - case "metaextension": - return DecoratorKind.MetaExtension; - case "customconstructor": - return DecoratorKind.CustomConstructor; - case "compilemembersonly": - return DecoratorKind.CompileMembersOnly; - case "noresolution": - return DecoratorKind.NoResolution; - case "pureabstract": - return DecoratorKind.PureAbstract; - case "phantom": - return DecoratorKind.Phantom; - case "tuplereturn": - return DecoratorKind.TupleReturn; - case "luaiterator": - return DecoratorKind.LuaIterator; - case "luatable": - return DecoratorKind.LuaTable; - case "noself": - return DecoratorKind.NoSelf; - case "noselfinfile": - return DecoratorKind.NoSelfInFile; - case "vararg": - return DecoratorKind.Vararg; - case "forrange": - return DecoratorKind.ForRange; - } - - return undefined; + return Object.values(DecoratorKind).find( + decoratorKind => decoratorKind.toLowerCase() === decoratorKindString.toLowerCase() + ); } public kind: DecoratorKind; - public args: string[]; - - constructor(name: string, args: string[]) { + constructor(name: string, public args: string[]) { const kind = Decorator.getDecoratorKind(name); if (kind === undefined) { throw new Error(`Failed to parse decorator '${name}'`); } this.kind = kind; - this.args = args; } } From 2112cd4ca18c66bbfc865fb5953d5281cdd38382 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 8 Jul 2019 23:20:32 +0500 Subject: [PATCH 02/14] Make TableExpression.fields not optional --- src/LuaAST.ts | 4 ++-- src/LuaPrinter.ts | 12 +----------- src/LuaTransformer.ts | 20 +++++++++----------- src/TSHelper.ts | 2 +- 4 files changed, 13 insertions(+), 25 deletions(-) diff --git a/src/LuaAST.ts b/src/LuaAST.ts index b8402d808..1ded4765b 100644 --- a/src/LuaAST.ts +++ b/src/LuaAST.ts @@ -687,7 +687,7 @@ export function createTableFieldExpression( export interface TableExpression extends Expression { kind: SyntaxKind.TableExpression; - fields?: TableFieldExpression[]; + fields: TableFieldExpression[]; } export function isTableExpression(node: Node): node is TableExpression { @@ -695,7 +695,7 @@ export function isTableExpression(node: Node): node is TableExpression { } export function createTableExpression( - fields?: TableFieldExpression[], + fields: TableFieldExpression[] = [], tsOriginal?: ts.Node, parent?: Node ): TableExpression { diff --git a/src/LuaPrinter.ts b/src/LuaPrinter.ts index e5058cbf5..880fa03fb 100644 --- a/src/LuaPrinter.ts +++ b/src/LuaPrinter.ts @@ -571,17 +571,7 @@ export class LuaPrinter { } public printTableExpression(expression: tstl.TableExpression): SourceNode { - const chunks: SourceChunk[] = []; - - chunks.push("{"); - - if (expression.fields) { - chunks.push(...this.printExpressionList(expression.fields)); - } - - chunks.push("}"); - - return this.createSourceNode(expression, chunks); + return this.createSourceNode(expression, ["{", ...this.printExpressionList(expression.fields), "}"]); } public printUnaryExpression(expression: tstl.UnaryExpression): SourceNode { diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index b1d54826d..c6593e4e9 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -785,7 +785,7 @@ export class LuaTransformer { const result: tstl.Statement[] = []; // [____exports.]className = {} - const classTable: tstl.Expression = tstl.createTableExpression([]); + const classTable: tstl.Expression = tstl.createTableExpression(); const classVar = this.createLocalOrExportedOrGlobalDeclaration(className, classTable, statement); result.push(...classVar); @@ -4830,16 +4830,14 @@ export class LuaTransformer { const stringTableLiteral = tstl.createTableExpression( strings.map(partialString => tstl.createTableFieldExpression(tstl.createStringLiteral(partialString))) ); - if (stringTableLiteral.fields) { - const rawStringArray = tstl.createTableExpression( - rawStrings.map(stringLiteral => - tstl.createTableFieldExpression(tstl.createStringLiteral(stringLiteral)) - ) - ); - stringTableLiteral.fields.push( - tstl.createTableFieldExpression(rawStringArray, tstl.createStringLiteral("raw")) - ); - } + const rawStringArray = tstl.createTableExpression( + rawStrings.map(stringLiteral => + tstl.createTableFieldExpression(tstl.createStringLiteral(stringLiteral)) + ) + ); + stringTableLiteral.fields.push( + tstl.createTableFieldExpression(rawStringArray, tstl.createStringLiteral("raw")) + ); // Evaluate if there is a self parameter to be used. const signature = this.checker.getResolvedSignature(expression); diff --git a/src/TSHelper.ts b/src/TSHelper.ts index b587f99e9..572e2d00c 100644 --- a/src/TSHelper.ts +++ b/src/TSHelper.ts @@ -869,7 +869,7 @@ export function isSimpleExpression(expression: tstl.Expression): boolean { case tstl.SyntaxKind.TableExpression: const tableExpression = expression as tstl.TableExpression; - return !tableExpression.fields || tableExpression.fields.every(e => isSimpleExpression(e)); + return tableExpression.fields.every(e => isSimpleExpression(e)); case tstl.SyntaxKind.TableFieldExpression: const fieldExpression = expression as tstl.TableFieldExpression; From e144a53093be0df6b84e8e47c537c951183053b0 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 8 Jul 2019 23:26:09 +0500 Subject: [PATCH 03/14] Remove unsound cast --- src/LuaTransformer.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index c6593e4e9..513f823bf 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -3025,7 +3025,7 @@ export class LuaTransformer { // Destructuring assignment const left = expression.left.elements.length > 0 - ? expression.left.elements.map(e => this.transformArrayBindingExpression(e)) + ? expression.left.elements.map(e => this.transformArrayBindingElement(e)) : [tstl.createAnonymousIdentifier(expression.left)]; let right: tstl.Expression[]; if (ts.isArrayLiteralExpression(expression.right)) { @@ -4734,11 +4734,7 @@ export class LuaTransformer { } } - public transformArrayBindingElement(name: ts.ArrayBindingElement): ExpressionVisitResult { - return this.transformArrayBindingExpression(name as ts.Expression); - } - - public transformArrayBindingExpression(name: ts.Expression): ExpressionVisitResult { + public transformArrayBindingElement(name: ts.ArrayBindingElement | ts.Expression): ExpressionVisitResult { if (ts.isOmittedExpression(name)) { return this.transformOmittedExpression(name); } else if (ts.isIdentifier(name)) { From 83ab3d4ea8736a224ae7f9042e953059bec44c1c Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 8 Jul 2019 23:33:38 +0500 Subject: [PATCH 04/14] Remove use of escapedText and __String --- src/LuaAST.ts | 6 ++--- src/LuaTransformer.ts | 54 +++++++++++++++++++++---------------------- 2 files changed, 29 insertions(+), 31 deletions(-) diff --git a/src/LuaAST.ts b/src/LuaAST.ts index 1ded4765b..ee6c8002b 100644 --- a/src/LuaAST.ts +++ b/src/LuaAST.ts @@ -614,7 +614,7 @@ export function isStringLiteral(node: Node): node is StringLiteral { return node.kind === SyntaxKind.StringLiteral; } -export function createStringLiteral(value: string | ts.__String, tsOriginal?: ts.Node, parent?: Node): StringLiteral { +export function createStringLiteral(value: string, tsOriginal?: ts.Node, parent?: Node): StringLiteral { const expression = createNode(SyntaxKind.StringLiteral, tsOriginal, parent) as StringLiteral; expression.value = value as string; return expression; @@ -839,14 +839,14 @@ export function isIdentifier(node: Node): node is Identifier { } export function createIdentifier( - text: string | ts.__String, + text: string, tsOriginal?: ts.Node, symbolId?: SymbolId, originalName?: string, parent?: Node ): Identifier { const expression = createNode(SyntaxKind.Identifier, tsOriginal, parent) as Identifier; - expression.text = text as string; + expression.text = text; expression.symbolId = symbolId; expression.originalName = originalName; return expression; diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index 513f823bf..b8b04aece 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -3878,7 +3878,7 @@ export class LuaTransformer { // if ownerType inherits from an array, use array calls where appropriate if ( tsHelper.isArrayType(ownerType, this.checker, this.program) && - tsHelper.isDefaultArrayCallMethodName(node.expression.name.escapedText as string) + tsHelper.isDefaultArrayCallMethodName(node.expression.name.text) ) { return this.transformArrayCallExpression(node); } @@ -3894,7 +3894,7 @@ export class LuaTransformer { return tstl.createCallExpression(this.transformExpression(node.expression), parameters); } else { // Replace last . with : here - const name = node.expression.name.escapedText; + const name = node.expression.name.text; if (name === "toString") { const toStringIdentifier = tstl.createIdentifier("tostring"); return tstl.createCallExpression( @@ -4096,7 +4096,7 @@ export class LuaTransformer { // Transpile a Math._ property protected transformMathExpression(identifier: ts.Identifier): tstl.Expression { - const name = identifier.escapedText as string; + const name = identifier.text; switch (name) { case "PI": const property = tstl.createStringLiteral("pi"); @@ -4122,7 +4122,7 @@ export class LuaTransformer { const expression = node.expression as ts.PropertyAccessExpression; const signature = this.checker.getResolvedSignature(node); const params = this.transformArguments(node.arguments, signature); - const expressionName = expression.name.escapedText as string; + const expressionName = expression.name.text; switch (expressionName) { // math.tan(x / y) case "atan2": { @@ -4192,7 +4192,7 @@ export class LuaTransformer { // Transpile access of string properties, only supported properties are allowed protected transformStringProperty(node: ts.PropertyAccessExpression): tstl.UnaryExpression { - switch (node.name.escapedText) { + switch (node.name.text) { case "length": let expression = this.transformExpression(node.expression); if (ts.isTemplateExpression(node.expression)) { @@ -4200,13 +4200,13 @@ export class LuaTransformer { } return tstl.createUnaryExpression(expression, tstl.SyntaxKind.LengthOperator, node); default: - throw TSTLErrors.UnsupportedProperty("string", node.name.escapedText as string, node); + throw TSTLErrors.UnsupportedProperty("string", node.name.text, node); } } // Transpile access of array properties, only supported properties are allowed protected transformArrayProperty(node: ts.PropertyAccessExpression): tstl.UnaryExpression | undefined { - switch (node.name.escapedText) { + switch (node.name.text) { case "length": let expression = this.transformExpression(node.expression); if (tstl.isTableExpression(expression)) { @@ -4219,12 +4219,12 @@ export class LuaTransformer { } protected transformLuaTableProperty(node: ts.PropertyAccessExpression): tstl.UnaryExpression { - switch (node.name.escapedText) { + switch (node.name.text) { case "length": const propertyAccessExpression = this.transformExpression(node.expression); return tstl.createUnaryExpression(propertyAccessExpression, tstl.SyntaxKind.LengthOperator, node); default: - throw TSTLErrors.UnsupportedProperty("LuaTable", node.name.escapedText as string, node); + throw TSTLErrors.UnsupportedProperty("LuaTable", node.name.text, node); } } @@ -4281,7 +4281,7 @@ export class LuaTransformer { const params = this.transformArguments(node.arguments, signature); const caller = this.transformExpression(expression.expression); - const expressionName = expression.name.escapedText as string; + const expressionName = expression.name.text; switch (expressionName) { case "replace": return this.transformLuaLibFunction(LuaLibFeature.StringReplace, node, caller, ...params); @@ -4424,7 +4424,7 @@ export class LuaTransformer { // Transpile a String._ property protected transformStringExpression(identifier: ts.Identifier): ExpressionVisitResult { - const identifierString = identifier.escapedText as string; + const identifierString = identifier.text; switch (identifierString) { case "fromCharCode": @@ -4445,7 +4445,7 @@ export class LuaTransformer { protected transformObjectCallExpression(expression: ts.CallExpression): ExpressionVisitResult { const method = expression.expression as ts.PropertyAccessExpression; const parameters = this.transformArguments(expression.arguments); - const methodName = method.name.escapedText; + const methodName = method.name.text; switch (methodName) { case "assign": @@ -4465,7 +4465,7 @@ export class LuaTransformer { protected transformConsoleCallExpression(expression: ts.CallExpression): ExpressionVisitResult { const method = expression.expression as ts.PropertyAccessExpression; - const methodName = method.name.escapedText; + const methodName = method.name.text; const signature = this.checker.getResolvedSignature(expression); switch (methodName) { @@ -4543,7 +4543,7 @@ export class LuaTransformer { const method = expression.expression as ts.PropertyAccessExpression; const signature = this.checker.getResolvedSignature(expression); const parameters = this.transformArguments(expression.arguments, signature); - const methodName = method.name.escapedText; + const methodName = method.name.text; switch (methodName) { case "for": @@ -4561,7 +4561,7 @@ export class LuaTransformer { protected transformNumberCallExpression(expression: ts.CallExpression): tstl.CallExpression { const method = expression.expression as ts.PropertyAccessExpression; const parameters = this.transformArguments(expression.arguments); - const methodName = method.name.escapedText; + const methodName = method.name.text; switch (methodName) { case "isNaN": @@ -4577,7 +4577,7 @@ export class LuaTransformer { expression: ts.CallExpression & { expression: ts.PropertyAccessExpression }, isWithinExpressionStatement: boolean ): void { - const methodName = expression.expression.name.escapedText; + const methodName = expression.expression.name.text; if (expression.arguments.some(argument => ts.isSpreadElement(argument))) { throw TSTLErrors.ForbiddenLuaTableUseException("Arguments cannot be spread.", expression); } @@ -4607,9 +4607,9 @@ export class LuaTransformer { expression: { expression: ts.PropertyAccessExpression }; } ): tstl.VariableDeclarationStatement | tstl.AssignmentStatement { - const methodName = node.expression.expression.name.escapedText; + const methodName = node.expression.expression.name.text; const signature = this.checker.getResolvedSignature(node.expression); - const tableName = (node.expression.expression.expression as ts.Identifier).escapedText; + const tableName = (node.expression.expression.expression as ts.Identifier).text; const luaTable = tstl.createIdentifier(tableName); const params = this.transformArguments((node.expression as ts.CallExpression).arguments, signature); @@ -4635,9 +4635,9 @@ export class LuaTransformer { expression: ts.CallExpression & { expression: ts.PropertyAccessExpression } ): tstl.Expression { const method = expression.expression; - const methodName = method.name.escapedText; + const methodName = method.name.text; const signature = this.checker.getResolvedSignature(expression); - const tableName = (method.expression as ts.Identifier).escapedText; + const tableName = (method.expression as ts.Identifier).text; const luaTable = tstl.createIdentifier(tableName); const params = this.transformArguments(expression.arguments, signature); @@ -4654,7 +4654,7 @@ export class LuaTransformer { const signature = this.checker.getResolvedSignature(node); const params = this.transformArguments(node.arguments, signature); const caller = this.transformExpression(expression.expression); - const expressionName = expression.name.escapedText; + const expressionName = expression.name.text; switch (expressionName) { case "concat": return this.transformLuaLibFunction(LuaLibFeature.ArrayConcat, node, caller, ...params); @@ -4708,7 +4708,7 @@ export class LuaTransformer { case "flatMap": return this.transformLuaLibFunction(LuaLibFeature.ArrayFlatMap, node, caller, ...params); default: - throw TSTLErrors.UnsupportedProperty("array", expressionName as string, node); + throw TSTLErrors.UnsupportedProperty("array", expressionName, node); } } @@ -4721,7 +4721,7 @@ export class LuaTransformer { const signature = this.checker.getResolvedSignature(node); const params = this.transformArguments(node.arguments, signature); const caller = this.transformExpression(expression.expression); - const expressionName = expression.name.escapedText; + const expressionName = expression.name.text; switch (expressionName) { case "apply": return this.transformLuaLibFunction(LuaLibFeature.FunctionApply, node, caller, ...params); @@ -4730,7 +4730,7 @@ export class LuaTransformer { case "call": return this.transformLuaLibFunction(LuaLibFeature.FunctionCall, node, caller, ...params); default: - throw TSTLErrors.UnsupportedProperty("function", expressionName as string, node); + throw TSTLErrors.UnsupportedProperty("function", expressionName, node); } } @@ -4827,9 +4827,7 @@ export class LuaTransformer { strings.map(partialString => tstl.createTableFieldExpression(tstl.createStringLiteral(partialString))) ); const rawStringArray = tstl.createTableExpression( - rawStrings.map(stringLiteral => - tstl.createTableFieldExpression(tstl.createStringLiteral(stringLiteral)) - ) + rawStrings.map(stringLiteral => tstl.createTableFieldExpression(tstl.createStringLiteral(stringLiteral))) ); stringTableLiteral.fields.push( tstl.createTableFieldExpression(rawStringArray, tstl.createStringLiteral("raw")) @@ -5352,7 +5350,7 @@ export class LuaTransformer { const leftType = this.checker.getTypeAtLocation(node.left.expression); const decorators = tsHelper.getCustomDecorators(leftType, this.checker); if (decorators.has(DecoratorKind.LuaTable)) { - switch (node.left.name.escapedText as string) { + switch (node.left.name.text) { case "length": throw TSTLErrors.ForbiddenLuaTableUseException( `A LuaTable object's length cannot be re-assigned.`, From 93ad2bca8eb56c392dc8195e9f669f87f7698c80 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 8 Jul 2019 23:35:04 +0500 Subject: [PATCH 05/14] Remove getIdentifierText --- src/LuaTransformer.ts | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index b8b04aece..0b7dab000 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -517,7 +517,7 @@ export class LuaTransformer { } public transformQualifiedName(qualifiedName: ts.QualifiedName): ExpressionVisitResult { - const right = tstl.createStringLiteral(this.getIdentifierText(qualifiedName.right), qualifiedName.right); + const right = tstl.createStringLiteral(qualifiedName.right.text, qualifiedName.right); const left = this.transformEntityName(qualifiedName.left); return tstl.createTableIndexExpression(left, right, qualifiedName); @@ -4045,7 +4045,7 @@ export class LuaTransformer { } public transformPropertyAccessExpression(expression: ts.PropertyAccessExpression): ExpressionVisitResult { - const property = this.getIdentifierText(expression.name); + const property = expression.name.text; const constEnumValue = this.tryGetConstEnumValue(expression); if (constEnumValue) { @@ -4884,14 +4884,10 @@ export class LuaTransformer { const value = Number(propertyName.text); return tstl.createNumericLiteral(value, propertyName); } else { - return tstl.createStringLiteral(this.getIdentifierText(propertyName)); + return tstl.createStringLiteral(propertyName.text); } } - protected getIdentifierText(identifier: ts.Identifier): string { - return ts.idText(identifier); - } - public transformIdentifier(identifier: ts.Identifier): tstl.Identifier { if (tsHelper.isForRangeType(identifier, this.checker)) { const callExpression = tsHelper.findFirstNodeAbove(identifier, ts.isCallExpression); @@ -4904,11 +4900,11 @@ export class LuaTransformer { } const text = this.hasUnsafeIdentifierName(identifier) - ? this.createSafeName(this.getIdentifierText(identifier)) - : this.getIdentifierText(identifier); + ? this.createSafeName(identifier.text) + : identifier.text; const symbolId = this.getIdentifierSymbolId(identifier); - return tstl.createIdentifier(text, identifier, symbolId, this.getIdentifierText(identifier)); + return tstl.createIdentifier(text, identifier, symbolId, identifier.text); } protected transformIdentifierExpression(expression: ts.Identifier): tstl.Expression { @@ -4923,7 +4919,7 @@ export class LuaTransformer { return tstl.createNilLiteral(); } - switch (this.getIdentifierText(expression)) { + switch (expression.text) { case "NaN": return tstl.createParenthesizedExpression( tstl.createBinaryExpression( @@ -5420,7 +5416,7 @@ export class LuaTransformer { ? this.createSafeName(valueSymbol.name) : valueSymbol.name; } else { - const propertyName = this.getIdentifierText(propertyIdentifier); + const propertyName = propertyIdentifier.text; if (luaKeywords.has(propertyName) || !tsHelper.isValidLuaIdentifier(propertyName)) { // Catch ambient declarations of identifiers with bad names throw TSTLErrors.InvalidAmbientIdentifierName(propertyIdentifier); From f17da36e6c32aded58fc1f95ce8ee489f09bc078 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 8 Jul 2019 23:42:50 +0500 Subject: [PATCH 06/14] Remove function assignment validation in type assertion --- src/LuaTransformer.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index 0b7dab000..eb39d6b9a 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -4747,11 +4747,6 @@ export class LuaTransformer { } public transformAssertionExpression(expression: ts.AssertionExpression): ExpressionVisitResult { - this.validateFunctionAssignment( - expression, - this.checker.getTypeAtLocation(expression.expression), - this.checker.getTypeAtLocation(expression.type) - ); return this.transformExpression(expression.expression); } From ae34353b2d798819456abae2c3fa3b2f33620e7f Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 8 Jul 2019 23:48:56 +0500 Subject: [PATCH 07/14] Make LuaLib.loadFeatures a regular function --- build_lualib.ts | 8 ++------ src/LuaLib.ts | 44 ++++++++++++++++++++++---------------------- src/LuaPrinter.ts | 6 +++--- 3 files changed, 27 insertions(+), 31 deletions(-) diff --git a/build_lualib.ts b/build_lualib.ts index 330a3ef04..1f6897f0d 100644 --- a/build_lualib.ts +++ b/build_lualib.ts @@ -2,7 +2,7 @@ import * as fs from "fs"; import * as path from "path"; import * as ts from "typescript"; import * as tstl from "./src"; -import { LuaLib } from "./src/LuaLib"; +import { loadLuaLibFeatures } from "./src/LuaLib"; const configFileName = path.resolve(__dirname, "src/lualib/tsconfig.json"); const { emitResult, diagnostics } = tstl.transpileProject(configFileName); @@ -16,8 +16,4 @@ if (fs.existsSync(bundlePath)) { fs.unlinkSync(bundlePath); } -const emitHost = { - readFile: (path: string) => fs.readFileSync(path, "utf-8"), - writeFile: fs.writeFileSync, -}; -fs.writeFileSync(bundlePath, LuaLib.loadFeatures(Object.values(tstl.LuaLibFeature), emitHost)); +fs.writeFileSync(bundlePath, loadLuaLibFeatures(Object.values(tstl.LuaLibFeature), ts.sys)); diff --git a/src/LuaLib.ts b/src/LuaLib.ts index d611a28bb..aa7c3e432 100644 --- a/src/LuaLib.ts +++ b/src/LuaLib.ts @@ -72,32 +72,32 @@ const luaLibDependencies: { [lib in LuaLibFeature]?: LuaLibFeature[] } = { SymbolRegistry: [LuaLibFeature.Symbol], }; -export class LuaLib { - public static loadFeatures(features: Iterable, emitHost: EmitHost): string { - let result = ""; +export function loadLuaLibFeatures(features: Iterable, emitHost: EmitHost): string { + let result = ""; - const loadedFeatures = new Set(); + const loadedFeatures = new Set(); - function load(feature: LuaLibFeature): void { - if (!loadedFeatures.has(feature)) { - loadedFeatures.add(feature); - const dependencies = luaLibDependencies[feature]; - if (dependencies) { - dependencies.forEach(load); - } - const featureFile = path.resolve(__dirname, `../dist/lualib/${feature}.lua`); - const luaLibFeature = emitHost.readFile(featureFile); - if (luaLibFeature !== undefined) { - result += luaLibFeature.toString() + "\n"; - } else { - throw new Error(`Could not read lualib feature ../dist/lualib/${feature}.lua`); - } - } + function load(feature: LuaLibFeature): void { + if (loadedFeatures.has(feature)) return; + loadedFeatures.add(feature); + + const dependencies = luaLibDependencies[feature]; + if (dependencies) { + dependencies.forEach(load); } - for (const feature of features) { - load(feature); + const featureFile = path.resolve(__dirname, `../dist/lualib/${feature}.lua`); + const luaLibFeature = emitHost.readFile(featureFile); + if (luaLibFeature !== undefined) { + result += luaLibFeature + "\n"; + } else { + throw new Error(`Could not read lualib feature ../dist/lualib/${feature}.lua`); } - return result; } + + for (const feature of features) { + load(feature); + } + + return result; } diff --git a/src/LuaPrinter.ts b/src/LuaPrinter.ts index 880fa03fb..ea08fc906 100644 --- a/src/LuaPrinter.ts +++ b/src/LuaPrinter.ts @@ -3,9 +3,9 @@ import { Mapping, SourceMapGenerator, SourceNode } from "source-map"; import { CompilerOptions, LuaLibImportKind } from "./CompilerOptions"; import * as tstl from "./LuaAST"; import { luaKeywords } from "./LuaKeywords"; -import { LuaLib, LuaLibFeature } from "./LuaLib"; -import * as tsHelper from "./TSHelper"; +import { loadLuaLibFeatures, LuaLibFeature } from "./LuaLib"; import { EmitHost } from "./Transpile"; +import * as tsHelper from "./TSHelper"; type SourceChunk = string | SourceNode; @@ -132,7 +132,7 @@ export class LuaPrinter { // Inline lualib features else if (luaLibImport === LuaLibImportKind.Inline && luaLibFeatures.size > 0) { header += "-- Lua Library inline imports\n"; - header += LuaLib.loadFeatures(luaLibFeatures, this.emitHost); + header += loadLuaLibFeatures(luaLibFeatures, this.emitHost); } } From 31b5c47b66b975d5da110129c54f844c3db9d947 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Tue, 9 Jul 2019 00:11:36 +0500 Subject: [PATCH 08/14] Remove TODOs for old TS upgrades --- src/TSTransformers.ts | 15 ++++----------- src/Transpile.ts | 2 -- src/lualib/SourceMapTraceBack.ts | 10 +++++----- src/lualib/declarations/global.d.ts | 12 ++++++------ 4 files changed, 15 insertions(+), 24 deletions(-) diff --git a/src/TSTransformers.ts b/src/TSTransformers.ts index 720fc98cd..81241810c 100644 --- a/src/TSTransformers.ts +++ b/src/TSTransformers.ts @@ -10,17 +10,10 @@ export function getCustomTransformers( customTransformers: ts.CustomTransformers, onSourceFile: (sourceFile: ts.SourceFile) => void ): ts.CustomTransformers { - // TODO: https://github.com/Microsoft/TypeScript/issues/28310 - const forEachSourceFile = (node: ts.SourceFile, callback: (sourceFile: ts.SourceFile) => ts.SourceFile) => - ts.isBundle(node) - ? ((ts.updateBundle(node, node.sourceFiles.map(callback)) as unknown) as ts.SourceFile) - : callback(node); - - const luaTransformer: ts.TransformerFactory = () => node => - forEachSourceFile(node, sourceFile => { - onSourceFile(sourceFile); - return ts.createSourceFile(sourceFile.fileName, "", ts.ScriptTarget.ESNext); - }); + const luaTransformer: ts.TransformerFactory = () => sourceFile => { + onSourceFile(sourceFile); + return ts.createSourceFile(sourceFile.fileName, "", ts.ScriptTarget.ESNext); + }; const transformersFromOptions = loadTransformersFromOptions(program, diagnostics); return { diff --git a/src/Transpile.ts b/src/Transpile.ts index b0d0d4c0a..12dc51d43 100644 --- a/src/Transpile.ts +++ b/src/Transpile.ts @@ -47,8 +47,6 @@ export function transpile({ const diagnostics: ts.Diagnostic[] = []; let transpiledFiles: TranspiledFile[] = []; - // TODO: Included in TS3.5 - type Omit = Pick>; const updateTranspiledFile = (fileName: string, update: Omit) => { const file = transpiledFiles.find(f => f.fileName === fileName); if (file) { diff --git a/src/lualib/SourceMapTraceBack.ts b/src/lualib/SourceMapTraceBack.ts index 4aed661cc..c5fa8c12c 100644 --- a/src/lualib/SourceMapTraceBack.ts +++ b/src/lualib/SourceMapTraceBack.ts @@ -1,16 +1,16 @@ // TODO: In the future, change this to __TS__RegisterFileInfo and provide tstl interface to // get some metadata about transpilation. function __TS__SourceMapTraceBack(this: void, fileName: string, sourceMap: { [line: number]: number }): void { - _G["__TS__sourcemap"] = _G["__TS__sourcemap"] || {}; - _G["__TS__sourcemap"][fileName] = sourceMap; + _G.__TS__sourcemap = _G.__TS__sourcemap || {}; + _G.__TS__sourcemap[fileName] = sourceMap; if (_G.__TS__originalTraceback === undefined) { _G.__TS__originalTraceback = debug.traceback; debug.traceback = (thread, message, level) => { - const trace = _G["__TS__originalTraceback"](thread, message, level); + const trace = _G.__TS__originalTraceback(thread, message, level); const [result] = string.gsub(trace, "(%S+).lua:(%d+)", (file, line) => { - if (_G["__TS__sourcemap"][file + ".lua"] && _G["__TS__sourcemap"][file + ".lua"][line]) { - return `${file}.ts:${_G["__TS__sourcemap"][file + ".lua"][line]}`; + if (_G.__TS__sourcemap[file + ".lua"] && _G.__TS__sourcemap[file + ".lua"][line]) { + return `${file}.ts:${_G.__TS__sourcemap[file + ".lua"][line]}`; } return `${file}.lua:${line}`; }); diff --git a/src/lualib/declarations/global.d.ts b/src/lualib/declarations/global.d.ts index b34b857f4..8a102241d 100644 --- a/src/lualib/declarations/global.d.ts +++ b/src/lualib/declarations/global.d.ts @@ -1,11 +1,11 @@ /** @noSelfInFile */ -// TODO: TS3.4: typeof globalThis -declare const _G: { - // Required? - __TS__originalTraceback(this: void, thread?: any, message?: string, level?: number): string; - [key: string]: any; -}; +declare const _G: typeof globalThis; + +declare var __TS__sourcemap: Record | undefined; +declare var __TS__originalTraceback: + | ((this: void, thread?: any, message?: string, level?: number) => string) + | undefined; declare function tonumber(value: any, base?: number): number | undefined; declare function type( From 6d78e35e5969953173e3c8397b4441034a874b5a Mon Sep 17 00:00:00 2001 From: ark120202 Date: Tue, 9 Jul 2019 00:15:17 +0500 Subject: [PATCH 09/14] Use globalThis instead of _G --- src/lualib/SourceMapTraceBack.ts | 15 ++++++++------- src/lualib/declarations/global.d.ts | 2 -- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/lualib/SourceMapTraceBack.ts b/src/lualib/SourceMapTraceBack.ts index c5fa8c12c..374f52b10 100644 --- a/src/lualib/SourceMapTraceBack.ts +++ b/src/lualib/SourceMapTraceBack.ts @@ -1,16 +1,17 @@ // TODO: In the future, change this to __TS__RegisterFileInfo and provide tstl interface to // get some metadata about transpilation. function __TS__SourceMapTraceBack(this: void, fileName: string, sourceMap: { [line: number]: number }): void { - _G.__TS__sourcemap = _G.__TS__sourcemap || {}; - _G.__TS__sourcemap[fileName] = sourceMap; + globalThis.__TS__sourcemap = globalThis.__TS__sourcemap || {}; + globalThis.__TS__sourcemap[fileName] = sourceMap; - if (_G.__TS__originalTraceback === undefined) { - _G.__TS__originalTraceback = debug.traceback; + if (globalThis.__TS__originalTraceback === undefined) { + globalThis.__TS__originalTraceback = debug.traceback; debug.traceback = (thread, message, level) => { - const trace = _G.__TS__originalTraceback(thread, message, level); + const trace = globalThis.__TS__originalTraceback(thread, message, level); const [result] = string.gsub(trace, "(%S+).lua:(%d+)", (file, line) => { - if (_G.__TS__sourcemap[file + ".lua"] && _G.__TS__sourcemap[file + ".lua"][line]) { - return `${file}.ts:${_G.__TS__sourcemap[file + ".lua"][line]}`; + const fileSourceMap = globalThis.__TS__sourcemap[file + ".lua"]; + if (fileSourceMap && fileSourceMap[line]) { + return `${file}.ts:${fileSourceMap[line]}`; } return `${file}.lua:${line}`; }); diff --git a/src/lualib/declarations/global.d.ts b/src/lualib/declarations/global.d.ts index 8a102241d..e27b9ecea 100644 --- a/src/lualib/declarations/global.d.ts +++ b/src/lualib/declarations/global.d.ts @@ -1,7 +1,5 @@ /** @noSelfInFile */ -declare const _G: typeof globalThis; - declare var __TS__sourcemap: Record | undefined; declare var __TS__originalTraceback: | ((this: void, thread?: any, message?: string, level?: number) => string) From 464bba1357574853add96e3baab9d906b88e4c24 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Tue, 9 Jul 2019 00:26:49 +0500 Subject: [PATCH 10/14] Remove TS prefix from 4-underscore-prefixed identifiers --- src/LuaTransformer.ts | 120 +++++++++--------- .../__snapshots__/transformation.spec.ts.snap | 8 +- 2 files changed, 62 insertions(+), 66 deletions(-) diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index eb39d6b9a..a6c040193 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -887,7 +887,7 @@ export class LuaTransformer { tstl.createStringLiteral("__index") ); if (tsHelper.hasGetAccessorInClassOrAncestor(statement, false, this.checker)) { - // localClassName.prototype.__index = __TS_Index(localClassName.prototype) + // localClassName.prototype.__index = __TS__Index(localClassName.prototype) const assignClassPrototypeIndex = tstl.createAssignmentStatement( classPrototypeIndex, this.transformLuaLibFunction(LuaLibFeature.Index, undefined, createClassPrototype()), @@ -919,7 +919,7 @@ export class LuaTransformer { } if (tsHelper.hasSetAccessorInClassOrAncestor(statement, false, this.checker)) { - // localClassName.prototype.__newindex = __TS_NewIndex(localClassName.prototype) + // localClassName.prototype.__newindex = __TS__NewIndex(localClassName.prototype) const classPrototypeNewIndex = tstl.createTableIndexExpression( createClassPrototype(), tstl.createStringLiteral("__newindex") @@ -1388,11 +1388,11 @@ export class LuaTransformer { continue; } - // Binding patterns become ____TS_bindingPattern0, ____TS_bindingPattern1, etc as function parameters + // Binding patterns become ____bindingPattern0, ____bindingPattern1, etc as function parameters // See transformFunctionBody for how these values are destructured const paramName = ts.isObjectBindingPattern(param.name) || ts.isArrayBindingPattern(param.name) - ? tstl.createIdentifier(`____TS_bindingPattern${identifierIndex++}`) + ? tstl.createIdentifier(`____bindingPattern${identifierIndex++}`) : this.transformIdentifier(param.name as ts.Identifier); // This parameter is a spread parameter (...param) @@ -1441,7 +1441,7 @@ export class LuaTransformer { let bindPatternIndex = 0; for (const declaration of parameters) { if (ts.isObjectBindingPattern(declaration.name) || ts.isArrayBindingPattern(declaration.name)) { - const identifier = tstl.createIdentifier(`____TS_bindingPattern${bindPatternIndex++}`); + const identifier = tstl.createIdentifier(`____bindingPattern${bindPatternIndex++}`); if (declaration.initializer !== undefined) { // Default binding parameter headerStatements.push( @@ -2336,14 +2336,14 @@ export class LuaTransformer { // Declaration of new variable const variables = statement.initializer.declarations[0].name; if (ts.isArrayBindingPattern(variables) || ts.isObjectBindingPattern(variables)) { - valueVariable = tstl.createIdentifier("____TS_values"); + valueVariable = tstl.createIdentifier("____values"); block.statements.unshift(this.transformForOfInitializer(statement.initializer, valueVariable)); } else { valueVariable = this.transformIdentifier(variables); } } else { // Assignment to existing variable - valueVariable = tstl.createIdentifier("____TS_value"); + valueVariable = tstl.createIdentifier("____value"); block.statements.unshift(this.transformForOfInitializer(statement.initializer, valueVariable)); } @@ -2387,12 +2387,10 @@ export class LuaTransformer { } } else { // Variables NOT declared in for loop - catch iterator values in temps and assign - // for ____TS_value0 in ${iterable} do - // ${initializer} = ____TS_value0 + // for ____value0 in ${iterable} do + // ${initializer} = ____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(`____value${i}`)); const assign = tstl.createAssignmentStatement( statement.initializer.elements.map( e => this.transformExpression(e) as tstl.AssignmentLeftHandSideExpression @@ -2421,9 +2419,9 @@ export class LuaTransformer { ); } else { // Destructuring or variable NOT declared in for loop - // for ____TS_value in ${iterator} do - // local ${initializer} = unpack(____TS_value) - const valueVariable = tstl.createIdentifier("____TS_value"); + // for ____value in ${iterator} do + // local ${initializer} = unpack(____value) + const valueVariable = tstl.createIdentifier("____value"); const initializer = this.transformForOfInitializer(statement.initializer, valueVariable); block.statements.splice(0, 0, initializer); return tstl.createForInStatement(block, [valueVariable], [luaIterator]); @@ -2446,9 +2444,9 @@ export class LuaTransformer { ); } else { // Destructuring or variable NOT declared in for loop - // for ____TS_value in __TS__iterator(${iterator}) do - // local ${initializer} = ____TS_value - const valueVariable = tstl.createIdentifier("____TS_value"); + // for ____value in __TS__iterator(${iterator}) do + // local ${initializer} = ____value + const valueVariable = tstl.createIdentifier("____value"); const initializer = this.transformForOfInitializer(statement.initializer, valueVariable); block.statements.splice(0, 0, initializer); return tstl.createForInStatement( @@ -2556,7 +2554,7 @@ export class LuaTransformer { if (scope === undefined) { throw TSTLErrors.UndefinedScope(); } - const switchName = `____TS_switch${scope.id}`; + const switchName = `____switch${scope.id}`; const expression = this.transformExpression(statement.expression); const switchVariable = tstl.createIdentifier(switchName); @@ -2612,7 +2610,7 @@ export class LuaTransformer { } if (breakableScope.type === ScopeType.Switch) { - return tstl.createGotoStatement(`____TS_switch${breakableScope.id}_end`); + return tstl.createGotoStatement(`____switch${breakableScope.id}_end`); } else { return tstl.createBreakStatement(breakStatement); } @@ -2628,8 +2626,8 @@ export class LuaTransformer { public transformTryStatement(statement: ts.TryStatement): StatementVisitResult { const [tryBlock, tryScope] = this.transformScopeBlock(statement.tryBlock, ScopeType.Try); - const tryResultIdentfier = tstl.createIdentifier("____TS_try"); - const returnValueIdentifier = tstl.createIdentifier("____TS_returnValue"); + const tryResultIdentifier = tstl.createIdentifier("____try"); + const returnValueIdentifier = tstl.createIdentifier("____returnValue"); const result: tstl.Statement[] = []; @@ -2643,18 +2641,18 @@ export class LuaTransformer { // try with catch let [catchBlock, catchScope] = this.transformScopeBlock(statement.catchClause.block, ScopeType.Catch); if (statement.catchClause.variableDeclaration) { - // Replace ____TS_returned with catch variable + // Replace ____returned with catch variable returnedIdentifier = this.transformIdentifier(statement.catchClause.variableDeclaration .name as ts.Identifier); } else if (tryScope.functionReturned || catchScope.functionReturned) { - returnedIdentifier = tstl.createIdentifier("____TS_returned"); + returnedIdentifier = tstl.createIdentifier("____returned"); } - const tryReturnIdentifiers = [tryResultIdentfier]; // ____TS_try + const tryReturnIdentifiers = [tryResultIdentifier]; // ____try if (returnedIdentifier) { - tryReturnIdentifiers.push(returnedIdentifier); // ____TS_returned or catch variable + tryReturnIdentifiers.push(returnedIdentifier); // ____returned or catch variable if (tryScope.functionReturned || catchScope.functionReturned) { - tryReturnIdentifiers.push(returnValueIdentifier); // ____TS_returnValue + tryReturnIdentifiers.push(returnValueIdentifier); // ____returnValue returnCondition = tstl.cloneIdentifier(returnedIdentifier); } } @@ -2672,19 +2670,19 @@ export class LuaTransformer { catchBlock = tstl.createBlock([catchAssign]); } const notTryCondition = tstl.createUnaryExpression( - tstl.createParenthesizedExpression(tryResultIdentfier), + tstl.createParenthesizedExpression(tryResultIdentifier), tstl.SyntaxKind.NotOperator ); result.push(tstl.createIfStatement(notTryCondition, catchBlock)); } else if (tryScope.functionReturned) { // try with return, but no catch - returnedIdentifier = tstl.createIdentifier("____TS_returned"); - const returnedVariables = [tryResultIdentfier, returnedIdentifier, returnValueIdentifier]; + returnedIdentifier = tstl.createIdentifier("____returned"); + const returnedVariables = [tryResultIdentifier, returnedIdentifier, returnValueIdentifier]; result.push(tstl.createVariableDeclarationStatement(returnedVariables, tryCall)); - // change return condition from '____TS_returned' to '____TS_try and ____TS_returned' + // change return condition from '____returned' to '____try and ____returned' returnCondition = tstl.createBinaryExpression( - tstl.cloneIdentifier(tryResultIdentfier), + tstl.cloneIdentifier(tryResultIdentifier), returnedIdentifier, tstl.SyntaxKind.AndOperator ); @@ -2699,9 +2697,9 @@ export class LuaTransformer { if (returnCondition && returnedIdentifier) { // With catch clause: - // if ____TS_returned then return ____TS_returnValue end + // if ____returned then return ____returnValue end // No catch clause: - // if ____TS_try and ____TS_returned then return ____TS_returnValue end + // if ____try and ____returned then return ____returnValue end const returnValues: tstl.Expression[] = []; const parentTryCatch = this.findScope(ScopeType.Function | ScopeType.Try | ScopeType.Catch); if (parentTryCatch && parentTryCatch.type !== ScopeType.Function) { @@ -3083,7 +3081,7 @@ export class LuaTransformer { } else { right = [this.createUnpackCall(this.transformExpression(expression.right), expression.right)]; } - const tmps = left.map((_, i) => tstl.createIdentifier(`____TS_tmp${i}`)); + const tmps = left.map((_, i) => tstl.createIdentifier(`____tmp${i}`)); const statements: tstl.Statement[] = [ tstl.createVariableDeclarationStatement(tmps, right), tstl.createAssignmentStatement(left as tstl.AssignmentLeftHandSideExpression[], tmps), @@ -3153,28 +3151,28 @@ export class LuaTransformer { ); if (hasEffects && objExpression && indexExpression) { // Complex property/element accesses need to cache object/index expressions to avoid repeating side-effects - // local __TS_obj, __TS_index = ${objExpression}, ${indexExpression}; - const obj = tstl.createIdentifier("____TS_obj"); - const index = tstl.createIdentifier("____TS_index"); + // local __obj, __index = ${objExpression}, ${indexExpression}; + const obj = tstl.createIdentifier("____obj"); + const index = tstl.createIdentifier("____index"); const objAndIndexDeclaration = tstl.createVariableDeclarationStatement( [obj, index], [this.transformExpression(objExpression), this.transformExpression(indexExpression)] ); const accessExpression = tstl.createTableIndexExpression(obj, index); - const tmp = tstl.createIdentifier("____TS_tmp"); + const tmp = tstl.createIdentifier("____tmp"); right = tstl.createParenthesizedExpression(right); let tmpDeclaration: tstl.VariableDeclarationStatement; let assignStatement: tstl.AssignmentStatement; if (isPostfix) { - // local ____TS_tmp = ____TS_obj[____TS_index]; - // ____TS_obj[____TS_index] = ____TS_tmp ${replacementOperator} ${right}; + // local ____tmp = ____obj[____index]; + // ____obj[____index] = ____tmp ${replacementOperator} ${right}; tmpDeclaration = tstl.createVariableDeclarationStatement(tmp, accessExpression); const operatorExpression = this.transformBinaryOperation(tmp, right, replacementOperator, expression); assignStatement = tstl.createAssignmentStatement(accessExpression, operatorExpression); } else { - // local ____TS_tmp = ____TS_obj[____TS_index] ${replacementOperator} ${right}; - // ____TS_obj[____TS_index] = ____TS_tmp; + // local ____tmp = ____obj[____index] ${replacementOperator} ${right}; + // ____obj[____index] = ____tmp; const operatorExpression = this.transformBinaryOperation( accessExpression, right, @@ -3184,7 +3182,7 @@ export class LuaTransformer { tmpDeclaration = tstl.createVariableDeclarationStatement(tmp, operatorExpression); assignStatement = tstl.createAssignmentStatement(accessExpression, tmp); } - // return ____TS_tmp + // return ____tmp return this.createImmediatelyInvokedFunctionExpression( [objAndIndexDeclaration, tmpDeclaration, assignStatement], tmp, @@ -3192,10 +3190,10 @@ export class LuaTransformer { ); } else if (isPostfix) { // Postfix expressions need to cache original value in temp - // local ____TS_tmp = ${left}; - // ${left} = ____TS_tmp ${replacementOperator} ${right}; - // return ____TS_tmp - const tmpIdentifier = tstl.createIdentifier("____TS_tmp"); + // local ____tmp = ${left}; + // ${left} = ____tmp ${replacementOperator} ${right}; + // return ____tmp + const tmpIdentifier = tstl.createIdentifier("____tmp"); const tmpDeclaration = tstl.createVariableDeclarationStatement(tmpIdentifier, left); const operatorExpression = this.transformBinaryOperation( tmpIdentifier, @@ -3211,10 +3209,10 @@ export class LuaTransformer { ); } else if (ts.isPropertyAccessExpression(lhs) || ts.isElementAccessExpression(lhs)) { // Simple property/element access expressions need to cache in temp to avoid double-evaluation - // local ____TS_tmp = ${left} ${replacementOperator} ${right}; - // ${left} = ____TS_tmp; - // return ____TS_tmp - const tmpIdentifier = tstl.createIdentifier("____TS_tmp"); + // local ____tmp = ${left} ${replacementOperator} ${right}; + // ${left} = ____tmp; + // return ____tmp + const tmpIdentifier = tstl.createIdentifier("____tmp"); const operatorExpression = this.transformBinaryOperation(left, right, replacementOperator, expression); const tmpDeclaration = tstl.createVariableDeclarationStatement(tmpIdentifier, operatorExpression); const assignStatement = this.transformAssignment(lhs, tmpIdentifier); @@ -3321,10 +3319,10 @@ export class LuaTransformer { ); if (hasEffects && objExpression && indexExpression) { // Complex property/element accesses need to cache object/index expressions to avoid repeating side-effects - // local __TS_obj, __TS_index = ${objExpression}, ${indexExpression}; - // ____TS_obj[____TS_index] = ____TS_obj[____TS_index] ${replacementOperator} ${right}; - const obj = tstl.createIdentifier("____TS_obj"); - const index = tstl.createIdentifier("____TS_index"); + // local __obj, __index = ${objExpression}, ${indexExpression}; + // ____obj[____index] = ____obj[____index] ${replacementOperator} ${right}; + const obj = tstl.createIdentifier("____obj"); + const index = tstl.createIdentifier("____index"); const objAndIndexDeclaration = tstl.createVariableDeclarationStatement( [obj, index], [this.transformExpression(objExpression), this.transformExpression(indexExpression)] @@ -3991,14 +3989,14 @@ export class LuaTransformer { const context = this.transformExpression(left.expression); if (tsHelper.isExpressionWithEvaluationEffect(left.expression)) { // Inject context parameter - transformedArguments.unshift(tstl.createIdentifier("____TS_self")); + transformedArguments.unshift(tstl.createIdentifier("____self")); // Cache left-side if it has effects - //(function() local ____TS_self = context; return ____TS_self[argument](parameters); end)() + //(function() local ____self = context; return ____self[argument](parameters); end)() const argument = ts.isElementAccessExpression(left) ? this.transformElementAccessArgument(left) : tstl.createStringLiteral(left.name.text); - const selfIdentifier = tstl.createIdentifier("____TS_self"); + const selfIdentifier = tstl.createIdentifier("____self"); const selfAssignment = tstl.createVariableDeclarationStatement(selfIdentifier, context); const index = tstl.createTableIndexExpression(selfIdentifier, argument); const callExpression = tstl.createCallExpression(index, transformedArguments); @@ -4894,9 +4892,7 @@ export class LuaTransformer { } } - const text = this.hasUnsafeIdentifierName(identifier) - ? this.createSafeName(identifier.text) - : identifier.text; + const text = this.hasUnsafeIdentifierName(identifier) ? this.createSafeName(identifier.text) : identifier.text; const symbolId = this.getIdentifierSymbolId(identifier); return tstl.createIdentifier(text, identifier, symbolId, identifier.text); diff --git a/test/translation/__snapshots__/transformation.spec.ts.snap b/test/translation/__snapshots__/transformation.spec.ts.snap index dfc23372a..e0d8bed84 100644 --- a/test/translation/__snapshots__/transformation.spec.ts.snap +++ b/test/translation/__snapshots__/transformation.spec.ts.snap @@ -562,12 +562,12 @@ f = function(____, x) return ({x = x}) end" exports[`Transformation (tryCatch) 1`] = ` "do - local ____TS_try, er = pcall( + local ____try, er = pcall( function() local a = 42 end ) - if not ____TS_try then + if not ____try then local b = \\"fail\\" end end" @@ -575,12 +575,12 @@ end" exports[`Transformation (tryCatchFinally) 1`] = ` "do - local ____TS_try, er = pcall( + local ____try, er = pcall( function() local a = 42 end ) - if not ____TS_try then + if not ____try then local b = \\"fail\\" end do From b4e7f009d64835f9fb3412b984f6e92379798efe Mon Sep 17 00:00:00 2001 From: ark120202 Date: Tue, 9 Jul 2019 01:23:20 +0500 Subject: [PATCH 11/14] Revert "Remove function assignment validation in type assertion" This reverts commit f17da36e6c32aded58fc1f95ce8ee489f09bc078. --- src/LuaTransformer.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index a6c040193..125e7e493 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -4745,6 +4745,11 @@ export class LuaTransformer { } public transformAssertionExpression(expression: ts.AssertionExpression): ExpressionVisitResult { + this.validateFunctionAssignment( + expression, + this.checker.getTypeAtLocation(expression.expression), + this.checker.getTypeAtLocation(expression.type) + ); return this.transformExpression(expression.expression); } From eb7cca73f6991a7186b2a417384eac6163559215 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Tue, 9 Jul 2019 01:24:53 +0500 Subject: [PATCH 12/14] Add line break before constructor --- src/Decorator.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Decorator.ts b/src/Decorator.ts index 330685202..107676b0d 100644 --- a/src/Decorator.ts +++ b/src/Decorator.ts @@ -10,6 +10,7 @@ export class Decorator { } public kind: DecoratorKind; + constructor(name: string, public args: string[]) { const kind = Decorator.getDecoratorKind(name); if (kind === undefined) { From 1ad7f81d3456f75760138f4328d9c0668cb2db37 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Tue, 9 Jul 2019 01:49:37 +0500 Subject: [PATCH 13/14] Replace __TSTL_ with 4 underscores --- src/LuaTransformer.ts | 4 +- .../__snapshots__/transformation.spec.ts.snap | 62 +++++++++---------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/LuaTransformer.ts b/src/LuaTransformer.ts index 125e7e493..48ee3734e 100644 --- a/src/LuaTransformer.ts +++ b/src/LuaTransformer.ts @@ -319,7 +319,7 @@ export class LuaTransformer { } const moduleRequire = this.createModuleRequire(statement.moduleSpecifier as ts.StringLiteral); - const tempModuleIdentifier = tstl.createIdentifier("__TSTL_export"); + const tempModuleIdentifier = tstl.createIdentifier("____export"); const declaration = tstl.createVariableDeclarationStatement(tempModuleIdentifier, moduleRequire); @@ -404,7 +404,7 @@ export class LuaTransformer { return undefined; } - const tstlIdentifier = (name: string) => "__TSTL_" + tsHelper.fixInvalidLuaIdentifier(name); + const tstlIdentifier = (name: string) => "____" + tsHelper.fixInvalidLuaIdentifier(name); const importUniqueName = tstl.createIdentifier(tstlIdentifier(path.basename(importPath))); const requireStatement = tstl.createVariableDeclarationStatement( tstl.createIdentifier(tstlIdentifier(path.basename(importPath))), diff --git a/test/translation/__snapshots__/transformation.spec.ts.snap b/test/translation/__snapshots__/transformation.spec.ts.snap index e0d8bed84..c77a614ca 100644 --- a/test/translation/__snapshots__/transformation.spec.ts.snap +++ b/test/translation/__snapshots__/transformation.spec.ts.snap @@ -198,21 +198,21 @@ local xyz = 4 ____exports.xyz = xyz ____exports.uwv = xyz do - local __TSTL_export = require(\\"xyz\\") - for ____exportKey, ____exportValue in pairs(__TSTL_export) do + local ____export = require(\\"xyz\\") + for ____exportKey, ____exportValue in pairs(____export) do ____exports[____exportKey] = ____exportValue end end do - local __TSTL_xyz = require(\\"xyz\\") - local abc = __TSTL_xyz.abc - local def = __TSTL_xyz.def + local ____xyz = require(\\"xyz\\") + local abc = ____xyz.abc + local def = ____xyz.def ____exports.abc = abc ____exports.def = def end do - local __TSTL_xyz = require(\\"xyz\\") - local def = __TSTL_xyz.abc + local ____xyz = require(\\"xyz\\") + local def = ____xyz.abc ____exports.def = def end return ____exports" @@ -371,22 +371,22 @@ local ____ = Test" `; exports[`Transformation (modulesImportNamed) 1`] = ` -"local __TSTL_test = require(\\"test\\") -local TestClass = __TSTL_test.TestClass +"local ____test = require(\\"test\\") +local TestClass = ____test.TestClass local ____ = TestClass" `; exports[`Transformation (modulesImportNamedSpecialChars) 1`] = ` -"local __TSTL_kebab_2Dmodule = require(\\"kebab-module\\") -local TestClass1 = __TSTL_kebab_2Dmodule.TestClass1 -local __TSTL_dollar_24module = require(\\"dollar$module\\") -local TestClass2 = __TSTL_dollar_24module.TestClass2 -local __TSTL_singlequote_27module = require(\\"singlequote'module\\") -local TestClass3 = __TSTL_singlequote_27module.TestClass3 -local __TSTL_hash_23module = require(\\"hash#module\\") -local TestClass4 = __TSTL_hash_23module.TestClass4 -local __TSTL_space_20module = require(\\"space module\\") -local TestClass5 = __TSTL_space_20module.TestClass5 +"local ____kebab_2Dmodule = require(\\"kebab-module\\") +local TestClass1 = ____kebab_2Dmodule.TestClass1 +local ____dollar_24module = require(\\"dollar$module\\") +local TestClass2 = ____dollar_24module.TestClass2 +local ____singlequote_27module = require(\\"singlequote'module\\") +local TestClass3 = ____singlequote_27module.TestClass3 +local ____hash_23module = require(\\"hash#module\\") +local TestClass4 = ____hash_23module.TestClass4 +local ____space_20module = require(\\"space module\\") +local TestClass5 = ____space_20module.TestClass5 local ____ = TestClass1 local ____ = TestClass2 local ____ = TestClass3 @@ -395,22 +395,22 @@ local ____ = TestClass5" `; exports[`Transformation (modulesImportRenamed) 1`] = ` -"local __TSTL_test = require(\\"test\\") -local RenamedClass = __TSTL_test.TestClass +"local ____test = require(\\"test\\") +local RenamedClass = ____test.TestClass local ____ = RenamedClass" `; exports[`Transformation (modulesImportRenamedSpecialChars) 1`] = ` -"local __TSTL_kebab_2Dmodule = require(\\"kebab-module\\") -local RenamedClass1 = __TSTL_kebab_2Dmodule.TestClass -local __TSTL_dollar_24module = require(\\"dollar$module\\") -local RenamedClass2 = __TSTL_dollar_24module.TestClass -local __TSTL_singlequote_27module = require(\\"singlequote'module\\") -local RenamedClass3 = __TSTL_singlequote_27module.TestClass -local __TSTL_hash_23module = require(\\"hash#module\\") -local RenamedClass4 = __TSTL_hash_23module.TestClass -local __TSTL_space_20module = require(\\"space module\\") -local RenamedClass5 = __TSTL_space_20module.TestClass +"local ____kebab_2Dmodule = require(\\"kebab-module\\") +local RenamedClass1 = ____kebab_2Dmodule.TestClass +local ____dollar_24module = require(\\"dollar$module\\") +local RenamedClass2 = ____dollar_24module.TestClass +local ____singlequote_27module = require(\\"singlequote'module\\") +local RenamedClass3 = ____singlequote_27module.TestClass +local ____hash_23module = require(\\"hash#module\\") +local RenamedClass4 = ____hash_23module.TestClass +local ____space_20module = require(\\"space module\\") +local RenamedClass5 = ____space_20module.TestClass local ____ = RenamedClass1 local ____ = RenamedClass2 local ____ = RenamedClass3 From c3aac655ccad4c6d8c4a177959eba50142773932 Mon Sep 17 00:00:00 2001 From: ark120202 Date: Tue, 9 Jul 2019 01:52:00 +0500 Subject: [PATCH 14/14] Remove outdated `Building & Tests` group from readme --- README.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/README.md b/README.md index 024e3ca3e..5fff008ac 100644 --- a/README.md +++ b/README.md @@ -65,16 +65,6 @@ The real power of this transpiler is usage together with good declarations for t - [Defold Game Engine Scripting](https://github.com/dasannikov/DefoldTypeScript/blob/master/defold.d.ts) - [LÖVE 2D Game Development](https://github.com/hazzard993/love-typescript-definitions) -## Building & Tests - -`npm run build` to build the project. - -`npm run test` to run tests. - -`npm run test-threaded` runs test in parallel, faster but less detailed output. - -`npm run coverage` or `npm run coverage-html` to generate a coverage report. - ## Sublime Text integration This compiler works great in combination with the [Sublime Text Typescript plugin](https://github.com/Microsoft/TypeScript-Sublime-Plugin) (available through the package manager as `TypeScript`).